From 370dc477b87b9678a056f6b46dc3a90f27b5b78d Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Thu, 3 Dec 2026 15:28:44 +0100 Subject: [PATCH 1/2] chore: remove the compute drivers migrated to desktop Delete the Docker, Podman and VM compute driver crates, the shared container-runtime crate, the VM scripts and tasks, the kernel release workflow and the Docker and Podman gateway configs. These now live in ai-openshell/desktop. Prune Cargo.lock and the deny.toml wrappers, and point the architecture table and driver docs at the new repository. Packaging, release workflows, e2e wrappers and tmachine still build or ship the driver binaries from core and are left for follow-up changes (#6042, #6044). Refs: #5200 Signed-off-by: Evan Lezar --- .github/workflows/release-vm-kernel.yml | 268 - AGENTS.md | 7 +- Cargo.lock | 744 +- crates/openshell-container-runtime/Cargo.toml | 24 - crates/openshell-container-runtime/README.md | 10 - crates/openshell-container-runtime/src/lib.rs | 9 - .../src/podman_socket.rs | 402 - crates/openshell-driver-docker/Cargo.toml | 62 - crates/openshell-driver-docker/README.md | 332 - .../src/image_update.rs | 1022 -- .../src/image_update/tests.rs | 1212 -- .../src/image_update/tests/live.rs | 268 - .../openshell-driver-docker/src/isolation.rs | 235 - crates/openshell-driver-docker/src/launch.rs | 120 - crates/openshell-driver-docker/src/lib.rs | 7576 -------- crates/openshell-driver-docker/src/main.rs | 132 - .../src/otel_tracing.rs | 19 - crates/openshell-driver-docker/src/serve.rs | 315 - crates/openshell-driver-docker/src/tests.rs | 4718 ----- .../openshell-driver-docker/src/workspace.rs | 806 - .../tests/fixtures/image-update/Dockerfile | 12 - .../tests/serve_configure.rs | 317 - crates/openshell-driver-podman/Cargo.toml | 66 - crates/openshell-driver-podman/NETWORKING.md | 66 - crates/openshell-driver-podman/README.md | 179 - crates/openshell-driver-podman/src/client.rs | 1533 -- crates/openshell-driver-podman/src/config.rs | 1453 -- .../openshell-driver-podman/src/container.rs | 4437 ----- crates/openshell-driver-podman/src/driver.rs | 5127 ------ crates/openshell-driver-podman/src/grpc.rs | 741 - .../openshell-driver-podman/src/isolation.rs | 649 - crates/openshell-driver-podman/src/lib.rs | 17 - crates/openshell-driver-podman/src/main.rs | 402 - .../src/otel_tracing.rs | 19 - crates/openshell-driver-podman/src/serve.rs | 271 - .../openshell-driver-podman/src/test_utils.rs | 145 - crates/openshell-driver-podman/src/watcher.rs | 1071 -- .../tests/podman_preflight.rs | 89 - .../tests/serve_configure.rs | 303 - crates/openshell-driver-vm/Cargo.toml | 140 - crates/openshell-driver-vm/README.md | 351 - crates/openshell-driver-vm/build.rs | 153 - crates/openshell-driver-vm/entitlements.plist | 8 - crates/openshell-driver-vm/runtime/README.md | 85 - .../runtime/kernel/openshell.kconfig | 51 - crates/openshell-driver-vm/runtime/pins.env | 33 - .../scripts/openshell-vm-sandbox-init.sh | 751 - .../src/bin/openshell-vm-init.rs | 240 - crates/openshell-driver-vm/src/driver.rs | 15154 ---------------- .../src/embedded_runtime.rs | 167 - .../openshell-driver-vm/src/extensions/mod.rs | 30 - crates/openshell-driver-vm/src/ffi.rs | 214 - crates/openshell-driver-vm/src/gpu.rs | 173 - .../openshell-driver-vm/src/isolation/mod.rs | 248 - .../openshell-driver-vm/src/layer_applier.rs | 913 - crates/openshell-driver-vm/src/lib.rs | 51 - crates/openshell-driver-vm/src/lifecycle.rs | 1241 -- crates/openshell-driver-vm/src/listener.rs | 271 - crates/openshell-driver-vm/src/main.rs | 893 - .../openshell-driver-vm/src/otel_tracing.rs | 19 - crates/openshell-driver-vm/src/preparation.rs | 1066 -- crates/openshell-driver-vm/src/procguard.rs | 197 - .../src/registry_cache_tests.rs | 680 - crates/openshell-driver-vm/src/rootfs.rs | 1891 -- crates/openshell-driver-vm/src/runtime.rs | 927 - crates/openshell-driver-vm/src/serve.rs | 378 - crates/openshell-driver-vm/src/settings.rs | 565 - .../tests/image_preparation.rs | 383 - .../tests/serve_configure.rs | 266 - deny.toml | 6 +- docs/extensibility/drivers.mdx | 6 +- docs/extensibility/overview.mdx | 4 +- e2e/configs/gateway/docker.toml | 28 - e2e/configs/gateway/podman.toml | 31 - tasks/scripts/vm/_lib.sh | 148 - tasks/scripts/vm/build-libkrun-macos.sh | 286 - tasks/scripts/vm/build-libkrun.sh | 458 - tasks/scripts/vm/build-supervisor-bundle.sh | 151 - tasks/scripts/vm/compress-vm-runtime.sh | 298 - tasks/scripts/vm/download-kernel-runtime.sh | 134 - tasks/scripts/vm/package-vm-runtime.sh | 158 - tasks/scripts/vm/smoke-orphan-cleanup.sh | 207 - tasks/scripts/vm/vm-setup.sh | 133 - tasks/vm.toml | 29 - 84 files changed, 45 insertions(+), 64749 deletions(-) delete mode 100644 .github/workflows/release-vm-kernel.yml delete mode 100644 crates/openshell-container-runtime/Cargo.toml delete mode 100644 crates/openshell-container-runtime/README.md delete mode 100644 crates/openshell-container-runtime/src/lib.rs delete mode 100644 crates/openshell-container-runtime/src/podman_socket.rs delete mode 100644 crates/openshell-driver-docker/Cargo.toml delete mode 100644 crates/openshell-driver-docker/README.md delete mode 100644 crates/openshell-driver-docker/src/image_update.rs delete mode 100644 crates/openshell-driver-docker/src/image_update/tests.rs delete mode 100644 crates/openshell-driver-docker/src/image_update/tests/live.rs delete mode 100644 crates/openshell-driver-docker/src/isolation.rs delete mode 100644 crates/openshell-driver-docker/src/launch.rs delete mode 100644 crates/openshell-driver-docker/src/lib.rs delete mode 100644 crates/openshell-driver-docker/src/main.rs delete mode 100644 crates/openshell-driver-docker/src/otel_tracing.rs delete mode 100644 crates/openshell-driver-docker/src/serve.rs delete mode 100644 crates/openshell-driver-docker/src/tests.rs delete mode 100644 crates/openshell-driver-docker/src/workspace.rs delete mode 100644 crates/openshell-driver-docker/tests/fixtures/image-update/Dockerfile delete mode 100644 crates/openshell-driver-docker/tests/serve_configure.rs delete mode 100644 crates/openshell-driver-podman/Cargo.toml delete mode 100644 crates/openshell-driver-podman/NETWORKING.md delete mode 100644 crates/openshell-driver-podman/README.md delete mode 100644 crates/openshell-driver-podman/src/client.rs delete mode 100644 crates/openshell-driver-podman/src/config.rs delete mode 100644 crates/openshell-driver-podman/src/container.rs delete mode 100644 crates/openshell-driver-podman/src/driver.rs delete mode 100644 crates/openshell-driver-podman/src/grpc.rs delete mode 100644 crates/openshell-driver-podman/src/isolation.rs delete mode 100644 crates/openshell-driver-podman/src/lib.rs delete mode 100644 crates/openshell-driver-podman/src/main.rs delete mode 100644 crates/openshell-driver-podman/src/otel_tracing.rs delete mode 100644 crates/openshell-driver-podman/src/serve.rs delete mode 100644 crates/openshell-driver-podman/src/test_utils.rs delete mode 100644 crates/openshell-driver-podman/src/watcher.rs delete mode 100644 crates/openshell-driver-podman/tests/podman_preflight.rs delete mode 100644 crates/openshell-driver-podman/tests/serve_configure.rs delete mode 100644 crates/openshell-driver-vm/Cargo.toml delete mode 100644 crates/openshell-driver-vm/README.md delete mode 100644 crates/openshell-driver-vm/build.rs delete mode 100644 crates/openshell-driver-vm/entitlements.plist delete mode 100644 crates/openshell-driver-vm/runtime/README.md delete mode 100644 crates/openshell-driver-vm/runtime/kernel/openshell.kconfig delete mode 100644 crates/openshell-driver-vm/runtime/pins.env delete mode 100644 crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh delete mode 100644 crates/openshell-driver-vm/src/bin/openshell-vm-init.rs delete mode 100644 crates/openshell-driver-vm/src/driver.rs delete mode 100644 crates/openshell-driver-vm/src/embedded_runtime.rs delete mode 100644 crates/openshell-driver-vm/src/extensions/mod.rs delete mode 100644 crates/openshell-driver-vm/src/ffi.rs delete mode 100644 crates/openshell-driver-vm/src/gpu.rs delete mode 100644 crates/openshell-driver-vm/src/isolation/mod.rs delete mode 100644 crates/openshell-driver-vm/src/layer_applier.rs delete mode 100644 crates/openshell-driver-vm/src/lib.rs delete mode 100644 crates/openshell-driver-vm/src/lifecycle.rs delete mode 100644 crates/openshell-driver-vm/src/listener.rs delete mode 100644 crates/openshell-driver-vm/src/main.rs delete mode 100644 crates/openshell-driver-vm/src/otel_tracing.rs delete mode 100644 crates/openshell-driver-vm/src/preparation.rs delete mode 100644 crates/openshell-driver-vm/src/procguard.rs delete mode 100644 crates/openshell-driver-vm/src/registry_cache_tests.rs delete mode 100644 crates/openshell-driver-vm/src/rootfs.rs delete mode 100644 crates/openshell-driver-vm/src/runtime.rs delete mode 100644 crates/openshell-driver-vm/src/serve.rs delete mode 100644 crates/openshell-driver-vm/src/settings.rs delete mode 100644 crates/openshell-driver-vm/tests/image_preparation.rs delete mode 100644 crates/openshell-driver-vm/tests/serve_configure.rs delete mode 100644 e2e/configs/gateway/docker.toml delete mode 100644 e2e/configs/gateway/podman.toml delete mode 100755 tasks/scripts/vm/_lib.sh delete mode 100755 tasks/scripts/vm/build-libkrun-macos.sh delete mode 100755 tasks/scripts/vm/build-libkrun.sh delete mode 100755 tasks/scripts/vm/build-supervisor-bundle.sh delete mode 100755 tasks/scripts/vm/compress-vm-runtime.sh delete mode 100755 tasks/scripts/vm/download-kernel-runtime.sh delete mode 100755 tasks/scripts/vm/package-vm-runtime.sh delete mode 100755 tasks/scripts/vm/smoke-orphan-cleanup.sh delete mode 100755 tasks/scripts/vm/vm-setup.sh delete mode 100644 tasks/vm.toml diff --git a/.github/workflows/release-vm-kernel.yml b/.github/workflows/release-vm-kernel.yml deleted file mode 100644 index deeff72a5c..0000000000 --- a/.github/workflows/release-vm-kernel.yml +++ /dev/null @@ -1,268 +0,0 @@ -name: Release VM Kernel - -# Build custom libkrunfw (kernel firmware) + libkrun (VMM) for all -# supported openshell-driver-vm platforms. Artifacts are uploaded to the -# rolling "vm-runtime" GitHub Release and consumed by normal dev/tag release -# workflows when building the openshell-driver-vm binary. -# -# The Linux kernel is compiled once on aarch64 Linux. The resulting kernel.c -# (a C source file containing the kernel as a byte array) is shared with the -# macOS job, which only needs to compile it into a .dylib — no krunvm, no -# Fedora VM, no kernel rebuild. This cuts macOS CI from ~45 min to ~5 min. -# -# This workflow runs on demand when kernel config or pins change. It is -# intentionally decoupled from the per-commit VM binary build because the -# kernel rarely changes and takes 15-45 minutes to compile. - -on: - workflow_dispatch: - -permissions: - contents: read - packages: read - -# Serialize runtime release updates. -concurrency: - group: vm-runtime-release - cancel-in-progress: false - -defaults: - run: - shell: bash - -jobs: - # --------------------------------------------------------------------------- - # Linux ARM64 — native kernel + libkrun build (also exports kernel.c) - # --------------------------------------------------------------------------- - build-runtime-linux-arm64: - name: Build Runtime (Linux ARM64) - runs-on: ubuntu-24.04-arm - timeout-minutes: 60 - container: - image: ghcr.io/ai-openshell/openshell/ci:82e753ba3ffdfb40c118e7cb416ced7f350381d5@sha256:d816f3b4b2de675928e2ecfd26ec6b937be35fe9986542c87d440bc3de5a29de - credentials: - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - options: --privileged - env: - MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Mark workspace safe for git - run: git config --global --add safe.directory "$GITHUB_WORKSPACE" - - - name: Build libkrunfw + libkrun from source - run: tasks/scripts/vm/build-libkrun.sh - - - name: Package runtime tarball - run: | - tasks/scripts/vm/package-vm-runtime.sh \ - --platform linux-aarch64 \ - --build-dir target/libkrun-build \ - --output artifacts/vm-runtime-linux-aarch64.tar.zst - - - name: Upload runtime artifact - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: vm-runtime-linux-arm64 - path: artifacts/vm-runtime-linux-aarch64.tar.zst - retention-days: 5 - - # Export kernel.c + ABI_VERSION for the macOS job. kernel.c contains - # the aarch64 Linux kernel as a byte array — it is OS-agnostic and can - # be compiled into a .dylib by Apple's cc without rebuilding the kernel. - - name: Upload kernel.c for macOS build - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: kernel-c-arm64 - path: | - target/libkrun-build/kernel.c - target/libkrun-build/ABI_VERSION - target/libkrun-build/provenance.json - retention-days: 1 - - # --------------------------------------------------------------------------- - # Linux AMD64 — native kernel + libkrun build - # --------------------------------------------------------------------------- - build-runtime-linux-amd64: - name: Build Runtime (Linux AMD64) - runs-on: ubuntu-24.04 - timeout-minutes: 60 - container: - image: ghcr.io/ai-openshell/openshell/ci:82e753ba3ffdfb40c118e7cb416ced7f350381d5@sha256:d816f3b4b2de675928e2ecfd26ec6b937be35fe9986542c87d440bc3de5a29de - credentials: - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - options: --privileged - env: - MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Mark workspace safe for git - run: git config --global --add safe.directory "$GITHUB_WORKSPACE" - - - name: Build libkrunfw + libkrun from source - run: tasks/scripts/vm/build-libkrun.sh - - - name: Package runtime tarball - run: | - tasks/scripts/vm/package-vm-runtime.sh \ - --platform linux-x86_64 \ - --build-dir target/libkrun-build \ - --output artifacts/vm-runtime-linux-x86_64.tar.zst - - - name: Upload artifact - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: vm-runtime-linux-amd64 - path: artifacts/vm-runtime-linux-x86_64.tar.zst - retention-days: 5 - - # --------------------------------------------------------------------------- - # macOS ARM64 — uses pre-built kernel.c from Linux ARM64 job - # --------------------------------------------------------------------------- - build-runtime-macos-arm64: - name: Build Runtime (macOS ARM64) - needs: [build-runtime-linux-arm64] - runs-on: macos-latest-xlarge - timeout-minutes: 30 - env: - RUSTC_WRAPPER: "" - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Install dependencies - run: | - set -euo pipefail - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.95.0 - echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" - brew install lld dtc xz - - - name: Download pre-built kernel.c - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: kernel-c-arm64 - path: target/kernel-artifact - - - name: Build libkrunfw + libkrun from pre-built kernel - run: tasks/scripts/vm/build-libkrun-macos.sh --kernel-dir target/kernel-artifact - - - name: Package runtime tarball - env: - CUSTOM_PROVENANCE_DIR: target/kernel-artifact - run: | - tasks/scripts/vm/package-vm-runtime.sh \ - --platform darwin-aarch64 \ - --build-dir target/libkrun-build \ - --output artifacts/vm-runtime-darwin-aarch64.tar.zst - - - name: Upload artifact - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: vm-runtime-macos-arm64 - path: artifacts/vm-runtime-darwin-aarch64.tar.zst - retention-days: 5 - - # --------------------------------------------------------------------------- - # Upload all runtime tarballs to the vm-runtime rolling release - # --------------------------------------------------------------------------- - release-kernel: - name: Release Kernel Runtime - needs: [build-runtime-linux-arm64, build-runtime-linux-amd64, build-runtime-macos-arm64] - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: write - id-token: write - attestations: write - artifact-metadata: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Download all runtime artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - pattern: vm-runtime-* - path: release/ - merge-multiple: true - - - name: Attest VM runtime artifacts - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 - with: - subject-path: | - release/vm-runtime-linux-aarch64.tar.zst - release/vm-runtime-linux-x86_64.tar.zst - release/vm-runtime-darwin-aarch64.tar.zst - - - name: Ensure vm-runtime tag exists - env: - RELEASE_TAG: vm-runtime - run: | - git config user.name "github-actions[bot]" - git config user.email "github-actions[bot]@users.noreply.github.com" - git tag -fa "$RELEASE_TAG" -m "VM Runtime Development Build" "${GITHUB_SHA}" - git push --force origin "$RELEASE_TAG" - - - name: Prune stale runtime assets from vm-runtime release - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 - env: - RELEASE_TAG: vm-runtime - with: - script: | - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - const tag = process.env.RELEASE_TAG; - let release; - try { - release = await github.rest.repos.getReleaseByTag({ owner, repo, tag }); - } catch (err) { - if (err.status === 404) { - core.info(`No existing ${tag} release; will create fresh.`); - return; - } - throw err; - } - // Delete old runtime assets, including removed checksum files. - for (const asset of release.data.assets) { - if (asset.name.startsWith('vm-runtime-')) { - core.info(`Deleting stale asset: ${asset.name}`); - await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id }); - } - } - - - name: Create / update vm-runtime GitHub Release - uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2 - with: - name: OpenShell VM Runtime - prerelease: true - tag_name: vm-runtime - target_commitish: ${{ github.sha }} - body: | - Build of the OpenShell VM runtime artifacts used by `openshell-driver-vm`. - - > **NOTE**: This is a development build. - - ### Kernel Runtime Artifacts - - Pre-built kernel runtime (libkrunfw + libkrun + umoci) for embedding - into the `openshell-driver-vm` binary. These are rebuilt on demand when the - kernel config or pinned dependency versions change. - - | Platform | Artifact | - |----------|----------| - | Linux ARM64 | `vm-runtime-linux-aarch64.tar.zst` | - | Linux x86_64 | `vm-runtime-linux-x86_64.tar.zst` | - | macOS ARM64 | `vm-runtime-darwin-aarch64.tar.zst` | - - ### Verify - - ```bash - gh release download vm-runtime -R ai-openshell/openshell -p vm-runtime-linux-x86_64.tar.zst - gh attestation verify vm-runtime-linux-x86_64.tar.zst -R ai-openshell/openshell - ``` - - files: | - release/vm-runtime-linux-aarch64.tar.zst - release/vm-runtime-linux-x86_64.tar.zst - release/vm-runtime-darwin-aarch64.tar.zst diff --git a/AGENTS.md b/AGENTS.md index 0133dd3de3..cd125c4655 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,10 +58,9 @@ Do not rely on this file for a full inventory. The detailed public and contribut | `crates/openshell-driver-vault/` | Vault credential driver | In-process `CredentialDriver` backend for Vault-compatible KV storage | | `crates/openshell-driver-db-credstore/` | Database credential driver | In-process `CredentialDriver` backend for gateway database credential storage | | `crates/openshell-driver-kubernetes/` | Kubernetes compute driver | In-process `ComputeDriver` backend for K8s sandbox pods | -| `crates/openshell-container-runtime/` | Container runtime helpers | Code used only by the desktop compute drivers (Docker, Podman, VM), starting with Podman socket discovery; moves with the drivers | -| `crates/openshell-driver-docker/` | Docker compute driver | Gateway-launched `ComputeDriver` subprocess for local Docker sandbox containers | -| `crates/openshell-driver-podman/` | Podman compute driver | Gateway-launched `ComputeDriver` subprocess for local Podman sandbox containers | -| `crates/openshell-driver-vm/` | VM compute driver | Standalone libkrun-backed `ComputeDriver` subprocess (embeds its own rootfs + runtime) | +| [`crates/openshell-driver-docker/`](https://github.com/ai-openshell/desktop/tree/main/crates/openshell-driver-docker) (`desktop` repository) | Docker compute driver | Gateway-launched `ComputeDriver` subprocess for local Docker sandbox containers | +| [`crates/openshell-driver-podman/`](https://github.com/ai-openshell/desktop/tree/main/crates/openshell-driver-podman) (`desktop` repository) | Podman compute driver | Gateway-launched `ComputeDriver` subprocess for local Podman sandbox containers | +| [`crates/openshell-driver-vm/`](https://github.com/ai-openshell/desktop/tree/main/crates/openshell-driver-vm) (`desktop` repository) | VM compute driver | Standalone libkrun-backed `ComputeDriver` subprocess | | [`crates/openshell-driver-mxc/`](https://github.com/ai-openshell/openshell/tree/windows/crates/openshell-driver-mxc) (`windows` branch) | Microsoft MXC compute driver | Native Windows ProcessContainer backend; see the Windows branch for the maintained implementation | | [`crates/openshell-mxc-boundary/`](https://github.com/ai-openshell/openshell/tree/windows/crates/openshell-mxc-boundary) (`windows` branch) | Windows sandbox boundary | Dedicated Windows workload boundary paired with the host supervisor | | `crates/openshell-prover/` | Policy prover | Policy verification and proof generation | diff --git a/Cargo.lock b/Cargo.lock index 988793659d..4e64d2e805 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -953,50 +953,6 @@ dependencies = [ "cipher", ] -[[package]] -name = "bollard" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee04c4c84f1f811b017f2fbb7dd8815c976e7ca98593de9c1e2afad0f636bff4" -dependencies = [ - "base64 0.22.1", - "bollard-stubs", - "bytes", - "futures-core", - "futures-util", - "hex", - "http 1.4.0", - "http-body-util", - "hyper", - "hyper-named-pipe", - "hyper-util", - "hyperlocal", - "log", - "openssh", - "pin-project-lite", - "serde", - "serde_derive", - "serde_json", - "serde_urlencoded", - "thiserror 2.0.20", - "tokio", - "tokio-util", - "tower-service", - "url", - "winapi", -] - -[[package]] -name = "bollard-stubs" -version = "1.52.1-rc.29.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f0a8ca8799131c1837d1282c3f81f31e76ceb0ce426e04a7fe1ccee3287c066" -dependencies = [ - "serde", - "serde_json", - "serde_repr", -] - [[package]] name = "borrow-or-share" version = "0.2.4" @@ -1178,12 +1134,6 @@ dependencies = [ "smol_str", ] -[[package]] -name = "cesu8" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" - [[package]] name = "cfg-if" version = "1.0.4" @@ -1332,15 +1282,6 @@ dependencies = [ "static_assertions", ] -[[package]] -name = "concurrent-queue" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" -dependencies = [ - "crossbeam-utils", -] - [[package]] name = "console" version = "0.15.11" @@ -1366,27 +1307,6 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" -[[package]] -name = "const_format" -version = "0.2.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" -dependencies = [ - "const_format_proc_macros", - "konst", -] - -[[package]] -name = "const_format_proc_macros" -version = "0.2.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - [[package]] name = "constant_time_eq" version = "0.6.1" @@ -1668,38 +1588,14 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "darling" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" -dependencies = [ - "darling_core 0.20.11", - "darling_macro 0.20.11", -] - [[package]] name = "darling" version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" dependencies = [ - "darling_core 0.24.1", - "darling_macro 0.24.1", -] - -[[package]] -name = "darling_core" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 2.0.117", + "darling_core", + "darling_macro", ] [[package]] @@ -1715,24 +1611,13 @@ dependencies = [ "syn 3.0.5", ] -[[package]] -name = "darling_macro" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" -dependencies = [ - "darling_core 0.20.11", - "quote", - "syn 2.0.117", -] - [[package]] name = "darling_macro" version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ - "darling_core 0.24.1", + "darling_core", "quote", "syn 3.0.5", ] @@ -1887,37 +1772,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "derive_builder" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" -dependencies = [ - "derive_builder_macro", -] - -[[package]] -name = "derive_builder_core" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" -dependencies = [ - "darling 0.20.11", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "derive_builder_macro" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" -dependencies = [ - "derive_builder_core", - "syn 2.0.117", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -2613,18 +2467,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "getset" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf0fc11e47561d47397154977bc219f4cf809b2974facc3ccb3b89e2436f912" -dependencies = [ - "proc-macro-error2", - "proc-macro2", - "quote", - "syn 2.0.117", -] - [[package]] name = "ghash" version = "0.6.0" @@ -2807,7 +2649,7 @@ dependencies = [ "data-encoding", "idna", "ipnet", - "jni 0.22.4", + "jni", "once_cell", "rand 0.10.2", "ring", @@ -2876,15 +2718,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-auth" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "150fa4a9462ef926824cf4519c84ed652ca8f4fbae34cb8af045b5cbcaf98822" -dependencies = [ - "memchr", -] - [[package]] name = "http-body" version = "0.4.6" @@ -2965,21 +2798,6 @@ dependencies = [ "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", - "hyper-util", - "pin-project-lite", - "tokio", - "tower-service", - "winapi", -] - [[package]] name = "hyper-rustls" version = "0.27.9" @@ -3035,21 +2853,6 @@ dependencies = [ "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", - "hyper-util", - "pin-project-lite", - "tokio", - "tower-service", -] - [[package]] name = "iana-time-zone" version = "0.1.65" @@ -3289,7 +3092,7 @@ version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c3b5acc1e2fd9375041a388da33d1eb8aed5f7a8c0dd3543e3ea2805adfbe20" dependencies = [ - "darling 0.24.1", + "darling", "indoc", "proc-macro2", "quote", @@ -3462,22 +3265,6 @@ dependencies = [ "jiff-tzdb 1.0.0", ] -[[package]] -name = "jni" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" -dependencies = [ - "cesu8", - "cfg-if", - "combine", - "jni-sys 0.3.1", - "log", - "thiserror 1.0.69", - "walkdir", - "windows-sys 0.45.0", -] - [[package]] name = "jni" version = "0.22.4" @@ -3487,7 +3274,7 @@ dependencies = [ "cfg-if", "combine", "jni-macros", - "jni-sys 0.4.1", + "jni-sys", "log", "simd_cesu8", "thiserror 2.0.20", @@ -3508,15 +3295,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "jni-sys" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" -dependencies = [ - "jni-sys 0.4.1", -] - [[package]] name = "jni-sys" version = "0.4.1" @@ -3626,7 +3404,7 @@ dependencies = [ "regex", "serde", "serde_json", - "strum 0.28.0", + "strum", "unicode-general-category", "uuid-simd", ] @@ -3735,21 +3513,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "konst" -version = "0.2.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" -dependencies = [ - "konst_macro_rules", -] - -[[package]] -name = "konst_macro_rules" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" - [[package]] name = "kqueue" version = "1.2.0" @@ -3807,7 +3570,7 @@ dependencies = [ "pem 4.0.0", "percent-encoding", "rustls", - "rustls-platform-verifier 0.7.1", + "rustls-platform-verifier", "secrecy", "serde", "serde-saphyr", @@ -3845,7 +3608,7 @@ version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cedc991dbe7757a646098dead35e070e13ce66e2996b02162ac7f97eb97f4d6e" dependencies = [ - "darling 0.24.1", + "darling", "proc-macro2", "quote", "serde", @@ -3953,16 +3716,6 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" -[[package]] -name = "libloading" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" -dependencies = [ - "cfg-if", - "windows-link", -] - [[package]] name = "libm" version = "0.2.16" @@ -4612,7 +4365,7 @@ dependencies = [ "getrandom 0.2.17", "http 1.4.0", "rand 0.8.6", - "reqwest 0.12.28", + "reqwest", "serde", "serde_json", "serde_path_to_error", @@ -4657,49 +4410,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "oci-client" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b7f8deaffcd3b0e3baf93dddcab3d18b91d46dc37d38a8b170089b234de5bb3" -dependencies = [ - "bytes", - "chrono", - "futures-util", - "http 1.4.0", - "http-auth", - "jsonwebtoken", - "lazy_static", - "oci-spec", - "olpc-cjson", - "regex", - "reqwest 0.13.2", - "serde", - "serde_json", - "sha2 0.10.9", - "thiserror 2.0.20", - "tokio", - "tracing", - "unicase", -] - -[[package]] -name = "oci-spec" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8445a2631507cec628a15fdd6154b54a3ab3f20ed4fe9d73a3b8b7a4e1ba03a" -dependencies = [ - "const_format", - "derive_builder", - "getset", - "regex", - "serde", - "serde_json", - "strum 0.27.2", - "strum_macros 0.27.2", - "thiserror 2.0.20", -] - [[package]] name = "oid-registry" version = "0.7.1" @@ -4718,17 +4428,6 @@ dependencies = [ "asn1-rs 0.7.2", ] -[[package]] -name = "olpc-cjson" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "696183c9b5fe81a7715d074fd632e8bd46f4ccc0231a3ed7fc580a80de5f7083" -dependencies = [ - "serde", - "serde_json", - "unicode-normalization", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -4808,7 +4507,7 @@ dependencies = [ "prost", "prost-types", "rcgen", - "reqwest 0.12.28", + "reqwest", "russh", "rustls", "serde", @@ -4827,16 +4526,6 @@ dependencies = [ "wiremock", ] -[[package]] -name = "openshell-container-runtime" -version = "0.0.0" -dependencies = [ - "nix 0.29.0", - "openshell-core", - "rustix 1.1.6", - "serde_json", -] - [[package]] name = "openshell-core" version = "0.0.0" @@ -4861,7 +4550,7 @@ dependencies = [ "prost-types", "protoc-bin-vendored", "rcgen", - "reqwest 0.12.28", + "reqwest", "rustix 1.1.6", "rustls", "serde", @@ -4905,7 +4594,7 @@ dependencies = [ "openshell-driver-vault", "prost-types", "rcgen", - "reqwest 0.12.28", + "reqwest", "rustix 1.1.6", "rustls", "serde", @@ -4962,47 +4651,6 @@ dependencies = [ "tonic", ] -[[package]] -name = "openshell-driver-docker" -version = "0.0.0" -dependencies = [ - "bollard", - "bytes", - "clap", - "futures", - "http 1.4.0", - "hyper-util", - "libc", - "miette", - "openshell-core", - "openshell-driver-sdk", - "openshell-isolation-interface", - "openshell-otel", - "openshell-otel-test-support", - "openshell-sandbox-backend", - "opentelemetry", - "opentelemetry_sdk", - "prost-types", - "rand 0.9.4", - "rustix 1.1.6", - "serde", - "serde_json", - "sha2 0.10.9", - "tar", - "temp-env", - "tempfile", - "tokio", - "tokio-stream", - "toml", - "tonic", - "tower", - "tower-http 0.6.8", - "tracing", - "tracing-opentelemetry", - "tracing-subscriber", - "url", -] - [[package]] name = "openshell-driver-kubernetes" version = "0.0.0" @@ -5074,83 +4722,38 @@ name = "openshell-driver-launch" version = "0.0.0" dependencies = [ "http 1.4.0", - "prost", - "protoc-bin-vendored", - "tokio", - "tokio-stream", - "tonic", - "tonic-prost", - "tonic-prost-build", - "tower", -] - -[[package]] -name = "openshell-driver-mxc" -version = "0.0.0" -dependencies = [ - "base64 0.22.1", - "futures", - "noyalib", - "openshell-core", - "openshell-crypto", - "openshell-ocsf", - "openshell-policy", - "openshell-supervisor-network", - "serde", - "serde_json", - "tempfile", - "thiserror 2.0.20", + "prost", + "protoc-bin-vendored", "tokio", "tokio-stream", "tonic", - "tracing", - "uuid", - "windows", + "tonic-prost", + "tonic-prost-build", + "tower", ] [[package]] -name = "openshell-driver-podman" +name = "openshell-driver-mxc" version = "0.0.0" dependencies = [ - "clap", + "base64 0.22.1", "futures", - "http 1.4.0", - "http-body-util", - "hyper", - "hyper-util", - "miette", - "nix 0.29.0", - "openshell-container-runtime", + "noyalib", "openshell-core", "openshell-crypto", - "openshell-driver-sdk", - "openshell-isolation-interface", - "openshell-otel", - "openshell-otel-test-support", - "openshell-sandbox-backend", - "opentelemetry", - "opentelemetry_sdk", - "prost-types", - "rcgen", - "rustix 1.1.6", + "openshell-ocsf", + "openshell-policy", + "openshell-supervisor-network", "serde", "serde_json", - "sha2 0.10.9", - "tar", - "temp-env", "tempfile", "thiserror 2.0.20", "tokio", "tokio-stream", - "toml", "tonic", - "tower", - "tower-http 0.6.8", "tracing", - "tracing-opentelemetry", - "tracing-subscriber", - "url", "uuid", + "windows", ] [[package]] @@ -5182,7 +4785,7 @@ dependencies = [ "openshell-core", "openshell-crypto", "rcgen", - "reqwest 0.12.28", + "reqwest", "rustls", "serde", "serde_json", @@ -5198,59 +4801,6 @@ dependencies = [ "wiremock", ] -[[package]] -name = "openshell-driver-vm" -version = "0.0.0" -dependencies = [ - "base64 0.22.1", - "bollard", - "clap", - "flate2", - "futures", - "http 1.4.0", - "hyper-util", - "libc", - "libloading", - "miette", - "nix 0.29.0", - "oci-client", - "openshell-container-runtime", - "openshell-core", - "openshell-crypto", - "openshell-driver-launch", - "openshell-driver-sdk", - "openshell-isolation-interface", - "openshell-otel", - "openshell-otel-test-support", - "openshell-policy", - "openshell-sandbox-backend", - "openshell-vfio", - "opentelemetry", - "opentelemetry_sdk", - "polling", - "prost", - "prost-types", - "rcgen", - "rustix 1.1.6", - "serde", - "serde_json", - "sha2 0.10.9", - "tar", - "temp-env", - "tempfile", - "tokio", - "tokio-stream", - "toml", - "tonic", - "tower", - "tower-http 0.6.8", - "tracing", - "tracing-opentelemetry", - "tracing-subscriber", - "url", - "zstd", -] - [[package]] name = "openshell-extension-core" version = "0.0.0" @@ -5666,7 +5216,7 @@ dependencies = [ "oauth2", "openshell-core", "openshell-crypto", - "reqwest 0.12.28", + "reqwest", "rustls", "serde", "serde_json", @@ -5745,7 +5295,7 @@ dependencies = [ "rand 0.10.2", "rand 0.9.4", "rcgen", - "reqwest 0.12.28", + "reqwest", "rsa", "russh", "rustix 1.1.6", @@ -5966,7 +5516,7 @@ dependencies = [ "prost-types", "rcgen", "regorus", - "reqwest 0.12.28", + "reqwest", "rustix 1.1.6", "rustls", "rustls-native-certs", @@ -6055,20 +5605,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "openssh" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d534c4bfecb0ed71dea4db444a5922a294d15cf40e700548f27295e1feb0ef18" -dependencies = [ - "libc", - "once_cell", - "shell-escape", - "tempfile", - "thiserror 2.0.20", - "tokio", -] - [[package]] name = "openssl" version = "0.10.81" @@ -6657,20 +6193,6 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" -[[package]] -name = "polling" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" -dependencies = [ - "cfg-if", - "concurrent-queue", - "hermit-abi", - "pin-project-lite", - "rustix 1.1.6", - "windows-sys 0.61.2", -] - [[package]] name = "poly1305" version = "0.9.1" @@ -6792,28 +6314,6 @@ dependencies = [ "wnaf", ] -[[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.117", -] - [[package]] name = "proc-macro2" version = "1.0.106" @@ -7024,7 +6524,6 @@ version = "0.11.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04759210543be93709136e28212294a659ef5001836ff4eab4d663e4529bba83" dependencies = [ - "aws-lc-rs", "bytes", "getrandom 0.4.2", "lru-slab", @@ -7200,7 +6699,7 @@ dependencies = [ "lru", "palette", "serde", - "strum 0.28.0", + "strum", "thiserror 2.0.20", "unicode-segmentation", "unicode-truncate", @@ -7254,7 +6753,7 @@ dependencies = [ "line-clipping", "ratatui-core", "serde", - "strum 0.28.0", + "strum", "time", "unicode-segmentation", "unicode-width 0.2.2", @@ -7442,47 +6941,6 @@ dependencies = [ "webpki-roots", ] -[[package]] -name = "reqwest" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab3f43e3283ab1488b624b44b0e988d0acea0b3214e694730a055cb6b2efa801" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-core", - "futures-util", - "http 1.4.0", - "http-body 1.0.1", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-pki-types", - "rustls-platform-verifier 0.6.2", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tokio-util", - "tower", - "tower-http 0.6.8", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-streams", - "web-sys", -] - [[package]] name = "rfc6979" version = "0.6.0" @@ -7775,27 +7233,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "rustls-platform-verifier" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d99feebc72bae7ab76ba994bb5e121b8d83d910ca40b36e0921f53becc41784" -dependencies = [ - "core-foundation", - "core-foundation-sys", - "jni 0.21.1", - "log", - "once_cell", - "rustls", - "rustls-native-certs", - "rustls-platform-verifier-android 0.1.1", - "rustls-webpki", - "security-framework", - "security-framework-sys", - "webpki-root-certs", - "windows-sys 0.61.2", -] - [[package]] name = "rustls-platform-verifier" version = "0.7.1" @@ -7804,12 +7241,12 @@ checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" dependencies = [ "core-foundation", "core-foundation-sys", - "jni 0.22.4", + "jni", "log", "once_cell", "rustls", "rustls-native-certs", - "rustls-platform-verifier-android 0.2.0", + "rustls-platform-verifier-android", "rustls-webpki", "security-framework", "security-framework-sys", @@ -7817,12 +7254,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "rustls-platform-verifier-android" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" - [[package]] name = "rustls-platform-verifier-android" version = "0.2.0" @@ -8161,7 +7592,7 @@ version = "3.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cff15a7c864bbec77d9586ca6822bc7c369bdf19e9243134a62b0b51ce26b31f" dependencies = [ - "darling 0.24.1", + "darling", "proc-macro2", "quote", "syn 3.0.5", @@ -8261,12 +7692,6 @@ dependencies = [ "lazy_static", ] -[[package]] -name = "shell-escape" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45bb67a18fa91266cc7807181f62f9178a6873bfad7dc788c42e6430db40184f" - [[package]] name = "shell-words" version = "1.1.1" @@ -8761,31 +8186,13 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "strum" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" - [[package]] name = "strum" version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" dependencies = [ - "strum_macros 0.28.0", -] - -[[package]] -name = "strum_macros" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.117", + "strum_macros", ] [[package]] @@ -9976,19 +9383,6 @@ dependencies = [ "wasmparser", ] -[[package]] -name = "wasm-streams" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "wasmparser" version = "0.244.0" @@ -10255,15 +9649,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", -] - [[package]] name = "windows-sys" version = "0.52.0" @@ -10300,21 +9685,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - [[package]] name = "windows-targets" version = "0.52.6" @@ -10357,12 +9727,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -10375,12 +9739,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" @@ -10393,12 +9751,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -10423,12 +9775,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - [[package]] name = "windows_i686_msvc" version = "0.52.6" @@ -10441,12 +9787,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" @@ -10459,12 +9799,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" @@ -10477,12 +9811,6 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -10755,7 +10083,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5077cb7ffc12400f0420586f1dd22158e0764b2136d19f06311496ef2bf7be34" dependencies = [ "pkg-config", - "reqwest 0.12.28", + "reqwest", "serde_json", "z3-src", "zip", diff --git a/crates/openshell-container-runtime/Cargo.toml b/crates/openshell-container-runtime/Cargo.toml deleted file mode 100644 index 0aa648724e..0000000000 --- a/crates/openshell-container-runtime/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -[package] -name = "openshell-container-runtime" -description = "Code shared by the OpenShell desktop compute drivers (Docker, Podman, VM)" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true - -[dependencies] -openshell-core = { path = "../openshell-core", default-features = false } -serde_json = { workspace = true } - -[target.'cfg(unix)'.dependencies] -nix = { workspace = true } - -[target.'cfg(target_os = "linux")'.dependencies] -rustix = { workspace = true } - -[lints] -workspace = true diff --git a/crates/openshell-container-runtime/README.md b/crates/openshell-container-runtime/README.md deleted file mode 100644 index a1b8f84980..0000000000 --- a/crates/openshell-container-runtime/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# openshell-container-runtime - -Code used only by the desktop compute drivers (Docker, Podman, and VM). It -moves with those drivers when they leave this repository. Code that the -gateway, supervisor, or Kubernetes driver also uses does not belong here. - -## Contents - -- `podman_socket`: Podman API socket discovery for native and machine-backed - installations. diff --git a/crates/openshell-container-runtime/src/lib.rs b/crates/openshell-container-runtime/src/lib.rs deleted file mode 100644 index b37532d8a3..0000000000 --- a/crates/openshell-container-runtime/src/lib.rs +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Code shared by the `OpenShell` desktop compute drivers. -//! -//! Everything here is used only by the Docker, Podman, and VM drivers, so the -//! crate moves with them when they leave this repository. - -pub mod podman_socket; diff --git a/crates/openshell-container-runtime/src/podman_socket.rs b/crates/openshell-container-runtime/src/podman_socket.rs deleted file mode 100644 index e7a6c79e74..0000000000 --- a/crates/openshell-container-runtime/src/podman_socket.rs +++ /dev/null @@ -1,402 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Podman socket discovery for local and machine-backed installations. - -use std::path::PathBuf; -use std::process::{Command, Stdio}; -use std::time::{Duration, Instant}; - -const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5); -const DISCOVERY_POLL_INTERVAL: Duration = Duration::from_millis(25); - -/// Return the first responsive well-known socket, then ask the Podman CLI for -/// the active native or machine-backed connection. -pub fn detect_socket() -> Option { - openshell_core::local_api_socket::first_responsive_socket(&socket_candidates(), |response| { - openshell_core::local_api_socket::http_response_is_success(response) - && openshell_core::local_api_socket::contains_ascii(response, b"Libpod-Api-Version:") - }) - .or_else(discover_socket) -} - -fn socket_candidates() -> Vec { - let mut candidates = Vec::new(); - if let Some(path) = env_var_nonempty("OPENSHELL_PODMAN_SOCKET") { - candidates.push(PathBuf::from(path)); - } - if let Some(runtime_dir) = std::env::var_os("XDG_RUNTIME_DIR") { - candidates.push(PathBuf::from(runtime_dir).join("podman/podman.sock")); - } - #[cfg(target_os = "linux")] - candidates.push(PathBuf::from(format!( - "/run/user/{}/podman/podman.sock", - rustix::process::geteuid().as_raw() - ))); - if let Some(home) = std::env::var_os("HOME") { - candidates - .push(PathBuf::from(home).join(".local/share/containers/podman/machine/podman.sock")); - } - candidates -} - -/// Query the same active connection selected by the Podman CLI. This covers -/// named/rootful machines and provider-specific forwarded socket locations that -/// do not have a stable well-known path. -fn discover_socket() -> Option { - let stdout = run_podman_capture(&["info", "--format", "json"])?; - - // A successful `podman info` proves this explicit socket is usable. A named - // connection has higher precedence, so only honor CONTAINER_HOST directly - // when no CONTAINER_CONNECTION is set. - if env_var_nonempty("CONTAINER_CONNECTION").is_none() - && let Some(path) = env_var_nonempty("CONTAINER_HOST") - .as_deref() - .and_then(unix_url_socket_path) - { - return Some(path); - } - - let info: serde_json::Value = serde_json::from_slice(&stdout).ok()?; - if !info["host"]["serviceIsRemote"].as_bool().unwrap_or(false) { - return parse_info_socket(&info); - } - - discover_machine_socket() -} - -fn discover_machine_socket() -> Option { - let connections = connection_list(); - let active = active_machine( - env_var_nonempty("CONTAINER_CONNECTION").as_deref(), - env_var_nonempty("CONTAINER_HOST").as_deref(), - connections.as_ref(), - )?; - machine_inspect_targets(&active) - .into_iter() - .find_map(|name| { - let stdout = run_podman_capture(&["machine", "inspect", &name])?; - let machines: serde_json::Value = serde_json::from_slice(&stdout).ok()?; - parse_machine_socket(&machines) - }) -} - -fn active_machine( - container_connection: Option<&str>, - container_host: Option<&str>, - connections: Option<&serde_json::Value>, -) -> Option { - if let Some(name) = container_connection.filter(|name| !name.trim().is_empty()) { - return Some(name.to_string()); - } - if let Some(host) = container_host.filter(|host| !host.trim().is_empty()) { - // An explicit non-machine endpoint must not fall back to an unrelated - // local machine. - return connection_name_for_uri(connections?, host); - } - default_machine_connection(connections).or_else(|| Some("podman-machine-default".to_string())) -} - -fn machine_inspect_targets(connection: &str) -> Vec { - let mut names = vec![connection.to_string()]; - if let Some(machine) = connection.strip_suffix("-root") - && !machine.is_empty() - { - names.push(machine.to_string()); - } - names -} - -fn connection_list() -> Option { - let stdout = run_podman_capture(&["system", "connection", "list", "--format", "json"])?; - serde_json::from_slice(&stdout).ok() -} - -fn default_machine_connection(connections: Option<&serde_json::Value>) -> Option { - connections? - .as_array()? - .iter() - .find(|connection| { - connection["Default"].as_bool().unwrap_or(false) - && connection["IsMachine"].as_bool().unwrap_or(false) - }) - .and_then(|connection| connection["Name"].as_str()) - .map(str::to_string) -} - -fn connection_name_for_uri(connections: &serde_json::Value, uri: &str) -> Option { - connections - .as_array()? - .iter() - .find(|connection| { - connection["IsMachine"].as_bool().unwrap_or(false) - && connection["URI"].as_str() == Some(uri) - }) - .and_then(|connection| connection["Name"].as_str()) - .map(str::to_string) -} - -fn parse_info_socket(info: &serde_json::Value) -> Option { - let path = info["host"]["remoteSocket"]["path"].as_str()?; - unix_url_socket_path(path).or_else(|| (!path.is_empty()).then(|| PathBuf::from(path))) -} - -fn parse_machine_socket(machines: &serde_json::Value) -> Option { - let path = machines.as_array()?.first()?["ConnectionInfo"]["PodmanSocket"]["Path"].as_str()?; - (!path.is_empty()).then(|| PathBuf::from(path)) -} - -fn unix_url_socket_path(url: &str) -> Option { - let path = url.trim().strip_prefix("unix://")?; - (!path.is_empty()).then(|| PathBuf::from(path)) -} - -fn env_var_nonempty(key: &str) -> Option { - std::env::var(key) - .ok() - .filter(|value| !value.trim().is_empty()) -} - -fn run_podman_capture(args: &[&str]) -> Option> { - run_bounded_command("podman", args, DISCOVERY_TIMEOUT) -} - -/// Capture stdout without allowing a stalled Podman machine, SSH transport, or -/// descendant holding the stdout pipe open to block gateway startup forever. -fn run_bounded_command(program: &str, args: &[&str], timeout: Duration) -> Option> { - use std::io::Read as _; - use std::sync::mpsc; - - let mut command = Command::new(program); - command - .args(args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()); - set_new_process_group(&mut command); - let mut child = command.spawn().ok()?; - - let mut stdout = child.stdout.take()?; - let (sender, receiver) = mpsc::channel(); - std::thread::spawn(move || { - let mut output = Vec::new(); - let _ = stdout.read_to_end(&mut output); - let _ = sender.send(output); - }); - - let deadline = Instant::now() + timeout; - let status = loop { - match child.try_wait() { - Ok(Some(status)) => break Some(status), - Ok(None) if Instant::now() < deadline => { - std::thread::sleep(DISCOVERY_POLL_INTERVAL); - } - Ok(None) | Err(_) => break None, - } - }; - - let Some(status) = status else { - terminate_process_group(&mut child); - let _ = child.wait(); - return None; - }; - - match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) { - Ok(output) if status.success() => Some(output), - Ok(_) => None, - Err(_) => { - terminate_process_group(&mut child); - None - } - } -} - -#[cfg(unix)] -fn set_new_process_group(command: &mut Command) { - use std::os::unix::process::CommandExt as _; - command.process_group(0); -} - -#[cfg(not(unix))] -fn set_new_process_group(_command: &mut Command) {} - -#[cfg(unix)] -fn terminate_process_group(child: &mut std::process::Child) { - let pid = i32::try_from(child.id()).unwrap_or(i32::MAX); - let group = nix::unistd::Pid::from_raw(-pid); - let _ = nix::sys::signal::kill(group, nix::sys::signal::Signal::SIGKILL); - let _ = child.kill(); -} - -#[cfg(not(unix))] -fn terminate_process_group(child: &mut std::process::Child) { - let _ = child.kill(); -} - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - #[test] - fn parse_info_socket_rejects_missing_or_empty_paths() { - assert_eq!( - parse_info_socket(&json!({"host": {"remoteSocket": {}}})), - None - ); - assert_eq!( - parse_info_socket(&json!({"host": {"remoteSocket": {"path": ""}}})), - None - ); - } - - #[test] - fn parse_machine_socket_rejects_missing_socket_or_machine() { - assert_eq!(parse_machine_socket(&json!([])), None); - assert_eq!(parse_machine_socket(&json!([{"ConnectionInfo": {}}])), None); - } - - #[test] - fn parses_native_and_machine_socket_paths() { - let info = json!({"host": {"remoteSocket": {"path": "unix:///run/user/1000/podman.sock"}}}); - assert_eq!( - parse_info_socket(&info), - Some(PathBuf::from("/run/user/1000/podman.sock")) - ); - - let machine = json!([{"ConnectionInfo": {"PodmanSocket": {"Path": "/tmp/machine.sock"}}}]); - assert_eq!( - parse_machine_socket(&machine), - Some(PathBuf::from("/tmp/machine.sock")) - ); - } - - #[test] - fn resolves_named_rootful_and_default_machine_connections() { - let connections = json!([ - {"Name": "team-machine-root", "URI": "ssh://team", "Default": true, "IsMachine": true}, - {"Name": "remote", "URI": "ssh://remote", "Default": false, "IsMachine": false} - ]); - assert_eq!( - active_machine(Some("team-machine-root"), None, Some(&connections)), - Some("team-machine-root".to_string()) - ); - assert_eq!( - machine_inspect_targets("team-machine-root"), - ["team-machine-root", "team-machine"] - ); - assert_eq!( - active_machine(None, None, Some(&connections)), - Some("team-machine-root".to_string()) - ); - } - - #[test] - fn explicit_non_machine_endpoint_does_not_guess_a_machine() { - let connections = json!([ - {"Name": "local", "URI": "ssh://local", "Default": true, "IsMachine": true}, - {"Name": "remote", "URI": "ssh://remote", "Default": false, "IsMachine": false} - ]); - assert_eq!( - active_machine(None, Some("ssh://remote"), Some(&connections)), - None - ); - } - - #[test] - fn container_host_maps_to_the_matching_machine_connection() { - let connections = json!([ - {"Name": "work", "URI": "ssh://core@127.0.0.1:5555/run/podman.sock", "Default": false, "IsMachine": true}, - {"Name": "podman-machine-default", "URI": "ssh://core@127.0.0.1:4444/run/podman.sock", "Default": true, "IsMachine": true} - ]); - assert_eq!( - active_machine( - None, - Some("ssh://core@127.0.0.1:5555/run/podman.sock"), - Some(&connections), - ), - Some("work".to_string()) - ); - } - - #[test] - fn unix_url_socket_path_only_accepts_nonempty_unix_urls() { - assert_eq!( - unix_url_socket_path("unix:///run/user/1000/podman.sock"), - Some(PathBuf::from("/run/user/1000/podman.sock")) - ); - assert_eq!(unix_url_socket_path("ssh://core@127.0.0.1/x"), None); - assert_eq!(unix_url_socket_path("tcp://127.0.0.1:2375"), None); - assert_eq!(unix_url_socket_path("unix://"), None); - } - - #[cfg(unix)] - #[test] - fn bounded_command_captures_stdout_on_success() { - assert_eq!( - run_bounded_command("printf", &["hello"], Duration::from_secs(5)), - Some(b"hello".to_vec()) - ); - } - - #[cfg(unix)] - #[test] - fn bounded_command_returns_none_on_nonzero_exit_or_missing_program() { - assert_eq!( - run_bounded_command("false", &[], Duration::from_secs(5)), - None - ); - assert_eq!( - run_bounded_command( - "openshell-nonexistent-binary-xyz", - &[], - Duration::from_secs(5), - ), - None - ); - } - - #[cfg(unix)] - #[test] - fn bounded_command_kills_child_that_exceeds_deadline() { - let start = Instant::now(); - let result = run_bounded_command("sleep", &["30"], Duration::from_millis(200)); - assert_eq!(result, None); - assert!( - start.elapsed() < Duration::from_secs(5), - "bounded command did not return promptly" - ); - } - - #[cfg(unix)] - #[test] - fn bounded_command_bounds_drain_when_in_group_descendant_holds_stdout() { - let start = Instant::now(); - let result = run_bounded_command( - "sh", - &["-c", "sleep 30 & echo done"], - Duration::from_millis(300), - ); - assert_eq!(result, None); - assert!( - start.elapsed() < Duration::from_secs(2), - "drain blocked on a descendant holding stdout" - ); - } - - #[cfg(unix)] - #[test] - fn bounded_command_bounds_drain_when_descendant_escapes_process_group() { - let start = Instant::now(); - let result = run_bounded_command( - "bash", - &["-c", "set -m; sleep 5 & echo done"], - Duration::from_millis(300), - ); - assert_eq!(result, None); - assert!( - start.elapsed() < Duration::from_secs(2), - "drain blocked on a descendant that escaped the process group" - ); - } -} diff --git a/crates/openshell-driver-docker/Cargo.toml b/crates/openshell-driver-docker/Cargo.toml deleted file mode 100644 index de2b341de4..0000000000 --- a/crates/openshell-driver-docker/Cargo.toml +++ /dev/null @@ -1,62 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -[package] -name = "openshell-driver-docker" -description = "Docker compute driver for OpenShell" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true - -[[bin]] -name = "openshell-driver-docker" -path = "src/main.rs" - -[dependencies] -openshell-core = { path = "../openshell-core", default-features = false, features = ["driver-extraction", "otel", "clap"] } -openshell-isolation-interface = { path = "../openshell-isolation-interface" } -openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } -openshell-driver-sdk = { path = "../openshell-driver-sdk" } -openshell-otel = { path = "../openshell-otel" } - -opentelemetry = { workspace = true } -opentelemetry_sdk = { workspace = true } -tracing-opentelemetry = { workspace = true } -tokio = { workspace = true } -tonic = { workspace = true, features = ["transport"] } -futures = { workspace = true } -tokio-stream = { workspace = true } -tracing = { workspace = true } -tracing-subscriber = { workspace = true } -bytes = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -prost-types = { workspace = true } -bollard = { version = "0.20" } -url = { workspace = true } -clap = { workspace = true } -miette = { workspace = true } -toml = { workspace = true } -tower-http = { workspace = true } -http = { workspace = true } -rand = { workspace = true } -sha2 = { workspace = true } -rustix = { workspace = true } -libc = "0.2" -tar = "0.4" -tempfile = "3" - -[dev-dependencies] -hyper-util = { workspace = true } -tower = { workspace = true } -openshell-otel-test-support = { path = "../openshell-otel-test-support" } -opentelemetry = { workspace = true } -opentelemetry_sdk = { workspace = true, features = ["testing"] } -prost-types = { workspace = true } -temp-env = "0.3" -tracing-subscriber = { workspace = true } - -[lints] -workspace = true diff --git a/crates/openshell-driver-docker/README.md b/crates/openshell-driver-docker/README.md deleted file mode 100644 index 871c9f2f01..0000000000 --- a/crates/openshell-driver-docker/README.md +++ /dev/null @@ -1,332 +0,0 @@ -# openshell-driver-docker - -Docker-backed compute driver for local and remote OpenShell gateways. - -The driver uses `bollard` to manage sandbox resources through the configured -Docker API socket. When `socket_path` is unset, it selects the first standard -local socket that responds to an API ping. An explicitly selected Docker driver -falls back to `/var/run/docker.sock` when no candidate responds. - -When the gateway configures `[openshell.gateway.otlp]`, the in-process driver -exports spans to the same OTLP collector, over its configured protocol, as -`openshell-driver-docker`. The standalone driver accepts -`OPENSHELL_OTLP_ENDPOINT` and `OPENSHELL_OTLP_PROTOCOL`, with -`OPENSHELL_OTLP_CA_FILE`, `OPENSHELL_OTLP_CERT_FILE`, and -`OPENSHELL_OTLP_KEY_FILE` for an `https://` collector, continues W3C trace -context from gateway RPC -metadata, and flushes spans during graceful shutdown. When -`[openshell.gateway.otlp.agent]` is enabled, the driver also sets -`OPENSHELL_OTLP_AGENT_ENDPOINT` on the supervisor container, plus -`OPENSHELL_OTLP_AGENT_PROTOCOL` for a non-gRPC collector, which starts the -agent trace relay. The standalone driver takes them as `--otlp-agent-endpoint` -and `--otlp-agent-protocol`. - -## Runtime Model - -Caller driver config is disabled by default. Existing volumes require -administrator-controlled approval labels; raw bind mounts have no supported -label resolver and are denied under enforcement. GPU devices are temporarily -exempt. Inspect labels again before launch, restart, and during reconciliation. -See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission). - -The driver creates two containers for each sandbox: - -- `openshell-sandbox` is PID 1 in the workload container. It owns the workload - process tree, seccomp notification broker, mandatory Landlock baseline, - binary identity, exec/signal/wait/PTY operations, and loopback forwarding. -- `openshell-supervisor` runs in a separate companion container. It owns the - gateway session, policy engine, credentials, interception CA, SSH relay, L7 - inspection, DNS policy, and external upstream connections. - -Both containers are non-root, request no capabilities, and set -no-new-privileges. A shared named volume carries the authenticated Unix socket -and sandbox bootstrap material. A second supervisor-only volume carries the -supervisor JWT and gateway client credentials and is never mounted into the -workload. - -The workload uses `network_mode=none`. Its seccomp user-notification broker -mediates every supported TCP and DNS operation, attributes it to the calling -binary, and sends the request across the private channel. The supervisor -authorizes the request before it opens an upstream connection. Docker's absent -workload network is the mandatory outer fence if mediation fails or is -bypassed. The trusted supervisor companion originates approved egress. Its -operator-owned `supervisor_network_mode` defaults to `host`. Set `bridge` to -run the supervisor on Docker's bridge network; `auto` also selects host. - -The driver copies trusted runtime bytes from the configured supervisor image -through the Docker archive API. No workload launch depends on a host bind -mount or a tool supplied by the workload image, so the same path works with -local, remote, and VM-backed Docker daemons. - -## Corporate Proxy Egress - -`[openshell.drivers.docker]` accepts the operator-owned corporate proxy fields -`https_proxy`, `no_proxy`, `proxy_auth_file`, -`proxy_auth_allow_insecure`, `proxy_connect_by_hostname`, and -`proxy_ca_bundle`. Sandbox environment, image contents, and per-sandbox driver -configuration cannot select or override them. - -The driver validates the proxy URL and cross-field relationships at gateway -startup. It bounded-reads proxy credentials and the PEM CA bundle before use. -Missing, unreadable, empty, oversized, malformed, or certificate-free CA files -fail closed. A CA bundle requires `https_proxy`, although the proxy URL may be -`http://` when the proxy intercepts destination TLS. - -For each supervisor launch, Docker copies the credential and CA contents into -the existing supervisor-only named volume. It passes only the fixed container -paths `/.openshell/supervisor/upstream-proxy-auth` and -`/.openshell/supervisor/upstream-proxy-ca-bundle.pem` to the supervisor. It -does not bind-mount the gateway-host files, which preserves remote-daemon -support and keeps host paths out of workload container metadata. - -The supervisor trusts the configured CA for its TLS connection to an HTTPS -proxy and for destination certificates re-signed by a TLS-intercepting proxy. -It also includes the corporate root in the generated combined trust bundle -used by workload processes. - -## Identity and Workspace - -Before creating the workload, the driver pins the image ID and reads its -passwd/group databases through a stopped metadata container. It resolves the -admitted policy identity, or the image `Config.User` fallback, into one exact -non-root UID, primary GID, and supplementary-group set. Docker launches -`openshell-sandbox` with that identity, and the sandbox uses the same identity -for every canonical and exec process. UID or GID zero and unresolved symbolic -identities are rejected. - -An absolute OCI working directory becomes the workspace. An empty, root (`/`), -or explicit `/sandbox` declaration uses `/sandbox`. Any other workdir must -already exist without symlink components. The resolved identity must be able to -traverse every parent and write and enter the workdir; OpenShell does not -change its ownership or mode. - -Image `VOLUME` declarations and user mounts must not cover the workdir, one of -its parents, or the reserved `/.openshell` runtime/channel tree. OpenShell asks -the kernel to validate access under the final identity, so POSIX ACL and host -LSM decisions remain authoritative. - -## Container Contract - -| Setting | Purpose | -|---|---| -| Exact non-root `user` and `group_add` | Gives sandbox and workload the same immutable UID/GID/group identity required for capability-free observation. | -| `cap_drop = ALL`, no `cap_add`, no-new-privileges | Prevents either container from acquiring Linux capabilities. | -| Docker default seccomp and AppArmor profiles | Retains runtime hardening; startup confirmation fails closed if nested seccomp notification is unavailable. | -| `network_mode = none` on the workload | Removes direct external routes. | -| `network_mode = host` on the supervisor | Lets the trusted supervisor reach the gateway's primary loopback listener and originate approved upstream connections. | -| `restart_policy = no` | Keeps canonical main-process exit terminal. | -| `PidsLimit` | Applies the configured sandbox PID budget. Omit `sandbox_pids_limit` to use OpenShell's default. Explicit zero is invalid. | -| Private named volumes | Separate volumes carry sandbox bootstrap keys, the runtime-initiated Unix socket, and supervisor-only credentials. The supervisor mounts bootstrap keys read-only and only the socket volume writable. | -| In-memory `/run/openshell-supervisor-ca` tmpfs | Holds only the public supervisor CA certificate and trust bundle without making all of `/run` writable. | -| CDI GPU request | Assigns the exact validated CDI devices requested by driver config or count-based selection. | - -New containers dial the supervisor at `/.openshell/channel/control/supervisor/control.sock`. -The runtime remains the TLS/gRPC server; the supervisor verifies its pinned -identity and supplies the existing bearer credential. Saved descriptors retain -the legacy Unix listener for existing containers, including across restart. -New generations require matching supervisor and sandbox runtime binaries. - -## Stop, Start, and Delete - -Set `persist_workspace = true` in `[openshell.drivers.docker]` to give newly -created default `/sandbox` workspaces a driver-owned local volume. The setting -defaults to false and does not migrate existing writable-layer workspaces. -Custom working directories and image-declared volumes overlapping `/sandbox` -are rejected when enabled. Initialization prepares the workspace ownership; -it does not copy the image's workspace contents into the volume. - -The driver records and rechecks the volume identity and workload UID/GID before -restart, including when external resource admission is disabled. Stop retains -the data. Explicit sandbox deletion removes the owned workspace volume and -reports removal failures. Startup orphan cleanup retains workspace volumes -without a workload; an interrupted create requires explicit recovery/removal. -This option advertises the optional workload update capability. The gateway's -separate `enable_sandbox_updates` setting must also be enabled to accept updates. - -Persistence ownership comes from `workspace-storage.json` in the protected -per-sandbox driver directory, bound into the private bootstrap and runtime -descriptor. It records the namespace, sandbox, workload UID/GID and exact volume -identity. Container labels do not select persistent storage or authorize volume -admission, updates or removal. All caller template labels retain their existing -meaning, including generic and Docker-specific workspace label names. - -### Stopped Workload Image Updates - -The Docker updater implements the existing configuration-update RPC for -image-only changes on stopped, persistent `/sandbox` workspaces. Source and -target images must already be cached locally and declare no image volumes. The -target must declare an explicit numeric `USER UID:GID` matching the recorded -non-root workload identity. Symbolic users/groups, UID-only users, and an absent -`USER` are rejected before replacement; update preflight does not resolve image -accounts. Command and environment changes are unsupported. - -The update replaces the stopped workload container while preserving the native -sandbox ID and owned workspace volume. It refreshes the private runtime evidence -for the replacement; it does not change the trusted sandbox or supervisor images. -A private operation record lets the same accepted operation resume after an -interruption. Start refuses an unfinished update. Stop and startup reconciliation -retain its data and runtime resources; explicit Delete removes its owned storage. -Retry through the gateway to finish the accepted update before starting it. -The operation never starts the workload or rolls back workspace data implicitly. - -#### Live Driver Integration Test - -The opt-in test below uses a real Docker daemon and isolated, uniquely labeled -stopped containers and a workspace volume. It checks numeric/symbolic identity -refusal, A-to-B replacement, retained file bytes, replay, and recovery after an -accepted update loses its source container. Cleanup verifies ownership and never -forces removal. This is driver integration coverage; gateway authorization, -supervisor startup, and authenticated workload operations still require E2E. - -From the repository root, prepare the four local test images: - -```shell -for version in A B BAD SYMBOLIC; do - case "$version" in - BAD) fixture_user=2000:2000 ;; - SYMBOLIC) fixture_user=other:other ;; - *) fixture_user=1234:1235 ;; - esac - docker build --network=none --build-arg VERSION="$version" \ - --build-arg WORKLOAD_USER="$fixture_user" -t "openshell-image-update-test:$version" \ - crates/openshell-driver-docker/tests/fixtures/image-update -done - -OPENSHELL_DOCKER_UPDATE_IMAGE_A=openshell-image-update-test:A \ -OPENSHELL_DOCKER_UPDATE_IMAGE_B=openshell-image-update-test:B \ -OPENSHELL_DOCKER_UPDATE_IMAGE_BAD=openshell-image-update-test:BAD \ -OPENSHELL_DOCKER_UPDATE_IMAGE_SYMBOLIC=openshell-image-update-test:SYMBOLIC \ -cargo test --locked -p openshell-driver-docker --lib \ - live_stopped_image_replacement -- --ignored --nocapture -``` - -The Docker CLI must be on `PATH` and use the same daemon as the SDK. On Docker -Desktop, set `DOCKER_HOST` to the socket reported by `docker context inspect`. - -For authenticated gateway/supervisor qualification, including SSH exec, -replacement, gateway restart, interrupted credential-publication repair and -complete API deletion, run the separate -[Docker update testkit suite](../../tests/suites/features/docker-updates/README.md). - -Stop terminates the supervisor companion, allowing it 10 seconds to stop the -workload, and stops the workload container without removing it. Docker retains -the workload writable layer and attached -volumes. Start stages a fresh sandbox bootstrap bundle, restarts that workload, -and creates a new supervisor companion. A durably stopped sandbox stays stopped -across gateway restarts. - -Delete force-removes both containers, the driver-owned runtime volumes, and the -host-private runtime descriptor. Missing or altered descriptor and channel resources -fail closed; the driver does not run an older combined-supervisor layout. - -## Driver Config Mounts - -The gateway forwards the `docker` block from `--driver-config-json`. Supported -mount types are: - -- `bind`: an absolute daemon-host path, allowed only when - `[openshell.drivers.docker].enable_bind_mounts = true` and label admission - is explicitly disabled. -- `volume`: an existing named volume. The driver never creates or removes a - user-supplied volume. Bind-backed local volumes require - `enable_bind_mounts = true`. -- `tmpfs`: an in-memory filesystem with optional size and mode. - -Host bind mounts are disabled by default because they expose daemon-host paths -to sandbox requests. User bind and volume mounts are read-only by default. -Targets must be absolute, normalized paths and cannot overlap the workspace -root or OpenShell control paths. - -Example: - -```shell -docker volume create openshell-work - -openshell sandbox create \ - --driver-config-json '{"docker":{"mounts":[{"type":"volume","source":"openshell-work","target":"/sandbox/work"}]}}' \ - -- claude -``` - -## Runtime Image - -`sandbox_runtime_image` contains the statically linked musl -`/openshell-sandbox` binary. The driver extracts that binary as bytes and -stages it into the stopped workload. `supervisor_image` contains the -dynamically linked glibc `/openshell-supervisor` binary that runs in the -supervisor companion container. Release and gateway image builds bake -matching image tags into the binary. - -## Gateway session and TLS - -`OPENSHELL_ENDPOINT` and gateway authentication material are injected only into -the supervisor companion. The workload never receives the sandbox JWT, gateway -client TLS key, policy authority, or interception CA private key. - -When no endpoint is configured, the supervisor connects to -`127.0.0.1:`. Set `grpc_endpoint` when the gateway is not on the -Docker daemon host. A configured HTTPS server certificate must include the -endpoint host in its subject alternative names. - -In host mode, the driver publishes host loopback as the backend address for -`host.openshell.internal`. Policy DNS resolves that reserved name through the -mediated path, so policies can reach host services without a Docker bridge, -container DNS alias, or another gateway listener. - -For HTTPS endpoints, the supervisor receives only the gateway CA and -uses its sandbox-scoped bearer token to authenticate RPCs. User client -certificates and private keys are not delivered to either container. - -Host mode on Docker Desktop requires host networking enabled in Settings. -For bridge mode or a gateway endpoint using `host.docker.internal`, the driver -resolves Docker's `host-gateway` once during initialization and caches it. -A temporary container runs `--help` from the immutable supervisor image with -no network, no capabilities, no privilege escalation, and a read-only root -filesystem. The driver downloads Docker's generated `/etc/hosts` through the -archive API, preferring a unique IPv4 address and otherwise a unique IPv6 -address. Resolution has a 30-second timeout; forced cleanup has a separate -10-second timeout and runs after success or failure. - -The driver uses the selected address for both host aliases and the runtime -descriptor's trust pin; workload DNS and hosts files cannot select it. Host -mode with other gateway endpoints retains its gateway-address pin. An explicit -operator-owned `host_gateway_ip` overrides discovery and skips the temporary -container. No supervisor changes or per-sandbox discovery are required. - -When `grpc_endpoint` is omitted, bridge mode uses `host.docker.internal` on -Desktop or for a wildcard gateway listener, and the concrete bind address for -other non-loopback Linux listeners. The port is the gateway bind port; remapped -container publications require an explicit endpoint. Native Linux loopback-only -listeners cannot serve a bridge supervisor and produce an actionable error. -Explicit endpoints retain TLS verification and are never rewritten; bridge -rejects loopback/unspecified endpoint addresses. Host services bound only to -loopback are also unreachable from a native Linux bridge supervisor. - -The selected network mode does not change the sandbox's mandatory Landlock -and seccomp qualification. - -The supervisor owns these security-critical variables: - -- `OPENSHELL_ENDPOINT` -- `OPENSHELL_SANDBOX_ID` -- `OPENSHELL_SANDBOX` -- `OPENSHELL_SANDBOX_TOKEN_FILE` -- `OPENSHELL_SSH_SOCKET_PATH` -- `OPENSHELL_MAIN_PROCESS_SPEC` -- `OPENSHELL_TLS_CA` when HTTPS is enabled - -Template and sandbox environment is encoded in the protected bootstrap and -exposed only to workload children. Workload input cannot override -security-critical supervisor variables. - -## Launched mode - -```text -openshell-driver-docker serve --bind-socket --expected-peer-pid --log-level < table.toml -openshell-driver-docker preflight < table.toml -``` - -The gateway passes the `[openshell.drivers.docker]` table on stdin and gateway metadata in a `Configure` call (`proto/driver_launch.proto`). `settings_from_table` in `src/launch.rs` is the only place the table is parsed and validated. - -`serve` resolves the Docker socket from `socket_path`, then `DOCKER_HOST` and the usual locations, and pings it before it binds. The ping gets 20 seconds, so the gateway, which waits 30 seconds for a driver to start, receives the report instead of killing the driver. It exits 69 when Docker is not reachable and 78 when the table is invalid. Until `Configure` succeeds, both gRPC services (`ComputeDriver` and `ComputeDriverConfigurationUpdates`) return `UNAVAILABLE` and the driver creates no volumes, networks or containers. `preflight` validates the table without contacting Docker. - -The gateway supplies the CA, the admission policy, its listener address, trusted runtime images from its environment, destination trust, and OTLP settings through `Configure`, so the table rejects `guest_tls_ca`, `allow_driver_config` and `resource_admission`. `grpc_endpoint` remains an optional override, and an `https://` endpoint needs the gateway CA. diff --git a/crates/openshell-driver-docker/src/image_update.rs b/crates/openshell-driver-docker/src/image_update.rs deleted file mode 100644 index 4c5070f2c9..0000000000 --- a/crates/openshell-driver-docker/src/image_update.rs +++ /dev/null @@ -1,1022 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Stopped workload replacement. The gateway remains the accepted-operation owner. - -use super::*; -use bollard::models::ContainerInspectResponse; -use openshell_core::proto::compute::v1::{ - SandboxUpdatePreconditions, UpdateSandboxConfigurationRequest, -}; -use serde::{Deserialize, Serialize}; -use std::io::Write as _; - -const RECORD_FILE: &str = "workload-image-update.json"; -const OPERATION_LABEL: &str = "openshell.ai/workload-image-operation"; -const REVISION_LABEL: &str = "openshell.ai/workload-image-revision"; -const MAX_RECORD_BYTES: usize = 2 * 1024 * 1024; - -#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -enum Phase { - Prepared, - Replaced, - Applied, -} - -// No Debug implementation: the immutable create input can contain private -// environment/configuration. It never enters logs or public status. -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Intent { - version: u32, - namespace: String, - sandbox_id: String, - sandbox_name: String, - operation_id: String, - revision: u64, - previous_image: String, - image: String, - image_id: String, - original_container: String, - container_name: String, - target_container: Option, - body: ContainerCreateBody, - original_bootstrap: Vec, - original_descriptor: Vec, - phase: Phase, -} - -fn invalid(message: &'static str) -> Status { - Status::failed_precondition(message) -} - -fn validate_request( - request: &UpdateSandboxConfigurationRequest, -) -> Result<&SandboxUpdatePreconditions, Status> { - let p = request - .preconditions - .as_ref() - .ok_or_else(|| Status::invalid_argument("update preconditions are required"))?; - if p.sandbox_id.is_empty() - || p.sandbox_id.len() > 128 - || !p - .sandbox_id - .bytes() - .all(|v| v.is_ascii_alphanumeric() || matches!(v, b'-' | b'_')) - || p.name.is_empty() - || p.name.len() > 256 - || p.image.is_empty() - || p.image.len() > 4096 - || p.expected_image.is_empty() - || p.expected_image.len() > 4096 - || p.revision == 0 - { - return Err(Status::invalid_argument( - "invalid Docker image-update preconditions", - )); - } - let operation = p.operation_id.as_bytes(); - if operation.len() != 36 - || operation.iter().enumerate().any(|(i, v)| { - if matches!(i, 8 | 13 | 18 | 23) { - *v != b'-' - } else { - !v.is_ascii_hexdigit() - } - }) - { - return Err(Status::invalid_argument( - "image-update operation ID must be a UUID", - )); - } - if request.main_process.is_some() || request.environment.is_some() { - return Err(Status::unimplemented( - "the initial Docker updater supports image-only workload changes", - )); - } - // Docker's pinned contract does not authenticate compute credentials or - // publish that optional identity. The private native descriptor, exact - // container ID and recorded persistent-volume identity anchor this update. - if !p.expected_runtime_identity.is_empty() { - return Err(invalid( - "Docker image update does not recognize the supplied compute runtime identity", - )); - } - Ok(p) -} - -fn path(config: &DockerDriverRuntimeConfig, id: &str) -> Result { - Ok(docker_boundary_state_dir_by_id(id, config)?.join(RECORD_FILE)) -} - -fn read(config: &DockerDriverRuntimeConfig, id: &str) -> Result, Status> { - let path = path(config, id)?; - let metadata = match std::fs::symlink_metadata(&path) { - Ok(metadata) => metadata, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(_) => return Err(invalid("Docker image-update record cannot be read")), - }; - if !metadata.is_file() || metadata.len() > MAX_RECORD_BYTES as u64 { - return Err(invalid( - "Docker image-update record is not a bounded regular file", - )); - } - let intent: Intent = serde_json::from_slice( - &std::fs::read(path).map_err(|_| invalid("Docker image-update record cannot be read"))?, - ) - .map_err(|_| invalid("Docker image-update record is invalid"))?; - if intent.version != 1 - || intent.sandbox_id != id - || intent.namespace != config.sandbox_namespace - { - return Err(invalid( - "Docker image-update record belongs to another native resource", - )); - } - Ok(Some(intent)) -} - -pub fn durable_write(path: &Path, contents: &[u8]) -> Result<(), Status> { - let parent = path - .parent() - .ok_or_else(|| invalid("Docker image-update state directory is missing"))?; - let mut temporary = tempfile::NamedTempFile::new_in(parent) - .map_err(|_| Status::internal("create private Docker image-update checkpoint"))?; - temporary - .write_all(contents) - .and_then(|()| temporary.as_file().sync_all()) - .map_err(|_| Status::internal("flush Docker image-update checkpoint"))?; - temporary - .persist(path) - .map_err(|_| Status::internal("publish Docker image-update checkpoint"))?; - std::fs::File::open(parent) - .and_then(|file| file.sync_all()) - .map_err(|_| Status::internal("flush Docker image-update directory")) -} - -fn save(config: &DockerDriverRuntimeConfig, intent: &Intent) -> Result<(), Status> { - let bytes = serde_json::to_vec(intent) - .map_err(|_| Status::internal("encode Docker image-update checkpoint"))?; - if bytes.len() > MAX_RECORD_BYTES { - return Err(invalid("Docker image-update checkpoint exceeds its bound")); - } - durable_write(&path(config, &intent.sandbox_id)?, &bytes) -} - -fn same_request(intent: &Intent, p: &SandboxUpdatePreconditions) -> bool { - (intent.sandbox_id.as_str(), intent.sandbox_name.as_str()) - == (p.sandbox_id.as_str(), p.name.as_str()) - && intent.operation_id == p.operation_id - && intent.revision == p.revision - && intent.previous_image == p.expected_image - && intent.image == p.image -} - -fn require_stopped(container: &ContainerInspectResponse) -> Result<(), Status> { - if container.state.as_ref().is_none_or(|state| { - state.running != Some(false) - || state.paused != Some(false) - || state.restarting != Some(false) - || !matches!( - state.status, - Some(ContainerStateStatusEnum::CREATED | ContainerStateStatusEnum::EXITED) - ) - }) { - return Err(invalid( - "Docker workload must be verifiably stopped before image replacement", - )); - } - validate_docker_outer_fence(container)?; - let host = container - .host_config - .as_ref() - .ok_or_else(|| invalid("Docker workload launch fence is missing"))?; - if host.privileged == Some(true) - || host - .cap_add - .as_ref() - .is_some_and(|values| !values.is_empty()) - || host - .cap_drop - .as_ref() - .is_none_or(|values| !values.iter().any(|value| value.eq_ignore_ascii_case("all"))) - || host.security_opt.as_ref().is_none_or(|values| { - !values.iter().any(|value| { - matches!( - value.as_str(), - "no-new-privileges" | "no-new-privileges:true" - ) - }) - }) - || host.auto_remove == Some(true) - { - return Err(invalid("Docker workload launch fence changed")); - } - Ok(()) -} - -fn verify_replacement(container: &ContainerInspectResponse, intent: &Intent) -> Result<(), Status> { - let actual = container - .config - .as_ref() - .ok_or_else(|| invalid("Docker replacement configuration is missing"))?; - let expected = &intent.body; - if container.image.as_ref() != Some(&intent.image_id) - || actual.user != expected.user - || actual.entrypoint != expected.entrypoint - || actual.cmd != expected.cmd - || actual.working_dir != expected.working_dir - || intent - .target_container - .as_ref() - .is_some_and(|id| container.id.as_ref() != Some(id)) - || expected.labels.as_ref().is_none_or(|labels| { - labels.iter().any(|(key, value)| { - actual.labels.as_ref().and_then(|labels| labels.get(key)) != Some(value) - }) - }) - { - return Err(invalid( - "Docker replacement does not match the accepted immutable input", - )); - } - for entry in expected.env.as_deref().unwrap_or_default() { - let (key, _) = entry - .split_once('=') - .ok_or_else(|| invalid("Docker bootstrap environment is invalid"))?; - let matches = actual - .env - .as_deref() - .unwrap_or_default() - .iter() - .filter(|value| value.split_once('=').is_some_and(|(name, _)| name == key)) - .collect::>(); - if matches.len() != 1 || matches[0] != entry { - return Err(invalid("Docker replacement bootstrap environment changed")); - } - } - let original_host = serde_json::to_value(&expected.host_config) - .map_err(|_| invalid("accepted Docker launch fence is invalid"))?; - let actual_host = serde_json::to_value(&container.host_config) - .map_err(|_| invalid("Docker replacement launch fence is invalid"))?; - for key in [ - "NetworkMode", - "CapDrop", - "CapAdd", - "Privileged", - "SecurityOpt", - "ReadonlyRootfs", - "Binds", - "Mounts", - "GroupAdd", - "Devices", - "DeviceRequests", - "PidMode", - "UsernsMode", - "IpcMode", - "VolumesFrom", - "AutoRemove", - "Sysctls", - "Tmpfs", - "Dns", - "DnsSearch", - "ExtraHosts", - "Memory", - "NanoCpus", - "PidsLimit", - ] { - if original_host[key] != actual_host[key] { - return Err(invalid("Docker replacement launch settings changed")); - } - } - Ok(()) -} - -fn read_published_boundary( - intent: &Intent, - config: &DockerDriverRuntimeConfig, -) -> Result<(BoundaryConfig, SandboxRuntimeDescriptor), Status> { - let directory = docker_boundary_state_dir_by_id(&intent.sandbox_id, config)?; - let bootstrap: BoundaryConfig = serde_json::from_slice( - &std::fs::read(directory.join(BOUNDARY_CONFIG_FILE)) - .map_err(|_| invalid("replacement Docker bootstrap is unavailable"))?, - ) - .map_err(|_| invalid("replacement Docker bootstrap is invalid"))?; - let descriptor: SandboxRuntimeDescriptor = serde_json::from_slice( - &std::fs::read(directory.join(RUNTIME_DESCRIPTOR_FILE)) - .map_err(|_| invalid("replacement Docker descriptor is unavailable"))?, - ) - .map_err(|_| invalid("replacement Docker descriptor is invalid"))?; - Ok((bootstrap, descriptor)) -} - -fn verify_boundary_resource_bindings( - intent: &Intent, - bootstrap: &BoundaryConfig, - descriptor: &SandboxRuntimeDescriptor, -) -> Result<(), Status> { - let target = intent - .target_container - .as_ref() - .ok_or_else(|| invalid("Docker replacement target is missing"))?; - let (_, expected) = decode_boundary(intent, target)?; - let expected: SandboxRuntimeDescriptor = serde_json::from_slice(&expected) - .map_err(|_| invalid("accepted Docker descriptor is invalid"))?; - // A launch can be interrupted between these files' atomic writes. Each - // must still identify the accepted resource, even when their launch-scoped - // generation/session differ. Only stopped Start with fresh auth repairs it. - for (id, generation, claims, identity, evidence) in [ - ( - &bootstrap.boundary_id, - &bootstrap.generation, - &bootstrap.resource_claims, - &bootstrap.workload_identity, - &bootstrap.provisioning_evidence, - ), - ( - &descriptor.boundary_id, - &descriptor.generation, - &descriptor.resource_claims, - &descriptor.workload_identity, - &descriptor.provisioning_evidence, - ), - ] { - if id != &intent.sandbox_id - || claims != &expected.resource_claims - || identity != &expected.workload_identity - || evidence - != &isolation::provisioning_evidence(target, generation) - .map_err(|_| invalid("replacement Docker evidence is invalid"))? - { - return Err(invalid("replacement Docker resource bindings changed")); - } - } - Ok(()) -} - -fn verify_published_boundary( - intent: &Intent, - config: &DockerDriverRuntimeConfig, -) -> Result<(), Status> { - let (bootstrap, descriptor) = read_published_boundary(intent, config)?; - verify_boundary_resource_bindings(intent, &bootstrap, &descriptor)?; - if bootstrap.generation != descriptor.generation - || bootstrap.session_id != descriptor.session_id - || bootstrap.provisioning_evidence != descriptor.provisioning_evidence - { - return Err(invalid( - "replacement Docker runtime evidence is inconsistent", - )); - } - Ok(()) -} - -fn require_owner( - container: &ContainerInspectResponse, - p: &SandboxUpdatePreconditions, - config: &DockerDriverRuntimeConfig, -) -> Result<(), Status> { - let labels = container - .config - .as_ref() - .and_then(|value| value.labels.as_ref()) - .ok_or_else(|| invalid("Docker image update lacks native ownership metadata"))?; - for (key, value) in [ - (LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE), - (LABEL_SANDBOX_NAMESPACE, config.sandbox_namespace.as_str()), - (LABEL_SANDBOX_ID, p.sandbox_id.as_str()), - (LABEL_SANDBOX_NAME, p.name.as_str()), - (LABEL_ISOLATION_ROLE, LABEL_ISOLATION_ROLE_SANDBOX), - ] { - if labels.get(key).map(String::as_str) != Some(value) { - return Err(invalid( - "Docker image update refused a changed resource owner or storage layout", - )); - } - } - require_stopped(container) -} - -fn decode_boundary(intent: &Intent, target_id: &str) -> Result<(Vec, Vec), Status> { - let mut bootstrap: BoundaryConfig = serde_json::from_slice(&intent.original_bootstrap) - .map_err(|_| invalid("saved Docker bootstrap is invalid"))?; - let mut descriptor: SandboxRuntimeDescriptor = - serde_json::from_slice(&intent.original_descriptor) - .map_err(|_| invalid("saved Docker runtime descriptor is invalid"))?; - if bootstrap.boundary_id != intent.sandbox_id - || descriptor.boundary_id != intent.sandbox_id - || bootstrap.generation != descriptor.generation - || bootstrap.resource_claims.get("docker.container_id") != Some(&intent.original_container) - || descriptor.resource_claims != bootstrap.resource_claims - || descriptor.workload_identity != bootstrap.workload_identity - || !descriptor - .resource_claims - .contains_key(workspace::RECORD_CLAIM) - { - return Err(invalid( - "Docker runtime evidence does not identify the original workload", - )); - } - let identity = &descriptor.workload_identity; - let identity = ResolvedWorkloadIdentity::new( - identity.uid, - identity.gid, - identity.supplementary_gids.clone(), - identity.source.clone(), - intent.image_id.clone(), - ) - .map_err(|_| invalid("Docker workload identity cannot be retained"))?; - let evidence = isolation::provisioning_evidence(target_id, &bootstrap.generation) - .map_err(|_| invalid("Docker replacement provisioning evidence is invalid"))?; - for claims in [ - &mut bootstrap.resource_claims, - &mut descriptor.resource_claims, - ] { - claims.insert("docker.container_id".into(), target_id.into()); - claims.insert("docker.image_identity".into(), intent.image_id.clone()); - } - bootstrap.workload_identity = identity.clone(); - descriptor.workload_identity = identity; - bootstrap.provisioning_evidence = evidence.clone(); - descriptor.provisioning_evidence = evidence; - Ok(( - bootstrap - .encode() - .map_err(|_| Status::internal("encode replacement bootstrap"))?, - serde_json::to_vec(&descriptor) - .map_err(|_| Status::internal("encode replacement descriptor"))?, - )) -} - -impl DockerComputeDriver { - /// Stopped image-only mutation for explicitly enabled persistent workspaces. - /// The gateway owns acceptance, retries and public lifecycle state. - pub async fn update_workload_image( - &self, - request: &UpdateSandboxConfigurationRequest, - ) -> Result<(), Status> { - let p = validate_request(request)?; - if self.config.workspace_storage != workspace::Storage::Persistent { - return Err(Status::unimplemented( - "Docker persistent workspace image updates are not enabled", - )); - } - self.verify_network_trust()?; - let _guard = self - .image_update_gates - .gate_for(&p.sandbox_id) - .lock_owned() - .await; - let previous = read(&self.config, &p.sandbox_id)?; - let mut intent = match previous { - Some(intent) if same_request(&intent, p) => intent, - Some(intent) if intent.phase != Phase::Applied || intent.revision >= p.revision => { - return Err(invalid( - "a conflicting or newer Docker image update is already recorded", - )); - } - _ => Box::pin(self.prepare_image_update(p)).await?, - }; - // A saved operation must retain independent storage authority even if - // interruption removed its original container before replay. - let claim = workspace::record_claim(&p.sandbox_id, &self.config)? - .ok_or_else(|| invalid("private Docker workspace record is missing"))?; - let descriptor: SandboxRuntimeDescriptor = - serde_json::from_slice(&intent.original_descriptor) - .map_err(|_| invalid("saved Docker runtime descriptor is invalid"))?; - if descriptor.resource_claims.get(workspace::RECORD_CLAIM) != Some(&claim) { - return Err(invalid( - "private Docker workspace record and accepted operation disagree", - )); - } - let _ = decode_boundary(&intent, "validation-only-target")?; - if p.validate_only { - return self.validate_update_resource(&intent, p).await; - } - if intent.phase == Phase::Applied { - return self.validate_update_resource(&intent, p).await; - } - save(&self.config, &intent)?; - Box::pin(self.replace_image_container(&mut intent, p)).await - } - - async fn prepare_image_update(&self, p: &SandboxUpdatePreconditions) -> Result { - let directory = docker_boundary_state_dir_by_id(&p.sandbox_id, &self.config)?; - let descriptor_bytes = std::fs::read(directory.join(RUNTIME_DESCRIPTOR_FILE)) - .map_err(|_| invalid("Docker image update requires the original native descriptor"))?; - let descriptor: SandboxRuntimeDescriptor = serde_json::from_slice(&descriptor_bytes) - .map_err(|_| invalid("Docker native descriptor is invalid"))?; - if descriptor.boundary_id != p.sandbox_id { - return Err(invalid( - "Docker native descriptor belongs to another sandbox", - )); - } - let source_id = descriptor - .resource_claims - .get("docker.container_id") - .ok_or_else(|| invalid("Docker native descriptor lacks its container identity"))?; - let source = self - .docker - .inspect_container(source_id, None) - .await - .map_err(|_| invalid("the original Docker workload is unavailable"))?; - if source.id.as_ref() != Some(source_id) { - return Err(invalid( - "Docker inspection did not return the original immutable container ID", - )); - } - require_owner(&source, p, &self.config)?; - self.admit_container_resources(&source).await?; - let original_image = self - .docker - .inspect_image(&p.expected_image) - .await - .map_err(|_| invalid("the expected original Docker image must be present locally"))?; - if original_image.id != source.image - || descriptor.resource_claims.get("docker.image_identity") != source.image.as_ref() - { - return Err(invalid( - "Docker workload image no longer matches the expected original", - )); - } - let target = self.docker.inspect_image(&p.image).await.map_err(|_| { - invalid("the target Docker image must be prepared locally before update") - })?; - let image_id = target - .id - .ok_or_else(|| invalid("target Docker image lacks immutable identity"))?; - let image_config = target - .config - .ok_or_else(|| invalid("target Docker image lacks configuration"))?; - if driver_mounts::resolve_oci_workspace_root( - image_config.working_dir.as_deref().unwrap_or_default(), - ) - .map_err(Status::failed_precondition)? - != "/sandbox" - || image_config - .volumes - .as_ref() - .is_some_and(|volumes| !volumes.is_empty()) - { - return Err(invalid( - "target Docker image requires an unsupported workspace or image volume layout", - )); - } - let source_config = source - .config - .as_ref() - .ok_or_else(|| invalid("Docker workload configuration is missing"))?; - if source_config - .volumes - .as_ref() - .is_some_and(|volumes| !volumes.is_empty()) - { - return Err(invalid( - "original Docker image has anonymous-volume state outside the initial update layout", - )); - } - let expected_user = format!( - "{}:{}", - descriptor.workload_identity.uid, descriptor.workload_identity.gid - ); - if source_config.user.as_deref() != Some(expected_user.as_str()) { - return Err(invalid( - "Docker native descriptor and workload user disagree", - )); - } - // The update RPC carries no identity-policy override. Admit only an - // explicit numeric USER matching the recorded non-root identity; - // symbolic or implicit users need image account resolution, which the - // initial image-only updater does not perform. - let target_identity = image_config.user.as_deref().and_then(|user| { - let (uid, gid) = user.split_once(':')?; - if uid.is_empty() - || gid.is_empty() - || !uid - .bytes() - .chain(gid.bytes()) - .all(|byte| byte.is_ascii_digit()) - { - return None; - } - Some((uid.parse::().ok()?, gid.parse::().ok()?)) - }); - if target_identity - != Some(( - descriptor.workload_identity.uid, - descriptor.workload_identity.gid, - )) - { - return Err(invalid( - "target Docker image must declare matching numeric non-root UID:GID", - )); - } - let mut body: ContainerCreateBody = serde_json::from_value( - serde_json::to_value(source_config) - .map_err(|_| invalid("Docker workload configuration cannot be retained"))?, - ) - .map_err(|_| invalid("Docker workload configuration cannot be retained"))?; - body.host_config.clone_from(&source.host_config); - body.image = Some(image_id.clone()); - // Let the new image supply PATH and other image defaults. Only the - // driver-owned bootstrap environment belongs to the container spec. - body.env = Some( - source_config - .env - .as_deref() - .unwrap_or_default() - .iter() - .filter(|entry| { - entry.split_once('=').is_some_and(|(name, _)| { - matches!( - name, - openshell_core::sandbox_env::LOG_LEVEL - | openshell_core::sandbox_env::TELEMETRY_ENABLED - ) - }) - }) - .cloned() - .collect(), - ); - let labels = body - .labels - .as_mut() - .ok_or_else(|| invalid("Docker workload labels are missing"))?; - labels.insert(OPERATION_LABEL.into(), p.operation_id.clone()); - labels.insert(REVISION_LABEL.into(), p.revision.to_string()); - let container_name = source - .name - .as_deref() - .and_then(|name| name.strip_prefix('/')) - .filter(|name| !name.is_empty()) - .ok_or_else(|| invalid("Docker workload canonical name is missing"))? - .to_string(); - let original_bootstrap = std::fs::read(directory.join(BOUNDARY_CONFIG_FILE)) - .map_err(|_| invalid("original Docker bootstrap is unavailable"))?; - let intent = Intent { - version: 1, - namespace: self.config.sandbox_namespace.clone(), - sandbox_id: p.sandbox_id.clone(), - sandbox_name: p.name.clone(), - operation_id: p.operation_id.clone(), - revision: p.revision, - previous_image: p.expected_image.clone(), - image: p.image.clone(), - image_id, - original_container: source_id.clone(), - container_name, - target_container: None, - body, - original_bootstrap, - original_descriptor: descriptor_bytes, - phase: Phase::Prepared, - }; - // Validate both halves before accepting any destructive Docker action. - let _ = decode_boundary(&intent, "validation-only-target")?; - Ok(intent) - } - - async fn validate_update_resource( - &self, - intent: &Intent, - p: &SandboxUpdatePreconditions, - ) -> Result<(), Status> { - let id = intent - .target_container - .as_ref() - .unwrap_or(&intent.original_container); - let container = self - .docker - .inspect_container(id, None) - .await - .map_err(|_| invalid("recorded Docker update resource is unavailable"))?; - require_owner(&container, p, &self.config)?; - self.admit_container_resources(&container).await?; - if intent.phase != Phase::Prepared { - verify_replacement(&container, intent)?; - } - if intent.phase == Phase::Applied { - verify_published_boundary(intent, &self.config)?; - } - Ok(()) - } - - async fn replace_image_container( - &self, - intent: &mut Intent, - p: &SandboxUpdatePreconditions, - ) -> Result<(), Status> { - if intent.phase == Phase::Prepared { - match self - .docker - .inspect_container(&intent.original_container, None) - .await - { - Ok(source) => { - require_owner(&source, p, &self.config)?; - self.admit_container_resources(&source).await?; - if source.image.as_ref() - != serde_json::from_slice::( - &intent.original_descriptor, - ) - .map_err(|_| invalid("original Docker descriptor changed"))? - .resource_claims - .get("docker.image_identity") - { - return Err(invalid( - "original Docker image changed after update acceptance", - )); - } - // No force and no volume-removal flag. The gateway owns the - // stopped lifecycle and user data remains in its volume. - self.docker - .remove_container(&intent.original_container, None) - .await - .map_err(|_| { - Status::unavailable( - "remove stopped Docker workload; retry the accepted update", - ) - })?; - } - Err(error) if is_not_found_error(&error) => {} - Err(_) => { - return Err(Status::unavailable( - "inspect original Docker workload during update", - )); - } - } - let target = match self - .docker - .inspect_container(&intent.container_name, None) - .await - { - Ok(target) => target, - Err(error) if is_not_found_error(&error) => { - let created = self - .docker - .create_container( - Some( - CreateContainerOptionsBuilder::default() - .name(&intent.container_name) - .build(), - ), - intent.body.clone(), - ) - .await - .map_err(|_| { - Status::unavailable( - "create corrected Docker workload; retry the accepted update", - ) - })?; - let target = self - .docker - .inspect_container(&created.id, None) - .await - .map_err(|_| Status::unavailable("inspect corrected Docker workload"))?; - if target.id.as_ref() != Some(&created.id) { - return Err(invalid( - "Docker replacement inspection returned another container", - )); - } - target - } - Err(_) => return Err(Status::unavailable("inspect pending Docker replacement")), - }; - require_owner(&target, p, &self.config)?; - self.admit_container_resources(&target).await?; - verify_replacement(&target, intent)?; - let labels = target - .config - .as_ref() - .and_then(|value| value.labels.as_ref()) - .ok_or_else(|| invalid("replacement ownership is missing"))?; - if target.image.as_ref() != Some(&intent.image_id) - || labels.get(OPERATION_LABEL) != Some(&intent.operation_id) - || labels.get(REVISION_LABEL) != Some(&intent.revision.to_string()) - || target.state.as_ref().and_then(|value| value.status) - != Some(ContainerStateStatusEnum::CREATED) - { - return Err(invalid( - "Docker replacement does not match the accepted operation", - )); - } - intent.target_container = - Some(target.id.ok_or_else(|| { - invalid("Docker replacement lacks its immutable container ID") - })?); - intent.phase = Phase::Replaced; - save(&self.config, intent)?; - } - self.validate_update_resource(intent, p).await?; - let target = intent - .target_container - .as_ref() - .ok_or_else(|| invalid("Docker replacement checkpoint lacks its target"))?; - let (bootstrap, descriptor) = decode_boundary(intent, target)?; - let directory = docker_boundary_state_dir_by_id(&intent.sandbox_id, &self.config)?; - durable_write(&directory.join(BOUNDARY_CONFIG_FILE), &bootstrap)?; - durable_write(&directory.join(RUNTIME_DESCRIPTOR_FILE), &descriptor)?; - verify_published_boundary(intent, &self.config)?; - intent.phase = Phase::Applied; - save(&self.config, intent) - } -} - -/// Same weak per-resource lock pattern as the Kubernetes driver. This is a -/// driver mutex, not another lifecycle controller or endpoint service. -#[derive(Default)] -pub struct Gates { - values: std::sync::Mutex>>>, -} - -impl Gates { - pub fn gate_for(&self, id: &str) -> Arc> { - let mut values = self - .values - .lock() - .expect("Docker image-update gate poisoned"); - values.retain(|_, value| value.strong_count() > 0); - if let Some(value) = values.get(id).and_then(std::sync::Weak::upgrade) { - return value; - } - let gate = Arc::new(Mutex::new(())); - values.insert(id.into(), Arc::downgrade(&gate)); - gate - } -} - -fn record_ids(config: &DockerDriverRuntimeConfig) -> Result, Status> { - let sample = docker_boundary_state_dir_by_id("discovery", config)?; - let root = sample - .parent() - .ok_or_else(|| invalid("Docker native state root is missing"))?; - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(_) => return Err(invalid("Docker pending update inventory cannot be read")), - }; - let mut ids = Vec::new(); - for entry in entries { - let entry = entry.map_err(|_| invalid("Docker pending update inventory is incomplete"))?; - if !entry - .file_type() - .map_err(|_| invalid("Docker native state type is unavailable"))? - .is_dir() - { - continue; - } - let Some(id) = entry.file_name().to_str().map(str::to_owned) else { - continue; - }; - if valid_native_id(&id) - && read(config, &id)?.is_some_and(|intent| intent.phase != Phase::Applied) - { - ids.push(id); - } - } - Ok(ids) -} - -fn valid_native_id(id: &str) -> bool { - !id.is_empty() - && id.len() <= 128 - && id - .bytes() - .all(|v| v.is_ascii_alphanumeric() || matches!(v, b'-' | b'_')) -} - -fn snapshot(intent: &Intent) -> DriverSandbox { - pending_sandbox_snapshot( - &DriverSandbox { - id: intent.sandbox_id.clone(), - name: intent.sandbox_name.clone(), - namespace: intent.namespace.clone(), - workspace: intent - .body - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_SANDBOX_WORKSPACE)) - .cloned() - .unwrap_or_default(), - ..Default::default() - }, - &intent.namespace, - DriverCondition { - r#type: "Ready".into(), - status: "False".into(), - reason: openshell_core::driver_utils::CONDITION_STOPPED.into(), - message: "Stopped; an accepted workload image update awaits recovery".into(), - transition_time: None, - }, - false, - ) -} - -pub fn pending_ids(config: &DockerDriverRuntimeConfig) -> Result, Status> { - record_ids(config) -} - -pub fn pending_snapshots(config: &DockerDriverRuntimeConfig) -> Result, Status> { - record_ids(config)? - .iter() - .map(|id| { - read(config, id)? - .map(|intent| snapshot(&intent)) - .ok_or_else(|| invalid("Docker pending update changed during observation")) - }) - .collect() -} - -pub fn pending_snapshot( - config: &DockerDriverRuntimeConfig, - id: &str, - name: &str, -) -> Result, Status> { - if !id.is_empty() { - if !valid_native_id(id) { - return Ok(None); - } - let Some(intent) = read(config, id)? else { - return Ok(None); - }; - if !name.is_empty() && name != intent.sandbox_name { - return Err(invalid( - "Docker update name does not match its native identity", - )); - } - return Ok((intent.phase != Phase::Applied).then(|| snapshot(&intent))); - } - let matches = pending_snapshots(config)? - .into_iter() - .filter(|value| value.name == name) - .collect::>(); - match matches.len() { - 0 => Ok(None), - 1 => Ok(matches.into_iter().next()), - _ => Err(invalid( - "Docker pending update name is ambiguous; use its native ID", - )), - } -} - -pub fn require_settled(config: &DockerDriverRuntimeConfig, id: &str) -> Result<(), Status> { - if valid_native_id(id) && read(config, id)?.is_some_and(|intent| intent.phase != Phase::Applied) - { - return Err(invalid( - "resume the accepted Docker image update before starting the workload", - )); - } - Ok(()) -} - -pub enum LaunchValidation { - Complete, - BeforeStoppedRotation, -} - -pub fn validate_committed_resource( - config: &DockerDriverRuntimeConfig, - id: &str, - container: &ContainerInspectResponse, - validation: LaunchValidation, -) -> Result<(), Status> { - if !valid_native_id(id) { - return Ok(()); - } - if let Some(intent) = read(config, id)? { - if intent.phase != Phase::Applied { - return Err(invalid("Docker image update is not settled")); - } - verify_replacement(container, &intent)?; - match validation { - LaunchValidation::Complete => return verify_published_boundary(&intent, config), - // Use the fresh inspect, not just the earlier list response, to - // prove that credentials are rotated only on a stopped workload. - LaunchValidation::BeforeStoppedRotation => require_stopped(container)?, - } - let (bootstrap, descriptor) = read_published_boundary(&intent, config)?; - verify_boundary_resource_bindings(&intent, &bootstrap, &descriptor)?; - } - Ok(()) -} - -/// Enforce launch-pair consistency before using credentials or starting any -/// process. Resource bindings must also be checked before credential rotation. -pub fn validate_committed_boundary( - config: &DockerDriverRuntimeConfig, - id: &str, -) -> Result<(), Status> { - if valid_native_id(id) - && let Some(intent) = read(config, id)? - { - if intent.phase != Phase::Applied { - return Err(invalid("Docker image update is not settled")); - } - verify_published_boundary(&intent, config)?; - } - Ok(()) -} - -#[cfg(test)] -mod tests; diff --git a/crates/openshell-driver-docker/src/image_update/tests.rs b/crates/openshell-driver-docker/src/image_update/tests.rs deleted file mode 100644 index 3ba13f7e21..0000000000 --- a/crates/openshell-driver-docker/src/image_update/tests.rs +++ /dev/null @@ -1,1212 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use super::*; -use crate::tests::{ - runtime_config, test_driver_with_config, test_launch_authentication, test_sandbox, - test_workload_identity, -}; -use crate::workspace::tests::{docker_api, fixture_for}; -use bollard::models::Volume; - -mod live; - -type Reply = (&'static str, String, u16, serde_json::Value); - -struct Fixture { - source: ContainerInspectResponse, - volume: Volume, - config: DockerDriverRuntimeConfig, - request: UpdateSandboxConfigurationRequest, - directory: PathBuf, -} - -impl Fixture { - fn new() -> Self { - let unique = openshell_core::SandboxSessionId::new().to_string(); - let mut sandbox = test_sandbox(); - sandbox.id = unique.clone(); - sandbox.workspace = "synthetic-update".into(); - let mut config = runtime_config(); - config.sandbox_namespace = format!("image-update-test-{unique}"); - config.workspace_storage = workspace::Storage::Persistent; - let (mut source, volume, config) = fixture_for(sandbox.clone(), config); - let labels = source.config.as_mut().unwrap().labels.as_mut().unwrap(); - labels.insert(LABEL_SANDBOX_NAME.into(), sandbox.name.clone()); - labels.insert(LABEL_MANAGED_BY.into(), LABEL_MANAGED_BY_VALUE.into()); - labels.insert( - LABEL_ISOLATION_ROLE.into(), - LABEL_ISOLATION_ROLE_SANDBOX.into(), - ); - labels.insert( - LABEL_ISOLATION_BACKEND.into(), - LABEL_ISOLATION_BACKEND_OPEN_SHELL.into(), - ); - source.id = Some("container-A".into()); - source.name = Some(format!("/openshell-fixture-{unique}")); - source.image = Some("sha256:immutable".into()); - let original_config = source.config.as_mut().unwrap(); - original_config.image = Some("sha256:immutable".into()); - original_config.working_dir = Some("/".into()); - original_config.entrypoint = Some(vec![SANDBOX_BINARY_PATH.into()]); - original_config.cmd = Some(vec![ - "--bootstrap".into(), - BOUNDARY_CONFIG_MOUNT_PATH.into(), - ]); - original_config.env = Some(vec![ - format!("{}=debug", openshell_core::sandbox_env::LOG_LEVEL), - format!("{}=false", openshell_core::sandbox_env::TELEMETRY_ENABLED), - "PATH=/original-image/path".into(), - ]); - source.host_config = Some(serde_json::from_value(serde_json::json!({ - "NetworkMode":"none", "CapDrop":["ALL"], "SecurityOpt":["no-new-privileges:true"], - "GroupAdd":["1236"], "Mounts":[{"Type":"volume", "Source":volume.name, "Target":"/sandbox", "ReadOnly":false, "VolumeOptions":{"NoCopy":true}}] - })).unwrap()); - source.state = Some(serde_json::from_value(serde_json::json!({"Status":"exited", "Running":false, "Paused":false, "Restarting":false})).unwrap()); - source.network_settings = - Some(serde_json::from_value(serde_json::json!({"Networks":{}})).unwrap()); - let authentication = - decode_docker_launch_authentication(&test_launch_authentication()).unwrap(); - let tls = generate_sandbox_tls_material(authentication.supervisor.session_id).unwrap(); - let mut provisioned = isolation::DockerBoundarySpec { - boundary_id: sandbox.id.clone(), - generation: authentication.supervisor.runtime_generation.to_string(), - session_id: authentication.supervisor.session_id, - session_rotation: authentication.supervisor.session_rotation, - auth_epoch: authentication.supervisor.auth_epoch, - gateway_id: authentication.gateway_id, - verification_keys: gateway_verification_keys(&authentication.verification_keys) - .unwrap(), - container_id: "container-A".into(), - image_identity: "sha256:immutable".into(), - gpu_requested: false, - listener_socket: BOUNDARY_SOCKET_MOUNT_PATH.into(), - control_socket: BOUNDARY_SOCKET_MOUNT_PATH.into(), - sandbox_tls: SandboxTlsServerConfig { - certificate_chain_path: BOUNDARY_CERTIFICATE_MOUNT_PATH.into(), - private_key_path: BOUNDARY_PRIVATE_KEY_MOUNT_PATH.into(), - }, - supervisor_tls: SandboxTlsClientConfig { - server_name: tls.server_name, - trust_anchor_pem: tls.trust_anchor_pem, - }, - host_gateway_ip: None, - workload_identity: test_workload_identity(), - child_env: HashMap::new(), - } - .provision() - .unwrap(); - let directory = prepare_docker_boundary_state_dir(&sandbox, &config).unwrap(); - let record = - workspace::record_bytes(&sandbox.id, &config, &volume, &test_workload_identity()) - .unwrap(); - durable_write(&directory.join(workspace::RECORD_FILE), &record).unwrap(); - let claim = String::from_utf8(record).unwrap(); - for claims in [ - &mut provisioned.boundary_config.resource_claims, - &mut provisioned.runtime_descriptor.resource_claims, - ] { - claims.insert(workspace::RECORD_CLAIM.into(), claim.clone()); - } - durable_write( - &directory.join(BOUNDARY_CONFIG_FILE), - &provisioned.boundary_config.encode().unwrap(), - ) - .unwrap(); - durable_write( - &directory.join(RUNTIME_DESCRIPTOR_FILE), - &serde_json::to_vec(&provisioned.runtime_descriptor).unwrap(), - ) - .unwrap(); - Self { - source, - volume, - config, - directory, - request: UpdateSandboxConfigurationRequest { - preconditions: Some(SandboxUpdatePreconditions { - sandbox_id: sandbox.id, - name: sandbox.name, - image: "corrected-image".into(), - expected_image: "old-image".into(), - expected_runtime_identity: String::new(), - operation_id: openshell_core::SandboxSessionId::new().to_string(), - validate_only: false, - revision: 1, - }), - ..Default::default() - }, - } - } - - fn p(&self) -> &SandboxUpdatePreconditions { - self.request.preconditions.as_ref().unwrap() - } - fn volume_reply(&self) -> Reply { - ( - "GET", - format!("/volumes/{}", self.volume.name), - 200, - serde_json::to_value(&self.volume).unwrap(), - ) - } - fn source_reply(&self) -> Reply { - ( - "GET", - "/containers/container-A/json".into(), - 200, - serde_json::to_value(&self.source).unwrap(), - ) - } - fn preflight(&self) -> Vec { - vec![ - self.source_reply(), - self.volume_reply(), - ( - "GET", - "/images/old-image/json".into(), - 200, - serde_json::json!({"Id":"sha256:immutable"}), - ), - ( - "GET", - "/images/corrected-image/json".into(), - 200, - serde_json::json!({"Id":"sha256:corrected", "Config":{"WorkingDir":"/sandbox", "User":"1234:1235"}}), - ), - ] - } - fn start_replies(&self, running: bool) -> Vec { - let mut target = self.target(); - let state = if running { "running" } else { "exited" }; - target.state.as_mut().unwrap().running = Some(running); - target.state.as_mut().unwrap().status = Some(if running { - ContainerStateStatusEnum::RUNNING - } else { - ContainerStateStatusEnum::EXITED - }); - vec![ - ( - "GET", - String::new(), - 200, - serde_json::json!([{ - "Id":"container-B", "Names":[target.name], "State":state, - "Labels":target.config.as_ref().unwrap().labels - }]), - ), - ( - "GET", - "/containers/container-B/json".into(), - 200, - serde_json::to_value(target).unwrap(), - ), - self.volume_reply(), - ] - } - fn target(&self) -> ContainerInspectResponse { - let mut target = self.source.clone(); - target.id = Some("container-B".into()); - target.image = Some("sha256:corrected".into()); - let config = target.config.as_mut().unwrap(); - config.image = Some("sha256:corrected".into()); - config - .env - .as_mut() - .unwrap() - .retain(|value| !value.starts_with("PATH=")); - config - .env - .as_mut() - .unwrap() - .push("PATH=/corrected-image/path".into()); - config - .labels - .as_mut() - .unwrap() - .insert(OPERATION_LABEL.into(), self.p().operation_id.clone()); - config - .labels - .as_mut() - .unwrap() - .insert(REVISION_LABEL.into(), self.p().revision.to_string()); - target.state.as_mut().unwrap().status = Some(ContainerStateStatusEnum::CREATED); - target - } - fn target_reply(&self, lookup: &str) -> Reply { - ( - "GET", - format!("/containers/{lookup}/json"), - 200, - serde_json::to_value(self.target()).unwrap(), - ) - } - fn name(&self) -> &str { - self.source - .name - .as_deref() - .unwrap() - .strip_prefix('/') - .unwrap() - } - fn after_create(&self) -> Vec { - vec![ - self.target_reply("container-B"), - self.volume_reply(), - self.target_reply("container-B"), - self.volume_reply(), - ] - } - fn create_reply(&self, status: u16) -> Reply { - ( - "POST", - format!("/containers/create?name={}&platform=", self.name()), - status, - if status == 201 { - serde_json::json!({"Id":"container-B", "Warnings":[]}) - } else { - serde_json::json!({"message":"synthetic creation interruption"}) - }, - ) - } - fn missing(id: &str) -> Reply { - ( - "GET", - format!("/containers/{id}/json"), - 404, - serde_json::json!({"message":"not found"}), - ) - } - fn apply_replies(&self) -> Vec { - let mut replies = self.preflight(); - replies.extend([ - self.source_reply(), - self.volume_reply(), - ( - "DELETE", - "/containers/container-A".into(), - 204, - serde_json::Value::Null, - ), - Self::missing(self.name()), - self.create_reply(201), - ]); - replies.extend(self.after_create()); - replies - } - async fn call( - &self, - replies: Vec, - request: &UpdateSandboxConfigurationRequest, - ) -> (Result<(), Status>, Vec) { - let (docker, server) = docker_api(replies).await; - let mut driver = test_driver_with_config(self.config.clone()); - driver.docker = Arc::new(docker); - let result = Box::pin(driver.update_workload_image(request)).await; - (result, server.await.unwrap()) - } - - async fn grpc_call( - &self, - config: DockerDriverRuntimeConfig, - replies: Vec, - request: UpdateSandboxConfigurationRequest, - ) -> Result<(), Status> { - use openshell_core::proto::compute::v1::{ - compute_driver_configuration_updates_client::ComputeDriverConfigurationUpdatesClient, - compute_driver_configuration_updates_server::ComputeDriverConfigurationUpdatesServer, - }; - let (docker, api) = docker_api(replies).await; - let mut driver = test_driver_with_config(config); - driver.docker = Arc::new(docker); - let service = ComputeDriverService::new_in_process(driver); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let (shutdown, stopped) = oneshot::channel(); - let server = tokio::spawn(async move { - tonic::transport::Server::builder() - .add_service(ComputeDriverConfigurationUpdatesServer::new(service)) - .serve_with_incoming_shutdown( - tokio_stream::wrappers::TcpListenerStream::new(listener), - async { - let _ = stopped.await; - }, - ) - .await - .unwrap(); - }); - let mut client = - ComputeDriverConfigurationUpdatesClient::connect(format!("http://{address}")) - .await - .unwrap(); - let result = client - .update_sandbox_configuration(request) - .await - .map(|_| ()); - let _ = shutdown.send(()); - server.await.unwrap(); - api.await.unwrap(); - result - } -} - -impl Drop for Fixture { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.directory); - if let Some(parent) = self.directory.parent() { - let _ = std::fs::remove_dir(parent); - } - } -} - -#[tokio::test] -async fn persistent_update_requires_the_private_workspace_record() { - for mutation in ["missing", "invalid", "foreign-namespace", "foreign-uid"] { - let fixture = Fixture::new(); - let path = fixture.directory.join(workspace::RECORD_FILE); - match mutation { - "missing" => std::fs::remove_file(&path).unwrap(), - "invalid" => std::fs::write(&path, "not-json").unwrap(), - _ => { - let mut record: serde_json::Value = - serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); - if mutation == "foreign-namespace" { - record["namespace"] = "foreign".into(); - } else { - record["uid"] = 2000.into(); - } - std::fs::write(&path, serde_json::to_vec(&record).unwrap()).unwrap(); - } - } - let (result, requests) = fixture - .call(vec![fixture.source_reply()], &fixture.request) - .await; - assert_eq!(result.unwrap_err().code(), tonic::Code::FailedPrecondition); - assert_eq!(requests.len(), 1); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .is_none() - ); - } -} - -#[tokio::test] -async fn replay_requires_storage_authority_before_any_docker_action() { - for mutation in ["missing", "changed"] { - let fixture = Fixture::new(); - let (docker, server) = docker_api(fixture.preflight()).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let intent = driver.prepare_image_update(fixture.p()).await.unwrap(); - server.await.unwrap(); - save(&fixture.config, &intent).unwrap(); - let checkpoint = - std::fs::read(path(&fixture.config, &fixture.p().sandbox_id).unwrap()).unwrap(); - let record = fixture.directory.join(workspace::RECORD_FILE); - if mutation == "missing" { - std::fs::remove_file(&record).unwrap(); - } else { - let mut value: serde_json::Value = - serde_json::from_slice(&std::fs::read(&record).unwrap()).unwrap(); - value["uid"] = 2000.into(); - std::fs::write(&record, serde_json::to_vec(&value).unwrap()).unwrap(); - } - let (result, requests) = fixture.call(vec![], &fixture.request).await; - assert_eq!(result.unwrap_err().code(), tonic::Code::FailedPrecondition); - assert!(requests.is_empty()); - assert_eq!( - std::fs::read(path(&fixture.config, &fixture.p().sandbox_id).unwrap()).unwrap(), - checkpoint - ); - } -} - -#[tokio::test] -async fn incompatible_target_identity_is_rejected_before_checkpoint_or_deletion() { - // Symbolic and implicit identities require account lookup. The initial - // updater rejects those representations rather than assuming that the - // source identity can execute a different image's application. - for user in [ - "2000:2000", - "1234:2000", - "other:other", - "1234:other", - "1234", - "", - ] { - let fixture = Fixture::new(); - let bootstrap = std::fs::read(fixture.directory.join(BOUNDARY_CONFIG_FILE)).unwrap(); - let descriptor = std::fs::read(fixture.directory.join(RUNTIME_DESCRIPTOR_FILE)).unwrap(); - let mut replies = fixture.preflight(); - replies.last_mut().unwrap().3["Config"]["User"] = user.into(); - let (result, requests) = fixture.call(replies, &fixture.request).await; - assert!( - matches!(result, Err(ref error) if error.code() == tonic::Code::FailedPrecondition), - "accepted target USER {user:?}" - ); - // The fake endpoint accepts only the four read-only preflight calls. - assert_eq!(requests.len(), 4); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .is_none() - ); - assert_eq!( - std::fs::read(fixture.directory.join(BOUNDARY_CONFIG_FILE)).unwrap(), - bootstrap - ); - assert_eq!( - std::fs::read(fixture.directory.join(RUNTIME_DESCRIPTOR_FILE)).unwrap(), - descriptor - ); - } -} - -#[tokio::test] -async fn validation_only_checks_original_without_writing_an_intent_or_replacing() { - let fixture = Fixture::new(); - let mut request = fixture.request.clone(); - request.preconditions.as_mut().unwrap().validate_only = true; - let original = std::fs::read(fixture.directory.join(RUNTIME_DESCRIPTOR_FILE)).unwrap(); - let mut replies = fixture.preflight(); - replies.extend([fixture.source_reply(), fixture.volume_reply()]); - fixture.call(replies, &request).await.0.unwrap(); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .is_none() - ); - assert_eq!( - std::fs::read(fixture.directory.join(RUNTIME_DESCRIPTOR_FILE)).unwrap(), - original - ); -} - -#[tokio::test] -async fn image_replacement_keeps_native_and_volume_identity_and_publishes_new_evidence() { - let fixture = Fixture::new(); - let (result, requests) = fixture - .call(fixture.apply_replies(), &fixture.request) - .await; - result.unwrap(); - let intent = read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap(); - assert!(intent.phase == Phase::Applied); - assert_eq!(intent.sandbox_id, fixture.p().sandbox_id); - assert_eq!(intent.target_container.as_deref(), Some("container-B")); - assert_eq!(requests[8]["Image"], "sha256:corrected"); - assert!( - !requests[8]["Env"] - .as_array() - .unwrap() - .iter() - .any(|value| value.as_str().unwrap().starts_with("PATH=")) - ); - let descriptor: SandboxRuntimeDescriptor = serde_json::from_slice( - &std::fs::read(fixture.directory.join(RUNTIME_DESCRIPTOR_FILE)).unwrap(), - ) - .unwrap(); - assert_eq!( - descriptor.resource_claims["docker.container_id"], - "container-B" - ); - assert_eq!( - descriptor.resource_claims["docker.image_identity"], - "sha256:corrected" - ); - assert_eq!( - descriptor.resource_claims[workspace::RECORD_CLAIM], - workspace::record_claim(&fixture.p().sandbox_id, &fixture.config) - .unwrap() - .unwrap() - ); -} - -#[tokio::test] -async fn running_original_refuses_before_volume_read_or_checkpoint() { - let mut fixture = Fixture::new(); - fixture.source.state.as_mut().unwrap().running = Some(true); - fixture.source.state.as_mut().unwrap().status = Some(ContainerStateStatusEnum::RUNNING); - let error = fixture - .call(vec![fixture.source_reply()], &fixture.request) - .await - .0 - .unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .is_none() - ); -} - -#[tokio::test] -async fn failed_target_creation_recovers_same_operation_in_a_fresh_driver() { - let fixture = Fixture::new(); - let mut replies = fixture.preflight(); - replies.extend([ - fixture.source_reply(), - fixture.volume_reply(), - ( - "DELETE", - "/containers/container-A".into(), - 204, - serde_json::Value::Null, - ), - Fixture::missing(fixture.name()), - fixture.create_reply(500), - ]); - assert_eq!( - fixture - .call(replies, &fixture.request) - .await - .0 - .unwrap_err() - .code(), - tonic::Code::Unavailable - ); - let before = read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap(); - assert!(before.phase == Phase::Prepared); - let mut recovery = vec![ - Fixture::missing("container-A"), - Fixture::missing(fixture.name()), - fixture.create_reply(201), - ]; - recovery.extend(fixture.after_create()); - fixture.call(recovery, &fixture.request).await.0.unwrap(); - let applied = read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap(); - assert!(applied.phase == Phase::Applied); - assert_eq!(applied.operation_id, before.operation_id); - fixture - .call( - vec![fixture.target_reply("container-B"), fixture.volume_reply()], - &fixture.request, - ) - .await - .0 - .unwrap(); -} - -#[tokio::test] -async fn target_created_before_checkpoint_is_reconciled_without_another_create() { - let fixture = Fixture::new(); - let (docker, server) = docker_api(fixture.preflight()).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let intent = driver.prepare_image_update(fixture.p()).await.unwrap(); - server.await.unwrap(); - save(&fixture.config, &intent).unwrap(); - let mut replies = vec![ - Fixture::missing("container-A"), - fixture.target_reply(fixture.name()), - fixture.volume_reply(), - ]; - replies.extend([fixture.target_reply("container-B"), fixture.volume_reply()]); - fixture.call(replies, &fixture.request).await.0.unwrap(); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap() - .phase - == Phase::Applied - ); -} - -#[test] -fn request_validation_rejects_paths_unsupported_mutations_and_foreign_compute_identity() { - let fixture = Fixture::new(); - let mut request = fixture.request.clone(); - request.preconditions.as_mut().unwrap().sandbox_id = "../foreign".into(); - assert!(validate_request(&request).is_err()); - request = fixture.request.clone(); - request - .preconditions - .as_mut() - .unwrap() - .expected_runtime_identity = "foreign".into(); - assert!(validate_request(&request).is_err()); - request = fixture.request.clone(); - request.environment = - Some(openshell_core::proto::compute::v1::SandboxEnvironmentUpdate::default()); - assert_eq!( - validate_request(&request).unwrap_err().code(), - tonic::Code::Unimplemented - ); -} - -#[tokio::test] -async fn interrupted_boundary_publication_is_repaired_from_the_same_native_intent() { - let fixture = Fixture::new(); - fixture - .call(fixture.apply_replies(), &fixture.request) - .await - .0 - .unwrap(); - let mut intent = read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap(); - intent.phase = Phase::Replaced; - save(&fixture.config, &intent).unwrap(); - durable_write( - &fixture.directory.join(BOUNDARY_CONFIG_FILE), - b"{incomplete", - ) - .unwrap(); - fixture - .call( - vec![fixture.target_reply("container-B"), fixture.volume_reply()], - &fixture.request, - ) - .await - .0 - .unwrap(); - let applied = read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap(); - assert!(applied.phase == Phase::Applied); - verify_published_boundary(&applied, &fixture.config).unwrap(); - assert_eq!(applied.operation_id, intent.operation_id); -} - -#[tokio::test] -async fn same_name_target_with_another_operation_is_not_adopted() { - let fixture = Fixture::new(); - let (docker, server) = docker_api(fixture.preflight()).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let intent = driver.prepare_image_update(fixture.p()).await.unwrap(); - server.await.unwrap(); - save(&fixture.config, &intent).unwrap(); - let mut foreign = fixture.target(); - foreign - .config - .as_mut() - .unwrap() - .labels - .as_mut() - .unwrap() - .insert(OPERATION_LABEL.into(), "foreign-operation".into()); - let replies = vec![ - Fixture::missing("container-A"), - ( - "GET", - format!("/containers/{}/json", fixture.name()), - 200, - serde_json::to_value(foreign).unwrap(), - ), - fixture.volume_reply(), - ]; - let error = fixture.call(replies, &fixture.request).await.0.unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap() - .phase - == Phase::Prepared - ); - assert_eq!( - std::fs::read(fixture.directory.join(RUNTIME_DESCRIPTOR_FILE)).unwrap(), - intent.original_descriptor - ); -} - -#[tokio::test] -async fn conflicting_replay_refuses_before_docker_or_checkpoint_writes() { - let fixture = Fixture::new(); - fixture - .call(fixture.apply_replies(), &fixture.request) - .await - .0 - .unwrap(); - let checkpoint = - std::fs::read(path(&fixture.config, &fixture.p().sandbox_id).unwrap()).unwrap(); - let mut conflicting = fixture.request.clone(); - conflicting.preconditions.as_mut().unwrap().operation_id = - openshell_core::SandboxSessionId::new().to_string(); - let error = fixture.call(vec![], &conflicting).await.0.unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert_eq!( - std::fs::read(path(&fixture.config, &fixture.p().sandbox_id).unwrap()).unwrap(), - checkpoint - ); -} - -#[tokio::test] -async fn replacement_cannot_substitute_another_persistent_volume_record() { - let fixture = Fixture::new(); - let (docker, server) = docker_api(fixture.preflight()).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let intent = driver.prepare_image_update(fixture.p()).await.unwrap(); - server.await.unwrap(); - let mut target = fixture.target(); - verify_replacement(&target, &intent).unwrap(); - target - .host_config - .as_mut() - .unwrap() - .mounts - .as_mut() - .unwrap()[0] - .source = Some("foreign-volume".into()); - assert_eq!( - verify_replacement(&target, &intent).unwrap_err().code(), - tonic::Code::FailedPrecondition - ); -} - -#[tokio::test] -async fn pending_update_survives_driver_restart_and_blocks_start_by_id_or_name() { - let fixture = Fixture::new(); - let (docker, server) = docker_api(fixture.preflight()).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let intent = driver.prepare_image_update(fixture.p()).await.unwrap(); - server.await.unwrap(); - save(&fixture.config, &intent).unwrap(); - let snapshots = pending_snapshots(&fixture.config).unwrap(); - assert_eq!(snapshots.len(), 1); - assert_eq!(snapshots[0].id, fixture.p().sandbox_id); - assert_eq!( - snapshots[0].status.as_ref().unwrap().conditions[0].reason, - openshell_core::driver_utils::CONDITION_STOPPED - ); - assert_eq!( - pending_ids(&fixture.config).unwrap(), - vec![fixture.p().sandbox_id.clone()] - ); - let (docker, server) = docker_api(vec![]).await; - let mut reopened = test_driver_with_config(fixture.config.clone()); - reopened.docker = Arc::new(docker); - let observed = reopened - .get_sandbox_snapshot("", &fixture.p().name) - .await - .unwrap() - .unwrap(); - assert_eq!(observed.id, fixture.p().sandbox_id); - for id in [fixture.p().sandbox_id.as_str(), ""] { - let error = Box::pin(reopened.start_sandbox( - id, - &fixture.p().name, - "generation-2", - &test_launch_authentication(), - None, - )) - .await - .unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - } - server.await.unwrap(); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap() - .phase - == Phase::Prepared - ); -} - -#[tokio::test] -async fn completed_update_clears_pending_inventory_and_keeps_start_bound_to_target() { - let fixture = Fixture::new(); - fixture - .call(fixture.apply_replies(), &fixture.request) - .await - .0 - .unwrap(); - assert!(pending_ids(&fixture.config).unwrap().is_empty()); - assert!( - pending_snapshot(&fixture.config, &fixture.p().sandbox_id, &fixture.p().name) - .unwrap() - .is_none() - ); - require_settled(&fixture.config, &fixture.p().sandbox_id).unwrap(); - let mut target = fixture.target(); - validate_committed_resource( - &fixture.config, - &fixture.p().sandbox_id, - &target, - LaunchValidation::Complete, - ) - .unwrap(); - target.id = Some("same-name-foreign-container".into()); - assert!( - validate_committed_resource( - &fixture.config, - &fixture.p().sandbox_id, - &target, - LaunchValidation::Complete - ) - .is_err() - ); -} - -#[tokio::test] -async fn stopped_start_repairs_interrupted_launch_rotation_before_staging() { - let fixture = Fixture::new(); - fixture - .call(fixture.apply_replies(), &fixture.request) - .await - .0 - .unwrap(); - let descriptor_path = fixture.directory.join(RUNTIME_DESCRIPTOR_FILE); - let previous_descriptor = std::fs::read(&descriptor_path).unwrap(); - let mut interrupted = - decode_docker_launch_authentication(&test_launch_authentication()).unwrap(); - interrupted.supervisor.runtime_generation = - openshell_core::sandbox_generation::SandboxGenerationId::parse("generation-interrupted") - .unwrap(); - let interrupted_authentication = serde_json::to_vec(&interrupted).unwrap(); - refresh_docker_boundary_authentication( - &fixture.p().sandbox_id, - &fixture.config, - &interrupted_authentication, - ) - .await - .unwrap(); - // Model exit after bootstrap publication but before descriptor publication. - std::fs::write(&descriptor_path, previous_descriptor).unwrap(); - let intent = read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .unwrap(); - assert!(verify_published_boundary(&intent, &fixture.config).is_err()); - - let (docker, server) = docker_api(fixture.start_replies(false)).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let mut authentication = - decode_docker_launch_authentication(&test_launch_authentication()).unwrap(); - authentication.supervisor.runtime_generation = - openshell_core::sandbox_generation::SandboxGenerationId::parse("generation-retry").unwrap(); - let encoded = serde_json::to_vec(&authentication).unwrap(); - let error = Box::pin(driver.start_sandbox( - &fixture.p().sandbox_id, - &fixture.p().name, - "generation-retry", - &encoded, - None, - )) - .await - .unwrap_err(); - server.await.unwrap(); - // Deliberately omit the workspace-root staging input: reaching this gate - // proves the real Start path repaired publication, without starting a fake - // workload or requiring a supervisor process in this unit test. - assert!(error.message().contains("workspace for restart"), "{error}"); - verify_published_boundary(&intent, &fixture.config).unwrap(); - let repaired = read_docker_runtime_descriptor(&fixture.p().sandbox_id, &fixture.config) - .await - .unwrap() - .unwrap(); - assert_eq!(repaired.generation, "generation-retry"); - assert_eq!(repaired.session_id, authentication.supervisor.session_id); - assert_eq!( - repaired.resource_claims["docker.container_id"], - "container-B" - ); - assert_eq!( - repaired.resource_claims["docker.image_identity"], - "sha256:corrected" - ); -} - -#[tokio::test] -async fn interrupted_launch_pair_requires_stopped_workload_and_fresh_authentication() { - for (running, fresh_authentication, inspected_running) in [ - (true, true, true), - (false, false, false), - (false, true, true), - ] { - let fixture = Fixture::new(); - fixture - .call(fixture.apply_replies(), &fixture.request) - .await - .0 - .unwrap(); - let descriptor_path = fixture.directory.join(RUNTIME_DESCRIPTOR_FILE); - let previous_descriptor = std::fs::read(&descriptor_path).unwrap(); - refresh_docker_boundary_authentication( - &fixture.p().sandbox_id, - &fixture.config, - &test_launch_authentication(), - ) - .await - .unwrap(); - std::fs::write(&descriptor_path, &previous_descriptor).unwrap(); - let previous_bootstrap = - std::fs::read(fixture.directory.join(BOUNDARY_CONFIG_FILE)).unwrap(); - let mut replies = fixture.start_replies(running); - if inspected_running { - replies[1].3["State"]["Running"] = true.into(); - replies[1].3["State"]["Status"] = "running".into(); - } - let (docker, server) = docker_api(replies).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let authentication = if fresh_authentication { - test_launch_authentication() - } else { - Vec::new() - }; - let error = Box::pin(driver.start_sandbox( - &fixture.p().sandbox_id, - &fixture.p().name, - "generation-1", - &authentication, - None, - )) - .await - .unwrap_err(); - server.await.unwrap(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!( - error.message().contains(if !running && inspected_running { - "verifiably stopped" - } else { - "runtime evidence is inconsistent" - }), - "{error}" - ); - assert_eq!( - std::fs::read(&descriptor_path).unwrap(), - previous_descriptor - ); - assert_eq!( - std::fs::read(fixture.directory.join(BOUNDARY_CONFIG_FILE)).unwrap(), - previous_bootstrap - ); - } -} - -#[tokio::test] -async fn launch_repair_never_adopts_changed_immutable_bindings() { - let fixture = Fixture::new(); - fixture - .call(fixture.apply_replies(), &fixture.request) - .await - .0 - .unwrap(); - for filename in [BOUNDARY_CONFIG_FILE, RUNTIME_DESCRIPTOR_FILE] { - let path = fixture.directory.join(filename); - let original = std::fs::read(&path).unwrap(); - for (pointer, foreign) in [ - ("/boundary_id", serde_json::json!("foreign-sandbox")), - ( - "/resource_claims/docker.container_id", - serde_json::json!("foreign-container"), - ), - ( - "/resource_claims/docker.image_identity", - serde_json::json!("sha256:foreign"), - ), - ("/workload_identity/uid", serde_json::json!(2000)), - ("/workload_identity/gid", serde_json::json!(2000)), - ] { - let mut changed: serde_json::Value = serde_json::from_slice(&original).unwrap(); - *changed.pointer_mut(pointer).unwrap() = foreign; - let changed = serde_json::to_vec(&changed).unwrap(); - std::fs::write(&path, &changed).unwrap(); - let mut replies = fixture.start_replies(false); - if filename == RUNTIME_DESCRIPTOR_FILE - && matches!( - pointer, - "/boundary_id" | "/workload_identity/uid" | "/workload_identity/gid" - ) - { - replies.pop(); // The protected record rejects before volume access. - } - let (docker, server) = docker_api(replies).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let error = Box::pin(driver.start_sandbox( - &fixture.p().sandbox_id, - &fixture.p().name, - "generation-1", - &test_launch_authentication(), - None, - )) - .await - .unwrap_err(); - server.await.unwrap(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert_eq!(std::fs::read(&path).unwrap(), changed); - } - std::fs::write(path, original).unwrap(); - } - // Native container/image/workspace substitutions must also fail before - // credential publication, independently of the private file checks. - for (pointer, foreign) in [ - ("/Id", "foreign-container"), - ("/Image", "sha256:foreign"), - ("/HostConfig/Mounts/0/Source", "foreign-workspace"), - ] { - let mut target = serde_json::to_value(fixture.target()).unwrap(); - *target.pointer_mut(pointer).unwrap() = foreign.into(); - let target: ContainerInspectResponse = serde_json::from_value(target).unwrap(); - assert!( - validate_committed_resource( - &fixture.config, - &fixture.p().sandbox_id, - &target, - LaunchValidation::BeforeStoppedRotation - ) - .is_err() - ); - } -} - -async fn prepared_fixture() -> Fixture { - let fixture = Fixture::new(); - let (docker, server) = docker_api(fixture.preflight()).await; - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = Arc::new(docker); - let intent = driver.prepare_image_update(fixture.p()).await.unwrap(); - server.await.unwrap(); - save(&fixture.config, &intent).unwrap(); - fixture -} - -#[tokio::test] -async fn startup_cleanup_and_stop_preserve_pending_update_without_a_workload() { - let fixture = prepared_fixture().await; - let mut channel = fixture.volume.clone(); - channel.name = docker_channel_volume_name_by_id(&fixture.p().sandbox_id, &fixture.config); - channel.labels.remove(workspace::ROLE_LABEL); - // All three list operations are read-only. Any removal during startup or - // Stop would fail the fixture's next expected method. - let replies = vec![ - ("GET", String::new(), 200, serde_json::json!([])), - ("GET", String::new(), 200, serde_json::json!([])), - ( - "GET", - String::new(), - 200, - serde_json::json!({"Volumes":[fixture.volume, channel]}), - ), - ("GET", String::new(), 200, serde_json::json!([])), - ("GET", String::new(), 200, serde_json::json!([])), - ]; - let (docker, server) = docker_api(replies).await; - let mut reopened = test_driver_with_config(fixture.config.clone()); - reopened.docker = Arc::new(docker); - reopened - .reconcile_runtime_resources_at_startup() - .await - .unwrap(); - ComputeDriver::stop_sandbox( - &reopened, - Request::new(StopSandboxRequest { - sandbox_id: String::new(), - name: fixture.p().name.clone(), - }), - ) - .await - .unwrap(); - server.await.unwrap(); - assert_eq!( - pending_ids(&fixture.config).unwrap(), - vec![fixture.p().sandbox_id.clone()] - ); - assert!(fixture.directory.join(RUNTIME_DESCRIPTOR_FILE).is_file()); -} - -#[tokio::test] -async fn explicit_delete_clears_pending_gap_and_reports_the_deleted_native_resource() { - let fixture = prepared_fixture().await; - let mut replies = vec![ - ("GET", String::new(), 200, serde_json::json!([])), - ("GET", String::new(), 200, serde_json::json!([])), - fixture.volume_reply(), - ( - "DELETE", - format!("/volumes/{}", fixture.volume.name), - 204, - serde_json::Value::Null, - ), - ]; - for name in [ - docker_channel_volume_name_by_id(&fixture.p().sandbox_id, &fixture.config), - docker_supervisor_volume_name_by_id(&fixture.p().sandbox_id, &fixture.config), - docker_control_volume_name_by_id(&fixture.p().sandbox_id, &fixture.config), - ] { - replies.push(( - "DELETE", - format!("/volumes/{name}"), - 204, - serde_json::Value::Null, - )); - } - let (docker, server) = docker_api(replies).await; - let mut reopened = test_driver_with_config(fixture.config.clone()); - reopened.docker = Arc::new(docker); - let response = ComputeDriver::delete_sandbox( - &reopened, - Request::new(DeleteSandboxRequest { - sandbox_id: String::new(), - name: fixture.p().name.clone(), - }), - ) - .await - .unwrap() - .into_inner(); - server.await.unwrap(); - assert!(response.deleted); - assert!(pending_ids(&fixture.config).unwrap().is_empty()); - assert!(!fixture.directory.exists()); -} - -#[tokio::test] -async fn optional_rpc_remains_disabled_without_persistent_storage() { - let fixture = Fixture::new(); - let mut config = fixture.config.clone(); - config.workspace_storage = workspace::Storage::WritableLayer; - let capability = openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION; - let advertised = test_driver_with_config(config.clone()) - .capabilities() - .extension - .unwrap() - .supported_capabilities; - assert!(!advertised.iter().any(|value| value == capability)); - let error = fixture - .grpc_call(config, vec![], fixture.request.clone()) - .await - .unwrap_err(); - assert_eq!(error.code(), tonic::Code::Unimplemented); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .is_none() - ); -} - -#[tokio::test] -async fn optional_rpc_uses_the_existing_preflight_contract_when_enabled() { - let fixture = Fixture::new(); - let capability = openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION; - let advertised = test_driver_with_config(fixture.config.clone()) - .capabilities() - .extension - .unwrap() - .supported_capabilities; - assert!(advertised.iter().any(|value| value == capability)); - let mut request = fixture.request.clone(); - request.preconditions.as_mut().unwrap().validate_only = true; - let mut replies = fixture.preflight(); - replies.extend([fixture.source_reply(), fixture.volume_reply()]); - fixture - .grpc_call(fixture.config.clone(), replies, request) - .await - .unwrap(); - assert!( - read(&fixture.config, &fixture.p().sandbox_id) - .unwrap() - .is_none() - ); -} diff --git a/crates/openshell-driver-docker/src/image_update/tests/live.rs b/crates/openshell-driver-docker/src/image_update/tests/live.rs deleted file mode 100644 index 2d8bb92a08..0000000000 --- a/crates/openshell-driver-docker/src/image_update/tests/live.rs +++ /dev/null @@ -1,268 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Opt-in real-Docker driver integration; not gateway/supervisor protocol E2E. -//! See the crate README for image preparation and invocation. - -use super::*; -use std::process::Command; - -struct Resources { - container: String, - volume: String, - sandbox: String, -} - -impl Drop for Resources { - fn drop(&mut self) { - // No force, broad selectors, or removal of unverified resources, even - // when an assertion fails halfway through replacement. - for (kind, name, label_path) in [ - ("container", &self.container, ".Config.Labels"), - ("volume", &self.volume, ".Labels"), - ] { - let format = format!("{{{{index {label_path} \"{LABEL_SANDBOX_ID}\"}}}}"); - let owned = Command::new("docker") - .args([kind, "inspect", "--format", &format, name]) - .output() - .is_ok_and(|output| { - output.status.success() - && String::from_utf8_lossy(&output.stdout).trim() == self.sandbox - }); - if owned { - let removed = Command::new("docker").args([kind, "rm", name]).output(); - if !removed.is_ok_and(|output| output.status.success()) { - eprintln!("live Docker test could not remove its owned {kind} {name}"); - } - } - } - } -} - -fn archived_file(docker_id: &str, path: &str) -> Vec { - let output = Command::new("docker") - .args(["cp", &format!("{docker_id}:{path}"), "-"]) - .output() - .unwrap(); - assert!(output.status.success()); - let mut archive = tar::Archive::new(output.stdout.as_slice()); - let mut bytes = Vec::new(); - std::io::Read::read_to_end( - &mut archive.entries().unwrap().next().unwrap().unwrap(), - &mut bytes, - ) - .unwrap(); - bytes -} - -#[tokio::test] -#[ignore = "requires a live Docker daemon and the four prepared test images; see README"] -async fn live_stopped_image_replacement_retains_data_and_recovers_a_deleted_source() { - let images: Vec = ["A", "B", "BAD", "SYMBOLIC"] - .into_iter() - .map(|suffix| { - std::env::var(format!("OPENSHELL_DOCKER_UPDATE_IMAGE_{suffix}")) - .expect("prepare live test images first") - }) - .collect(); - let docker = Arc::new(Docker::connect_with_local_defaults().unwrap()); - docker.ping().await.unwrap(); - let mut fixture = Fixture::new(); - let resources = Resources { - container: fixture.name().into(), - volume: fixture.volume.name.clone(), - sandbox: fixture.p().sandbox_id.clone(), - }; - assert!( - matches!(docker.inspect_volume(&resources.volume).await, Err(ref error) if is_not_found_error(error)) - ); - let volume = docker - .create_volume(VolumeCreateRequest { - name: Some(resources.volume.clone()), - driver: Some("local".into()), - labels: Some(fixture.volume.labels.clone()), - ..Default::default() - }) - .await - .unwrap(); - let mut body: ContainerCreateBody = - serde_json::from_value(serde_json::to_value(&fixture.source.config).unwrap()).unwrap(); - body.host_config = fixture.source.host_config.clone(); - body.image = Some(images[0].clone()); - let private_record = workspace::record_bytes( - &resources.sandbox, - &fixture.config, - &volume, - &test_workload_identity(), - ) - .unwrap(); - durable_write( - &fixture.directory.join(workspace::RECORD_FILE), - &private_record, - ) - .unwrap(); - let source_id = docker - .create_container( - Some( - CreateContainerOptionsBuilder::default() - .name(&resources.container) - .build(), - ), - body, - ) - .await - .unwrap() - .id; - let source = docker.inspect_container(&source_id, None).await.unwrap(); - for filename in [BOUNDARY_CONFIG_FILE, RUNTIME_DESCRIPTOR_FILE] { - let path = fixture.directory.join(filename); - let mut value: serde_json::Value = - serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); - value["resource_claims"]["docker.container_id"] = source_id.clone().into(); - value["resource_claims"]["docker.image_identity"] = source.image.clone().unwrap().into(); - value["resource_claims"][workspace::RECORD_CLAIM] = - String::from_utf8(private_record.clone()).unwrap().into(); - value["workload_identity"]["resource_digest"] = source.image.clone().unwrap().into(); - value["provisioning_evidence"] = serde_json::to_value( - isolation::provisioning_evidence(&source_id, value["generation"].as_str().unwrap()) - .unwrap(), - ) - .unwrap(); - durable_write(&path, &serde_json::to_vec(&value).unwrap()).unwrap(); - } - let mut archive = tar::Builder::new(Vec::new()); - let marker = b"retained workspace and session proof\n"; - let mut header = tar::Header::new_gnu(); - header.set_size(marker.len() as u64); - header.set_mode(0o600); - header.set_uid(1234); - header.set_gid(1235); - header.set_cksum(); - archive - .append_data(&mut header, "retained-session.txt", marker.as_slice()) - .unwrap(); - docker - .upload_to_container( - &source_id, - Some( - UploadToContainerOptionsBuilder::default() - .path("/sandbox") - .copy_uidgid("true") - .build(), - ), - bollard::body_full(Bytes::from(archive.into_inner().unwrap())), - ) - .await - .unwrap(); - let mut driver = test_driver_with_config(fixture.config.clone()); - driver.docker = docker.clone(); - fixture - .request - .preconditions - .as_mut() - .unwrap() - .expected_image = images[0].clone(); - for rejected_image in &images[2..] { - fixture.request.preconditions.as_mut().unwrap().image = rejected_image.clone(); - let error = Box::pin(driver.update_workload_image(&fixture.request)) - .await - .unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!(error.message().contains("matching numeric"), "{error}"); - assert!(read(&fixture.config, &resources.sandbox).unwrap().is_none()); - assert_eq!( - docker - .inspect_container(&source_id, None) - .await - .unwrap() - .id - .as_deref(), - Some(source_id.as_str()) - ); - } - fixture.request.preconditions.as_mut().unwrap().image = images[1].clone(); - Box::pin(driver.update_workload_image(&fixture.request)) - .await - .unwrap(); - let intent = read(&fixture.config, &resources.sandbox).unwrap().unwrap(); - assert!(intent.phase == Phase::Applied); - let first_target = intent.target_container.clone().unwrap(); - assert_ne!(first_target, source_id); - let target = docker.inspect_container(&first_target, None).await.unwrap(); - assert_eq!(target.state.as_ref().unwrap().running, Some(false)); - assert_eq!( - target.config.as_ref().unwrap().user.as_deref(), - Some("1234:1235") - ); - assert_eq!( - target.config.as_ref().unwrap().labels.as_ref().unwrap()[LABEL_SANDBOX_ID], - resources.sandbox - ); - assert_eq!( - archived_file(&first_target, "/sandbox/retained-session.txt"), - marker - ); - assert_eq!(archived_file(&first_target, "/app/version"), b"B\n"); - // Reopen the driver and replay: no second replacement of the applied target. - let mut reopened = test_driver_with_config(fixture.config.clone()); - reopened.docker = docker.clone(); - Box::pin(reopened.update_workload_image(&fixture.request)) - .await - .unwrap(); - assert_eq!( - read(&fixture.config, &resources.sandbox) - .unwrap() - .unwrap() - .target_container - .as_deref(), - Some(first_target.as_str()) - ); - - // Inject exit after an accepted update has removed its stopped source. - let p = fixture.request.preconditions.as_mut().unwrap(); - p.expected_image = images[1].clone(); - p.image = images[0].clone(); - p.revision = 2; - p.operation_id = openshell_core::SandboxSessionId::new().to_string(); - let pending = reopened.prepare_image_update(fixture.p()).await.unwrap(); - save(&fixture.config, &pending).unwrap(); - docker.remove_container(&first_target, None).await.unwrap(); - assert!(require_settled(&fixture.config, &resources.sandbox).is_err()); - let mut recovered = test_driver_with_config(fixture.config.clone()); - recovered.docker = docker.clone(); - Box::pin(recovered.update_workload_image(&fixture.request)) - .await - .unwrap(); - let applied = read(&fixture.config, &resources.sandbox).unwrap().unwrap(); - let final_target = applied.target_container.as_ref().unwrap(); - assert!(applied.phase == Phase::Applied); - assert_eq!( - archived_file(final_target, "/sandbox/retained-session.txt"), - marker - ); - assert_eq!(archived_file(final_target, "/app/version"), b"A\n"); - assert_eq!( - docker - .inspect_volume(&resources.volume) - .await - .unwrap() - .created_at, - volume.created_at - ); - validate_committed_resource( - &fixture.config, - &resources.sandbox, - &docker.inspect_container(final_target, None).await.unwrap(), - LaunchValidation::Complete, - ) - .unwrap(); - // Explicitly remove only this stopped test workload and its admitted volume. - docker.remove_container(final_target, None).await.unwrap(); - docker - .remove_volume( - &resources.volume, - None::, - ) - .await - .unwrap(); -} diff --git a/crates/openshell-driver-docker/src/isolation.rs b/crates/openshell-driver-docker/src/isolation.rs deleted file mode 100644 index 9935ff0cbe..0000000000 --- a/crates/openshell-driver-docker/src/isolation.rs +++ /dev/null @@ -1,235 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Docker provisioning for the shared authenticated boundary protocol. -//! -//! Docker owns only container placement, the protected socket, and immutable OCI resource -//! claims. Lifecycle, process, network, identity, and wire behavior live in -//! `openshell-isolation-interface` and `openshell-sandbox`. - -use std::collections::{BTreeMap, HashMap}; -use std::net::IpAddr; -use std::path::PathBuf; - -use openshell_isolation_interface::contract::{ - BackendError, ProvisioningEvidence, ResolvedWorkloadIdentity, -}; -use openshell_sandbox_backend::GPU_RESOURCE_CLAIM; -use openshell_sandbox_backend::boundary_protocol::{ - BoundaryConfig, BoundaryListener, GatewayVerificationKey, SandboxRuntimeDescriptor, - SandboxTlsClientConfig, SandboxTlsServerConfig, SandboxTransport, -}; -use serde::Serialize; - -#[derive(Serialize)] -struct DockerOuterFenceEvidence<'a> { - container_id: &'a str, - network_mode: &'static str, - unexpected_networks: &'a [String], -} - -impl DockerOuterFenceEvidence<'_> { - fn project(&self, generation: &str) -> Result { - if self.container_id.is_empty() - || self.network_mode != "none" - || !self.unexpected_networks.is_empty() - { - return Err(BackendError::Descriptor( - "Docker provisioning evidence is incomplete".to_string(), - )); - } - let encoded = serde_json::to_vec(self).map_err(|error| { - BackendError::Descriptor(format!("encode Docker outer fence evidence: {error}")) - })?; - let projection = ProvisioningEvidence::from_enforcement_evidence(generation, &encoded)?; - projection.validate(generation)?; - Ok(projection) - } -} - -/// Bind the validated container fence to the generation being launched. -pub fn provisioning_evidence( - container_id: &str, - generation: &str, -) -> Result { - DockerOuterFenceEvidence { - container_id, - network_mode: "none", - unexpected_networks: &[], - } - .project(generation) -} - -/// Driver-owned inputs that bind one Docker container to one boundary. -pub struct DockerBoundarySpec { - pub boundary_id: String, - pub generation: String, - pub session_id: openshell_core::SandboxSessionId, - pub session_rotation: openshell_core::jwt::SessionRotation, - pub auth_epoch: openshell_core::jwt::CredentialEpoch, - pub gateway_id: String, - pub verification_keys: Vec, - pub container_id: String, - pub image_identity: String, - pub gpu_requested: bool, - pub listener_socket: PathBuf, - pub control_socket: PathBuf, - pub sandbox_tls: SandboxTlsServerConfig, - pub supervisor_tls: SandboxTlsClientConfig, - pub host_gateway_ip: Option, - pub workload_identity: ResolvedWorkloadIdentity, - pub child_env: HashMap, -} - -/// Protected container config and matching host descriptor. -pub struct DockerBoundaryProvisioning { - pub boundary_config: BoundaryConfig, - pub runtime_descriptor: SandboxRuntimeDescriptor, -} - -impl DockerBoundarySpec { - /// Produce both sides of the common protocol from the same immutable - /// Docker coordinates so attach cannot bind a different container. - pub fn provision(self) -> Result { - let mut resource_claims = BTreeMap::from([ - ("docker.container_id".to_string(), self.container_id), - ("docker.image_identity".to_string(), self.image_identity), - ]); - if self.gpu_requested { - resource_claims.insert(GPU_RESOURCE_CLAIM.to_string(), "true".to_string()); - } - let provisioning_evidence = - provisioning_evidence(&resource_claims["docker.container_id"], &self.generation)?; - Ok(DockerBoundaryProvisioning { - boundary_config: BoundaryConfig { - boundary_id: self.boundary_id.clone(), - generation: self.generation.clone(), - session_id: self.session_id, - session_rotation: self.session_rotation, - auth_epoch: self.auth_epoch, - gateway_id: self.gateway_id, - verification_keys: self.verification_keys, - listener: BoundaryListener::RuntimeInitiatedUnix { - socket_path: self.listener_socket, - tls: self.sandbox_tls, - }, - resource_claims: resource_claims.clone(), - resource_claim_files: BTreeMap::new(), - workload_identity: self.workload_identity.clone(), - provisioning_evidence: provisioning_evidence.clone(), - child_env: self.child_env, - }, - runtime_descriptor: SandboxRuntimeDescriptor { - boundary_id: self.boundary_id, - generation: self.generation, - session_id: self.session_id, - workload_identity: self.workload_identity, - transport: SandboxTransport::RuntimeInitiatedUnix { - socket_path: self.control_socket, - }, - tls: self.supervisor_tls, - host_gateway_ip: self.host_gateway_ip, - resource_claims, - provisioning_evidence, - }, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn outer_fence_projection_rejects_each_missing_native_fact() { - let unexpected_networks = vec!["bridge".to_string()]; - for evidence in [ - DockerOuterFenceEvidence { - container_id: "", - network_mode: "none", - unexpected_networks: &[], - }, - DockerOuterFenceEvidence { - container_id: "container", - network_mode: "bridge", - unexpected_networks: &[], - }, - DockerOuterFenceEvidence { - container_id: "container", - network_mode: "none", - unexpected_networks: &unexpected_networks, - }, - ] { - assert!(evidence.project("generation-1").is_err()); - } - } - - #[test] - fn provisioning_binds_container_and_image_claims() { - let session_id = openshell_core::SandboxSessionId::new(); - let tls = - openshell_sandbox_backend::boundary_protocol::generate_sandbox_tls_material(session_id) - .unwrap(); - let provisioned = DockerBoundarySpec { - boundary_id: "sandbox-1".to_string(), - generation: "generation-1".to_string(), - session_id, - session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), - auth_epoch: openshell_core::jwt::CredentialEpoch::new(1).unwrap(), - gateway_id: "gateway-1".to_string(), - verification_keys: vec![GatewayVerificationKey { - key_id: "key-1".to_string(), - public_key_pem: "public-key".to_string(), - }], - container_id: "sha256:container".to_string(), - image_identity: "sha256:image".to_string(), - gpu_requested: true, - listener_socket: PathBuf::from("/run/openshell/boundary/control.sock"), - control_socket: PathBuf::from("/host/control.sock"), - sandbox_tls: SandboxTlsServerConfig { - certificate_chain_path: PathBuf::from("/run/openshell/boundary/server.crt"), - private_key_path: PathBuf::from("/run/openshell/boundary/server.key"), - }, - supervisor_tls: SandboxTlsClientConfig { - server_name: tls.server_name, - trust_anchor_pem: tls.trust_anchor_pem, - }, - host_gateway_ip: Some(IpAddr::from([127, 0, 0, 1])), - workload_identity: ResolvedWorkloadIdentity::new( - 1000, - 1000, - Vec::new(), - "image".to_string(), - "sha256:image".to_string(), - ) - .unwrap(), - child_env: HashMap::new(), - } - .provision() - .unwrap(); - - assert_eq!( - provisioned.boundary_config.resource_claims, - provisioned.runtime_descriptor.resource_claims - ); - assert_eq!( - provisioned.runtime_descriptor.resource_claims["docker.container_id"], - "sha256:container" - ); - assert_eq!( - provisioned.runtime_descriptor.resource_claims[GPU_RESOURCE_CLAIM], - "true" - ); - assert_eq!( - provisioned.boundary_config.provisioning_evidence, - provisioned.runtime_descriptor.provisioning_evidence - ); - assert!( - provisioned - .runtime_descriptor - .provisioning_evidence - .validate("generation-1") - .is_ok() - ); - } -} diff --git a/crates/openshell-driver-docker/src/launch.rs b/crates/openshell-driver-docker/src/launch.rs deleted file mode 100644 index b7bdcf0a45..0000000000 --- a/crates/openshell-driver-docker/src/launch.rs +++ /dev/null @@ -1,120 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! What a gateway-launched Docker driver needs before it serves: the one place -//! the operator's table is parsed, and the backend check. - -use bollard::Docker; - -use crate::{DockerComputeConfig, detect_socket}; - -/// Settings the gateway supplies through `Configure`, or owns itself, so the -/// table cannot set them. The standalone driver still takes some as flags, so -/// the struct keeps the fields. -const GATEWAY_SUPPLIED_KEYS: &[&str] = &[ - "allow_driver_config", - "resource_admission", - "guest_tls_ca", - "guest_tls_cert", - "guest_tls_key", -]; - -/// Parse and validate the operator's `[openshell.drivers.docker]` table. -/// -/// This is the only place the table is parsed. It has no side effects: it -/// needs neither the gateway context nor Docker. An empty table selects the -/// defaults. -pub fn settings_from_table(table: &str) -> Result { - let keys: toml::Table = - toml::from_str(table).map_err(|error| format!("invalid docker driver table: {error}"))?; - if let Some(key) = GATEWAY_SUPPLIED_KEYS - .iter() - .find(|key| keys.contains_key(**key)) - { - return Err(format!( - "invalid docker driver table: `{key}` is supplied by the gateway and cannot be set here" - )); - } - let config: DockerComputeConfig = - toml::from_str(table).map_err(|error| format!("invalid docker driver table: {error}"))?; - if !config.grpc_endpoint.trim().is_empty() { - openshell_driver_sdk::validate_grpc_endpoint(&config.grpc_endpoint)?; - } - config.validate_table().map_err(|error| error.to_string())?; - Ok(config) -} - -/// Check that Docker is reachable with `config`: resolve the socket (the -/// configured one, else the first responsive one) and ping it. Creates -/// nothing. -pub async fn check_backend(config: &DockerComputeConfig) -> Result<(), String> { - let socket = config - .socket_path - .clone() - .or_else(detect_socket) - .ok_or_else(|| { - "no responsive Docker API socket found; set DOCKER_HOST or configure socket_path" - .to_string() - })?; - let socket = socket.to_str().ok_or_else(|| { - format!( - "Docker socket path is not valid UTF-8: {}", - socket.display() - ) - })?; - let docker = Docker::connect_with_socket(socket, 30, bollard::API_DEFAULT_VERSION) - .map_err(|error| format!("failed to create Docker client: {error}"))?; - docker - .ping() - .await - .map(|_| ()) - .map_err(|error| format!("Docker is not reachable at {socket}: {error}")) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn an_empty_table_selects_the_defaults() { - let config = settings_from_table("").unwrap(); - assert!(!config.allow_driver_config); - assert_eq!(config.sandbox_label, "default"); - } - - #[test] - fn existing_operator_keys_are_accepted() { - let config = settings_from_table( - "sandbox_label = \"mine\"\nimage_pull_policy = \"always\"\npersist_workspace = true\nsocket_path = \"/var/run/docker.sock\"\ngrpc_endpoint = \"http://127.0.0.1:8080\"", - ) - .unwrap(); - assert_eq!(config.sandbox_label, "mine"); - assert!(config.persist_workspace); - } - - #[test] - fn gateway_supplied_keys_are_rejected() { - for key in [ - "allow_driver_config = true", - "resource_admission = {}", - "guest_tls_ca = \"/ca.pem\"", - "guest_tls_cert = \"/cert.pem\"", - ] { - let error = settings_from_table(key).unwrap_err(); - assert!(error.contains("supplied by the gateway"), "{key}: {error}"); - } - } - - #[test] - fn unknown_keys_and_bad_endpoints_are_rejected() { - assert!(settings_from_table("no_such_key = 1").is_err()); - assert!(settings_from_table("grpc_endpoint = \"ftp://gw:1\"").is_err()); - } - - #[tokio::test] - async fn an_unreachable_socket_is_reported_not_created() { - let config = settings_from_table("socket_path = \"/nonexistent/docker.sock\"").unwrap(); - let error = check_backend(&config).await.unwrap_err(); - assert!(error.contains("/nonexistent/docker.sock"), "{error}"); - } -} diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs deleted file mode 100644 index 75e894bd5e..0000000000 --- a/crates/openshell-driver-docker/src/lib.rs +++ /dev/null @@ -1,7576 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Docker compute driver. - -#![allow(clippy::result_large_err)] - -mod image_update; -mod isolation; -pub mod launch; -pub mod otel_tracing; -mod workspace; - -use bollard::Docker; -use bollard::errors::Error as BollardError; -use bollard::models::{ - ContainerCreateBody, ContainerState, ContainerStateStatusEnum, ContainerSummary, - ContainerSummaryStateEnum, ContainerWaitResponse, CreateImageInfo, DeviceRequest, HealthConfig, - HealthStatusEnum, HostConfig, Mount, MountTmpfsOptions, MountTypeEnum, MountVolumeOptions, - ProgressDetail, SystemInfo, SystemVersion, VolumeCreateRequest, -}; -use bollard::query_parameters::{ - CreateContainerOptionsBuilder, CreateImageOptions, DownloadFromContainerOptionsBuilder, - ListContainersOptionsBuilder, ListVolumesOptionsBuilder, LogsOptionsBuilder, - RemoveContainerOptionsBuilder, StopContainerOptionsBuilder, UploadToContainerOptionsBuilder, -}; -use bytes::Bytes; -use futures::{Stream, StreamExt}; -use openshell_core::config::DEFAULT_STOP_TIMEOUT_SECS; -use openshell_core::driver_mounts; -use openshell_core::driver_utils::{ - CONDITION_EXITED, CONDITION_RUNTIME_RESTART, CONDITION_WORKSPACE_VALIDATION_FAILED, - LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, - LABEL_SANDBOX_NAMESPACE, LABEL_SANDBOX_WORKSPACE, SANDBOX_RUNTIME_IMAGE_BINARY_PATH, - SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED, WORKSPACE_VALIDATION_FAILED_MESSAGE, - extract_first_tar_entry, supervisor_image_should_refresh, temp_extract_container_name, - validate_linux_elf_binary, -}; -use openshell_core::gpu::{ - CdiGpuDefaultSelector, CdiGpuInventory, CdiGpuSelectionError, driver_gpu_requirements, - effective_driver_gpu_count, validate_cdi_device_names, validate_cdi_gpu_device_request, -}; -use openshell_core::progress::{ - PROGRESS_STEP_PULLING_IMAGE, PROGRESS_STEP_REQUESTING_SANDBOX, PROGRESS_STEP_STARTING_SANDBOX, - format_bytes, mark_progress_active, mark_progress_complete, mark_progress_detail, -}; -use openshell_core::proto::compute::v1::{ - CpuResourceCapabilities, CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, - DeleteSandboxResponse, DeleteWorkspaceRequest, DeleteWorkspaceResponse, DriverCondition, - DriverPlatformEvent, DriverSandbox, DriverSandboxStatus, DriverSandboxTemplate, - EnsureWorkspaceRequest, EnsureWorkspaceResponse, GetCapabilitiesRequest, - GetCapabilitiesResponse, GetSandboxRequest, GetSandboxResponse, GpuResourceCapabilities, - GpuResourceRequirements, ListSandboxesRequest, ListSandboxesResponse, - MemoryResourceCapabilities, ResourceCapabilities, StartSandboxRequest, StartSandboxResponse, - StopSandboxRequest, StopSandboxResponse, SuspendSandboxRequest, SuspendSandboxResponse, - ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesDeletedEvent, - WatchSandboxesEvent, WatchSandboxesPlatformEvent, WatchSandboxesRequest, - WatchSandboxesSandboxEvent, compute_driver_server::ComputeDriver, watch_sandboxes_event, -}; -use openshell_core::proto_struct::{deserialize_optional_non_empty_string_list, from_struct}; -use openshell_core::{ - AppArmorProfile, Error, ImagePullPolicy, NetworkSupervisorTrustBundle, Result as CoreResult, - SupervisorIpv6EgressConfig, UpstreamProxyConfig, -}; -use openshell_isolation_interface::contract::ResolvedWorkloadIdentity; -use openshell_sandbox_backend::boundary_protocol::{ - BoundaryConfig, GatewayVerificationKey, SandboxRuntimeDescriptor, SandboxTlsClientConfig, - SandboxTlsServerConfig, generate_sandbox_tls_material, -}; -use opentelemetry::trace::TraceContextExt as _; -use sha2::{Digest as _, Sha256}; -use std::borrow::Cow; -use std::collections::{HashMap, HashSet}; -use std::fmt::Write as _; -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -#[cfg(unix)] -use std::path::{Path, PathBuf}; -use std::pin::Pin; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::time::Duration; -use tokio::io::AsyncWriteExt as _; -use tokio::sync::{Mutex, broadcast, mpsc, oneshot}; -use tokio::task::JoinHandle; -use tokio_stream::wrappers::ReceiverStream; -use tonic::{Request, Response, Status}; -use tracing::{Instrument as _, debug, info, warn}; -use tracing_opentelemetry::OpenTelemetrySpanExt as _; -use url::Url; - -const WATCH_BUFFER: usize = 128; -const WATCH_POLL_INTERVAL: Duration = Duration::from_secs(2); -const WATCH_POLL_MAX_BACKOFF: Duration = Duration::from_secs(30); -// The gateway closes a supervisor session as soon as it commits a sandbox to -// Stopping, just before the compute-driver StopSandbox RPC arrives. Give that -// request a bounded opportunity to mark the control exit intentional before -// publishing a fail-closed runtime error. -const SUPERVISOR_INTENTIONAL_SHUTDOWN_GRACE: Duration = Duration::from_secs(1); -// Longer than the supervisor's own bound on stopping its workload, so it -// finishes stopping before Docker kills it. -const SUPERVISOR_STOP_TIMEOUT_SECS: i32 = 10; -const SUPERVISOR_HEALTH_INTERVAL_NS: i64 = 30_000_000_000; -// Docker probes at this interval only before the first healthy result and -// within the start period. -const SUPERVISOR_HEALTH_START_INTERVAL_NS: i64 = 250_000_000; -const SUPERVISOR_HEALTH_TIMEOUT_NS: i64 = 2_000_000_000; -const SUPERVISOR_HEALTH_START_PERIOD_NS: i64 = 60_000_000_000; -const HOST_GATEWAY_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(30); -const HOST_GATEWAY_CLEANUP_TIMEOUT: Duration = Duration::from_secs(10); - -const SANDBOX_BINARY_PATH: &str = "/.openshell/runtime/openshell-sandbox"; -const SUPERVISOR_IMAGE_CONTROL_BINARY_PATH: &str = "/openshell-supervisor"; -const SUPERVISOR_HEALTH_SOCKET_PATH: &str = "/run/openshell/health.sock"; -const SUPERVISOR_UID: u32 = 65_534; -const SUPERVISOR_GID: u32 = 65_534; -const BOUNDARY_MOUNT_PATH: &str = "/.openshell/channel"; -const BOUNDARY_CONFIG_MOUNT_PATH: &str = "/.openshell/channel/sandbox/bootstrap.json"; -const BOUNDARY_CONTROL_MOUNT_PATH: &str = "/.openshell/channel/control"; -const BOUNDARY_SOCKET_MOUNT_PATH: &str = "/.openshell/channel/control/supervisor/control.sock"; -const BOUNDARY_CERTIFICATE_MOUNT_PATH: &str = "/.openshell/channel/sandbox/server.crt"; -const BOUNDARY_PRIVATE_KEY_MOUNT_PATH: &str = "/.openshell/channel/sandbox/server.key"; -const SUPERVISOR_STATE_MOUNT_PATH: &str = "/.openshell/supervisor"; -const SUPERVISOR_PROXY_AUTH_MOUNT_PATH: &str = "/.openshell/supervisor/upstream-proxy-auth"; -const SUPERVISOR_PROXY_CA_BUNDLE_MOUNT_PATH: &str = - "/.openshell/supervisor/upstream-proxy-ca-bundle.pem"; -const PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR: &str = - openshell_core::driver_utils::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR; -const DRIVER_ADMITTED_BACKEND: &str = openshell_sandbox_backend::BACKEND_NAME; -const LABEL_ISOLATION_BACKEND: &str = "openshell.ai/isolation-backend"; -const LABEL_ISOLATION_BACKEND_OPEN_SHELL: &str = openshell_sandbox_backend::BACKEND_NAME; -const LABEL_ISOLATION_ROLE: &str = "openshell.ai/isolation-role"; -const LABEL_ISOLATION_ROLE_SANDBOX: &str = "sandbox"; -const LABEL_ISOLATION_ROLE_SUPERVISOR: &str = "supervisor"; -const LABEL_ISOLATION_ROLE_STAGING: &str = "staging"; -const LABEL_ISOLATION_ROLE_IDENTITY: &str = "identity"; -const RUNTIME_DESCRIPTOR_FILE: &str = "runtime-descriptor.json"; -const MAIN_PROCESS_SPEC_FILE: &str = "main-process.json"; -const WORKSPACE_ROOT_FILE: &str = "workspace-root"; -const BOUNDARY_CONFIG_FILE: &str = "boundary-bootstrap.json"; -const BOUNDARY_CERTIFICATE_FILE: &str = "boundary-server.crt"; -const BOUNDARY_PRIVATE_KEY_FILE: &str = "boundary-server.key"; -const SUPERVISOR_AUTH_BUNDLE_FILE: &str = "supervisor-auth.json"; -const START_GENERATION_FILE: &str = "start-generation"; -const HOST_OPEN_SHELL_INTERNAL: &str = "host.openshell.internal"; -const HOST_DOCKER_INTERNAL: &str = "host.docker.internal"; -/// Fixed in-container path for the gateway-owned additional destination trust. -/// It is mounted only into the separate trusted supervisor container. -const ADDITIONAL_CA_MOUNT_PATH: &str = openshell_core::driver_utils::ADDITIONAL_CA_MOUNT_PATH; - -fn provisioning_span( - parent: &opentelemetry::Context, - sandbox: &DriverSandbox, - image_ref: &str, -) -> tracing::Span { - let span = tracing::info_span!( - parent: None, - "docker.provision", - otel.name = "docker.provision", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox.id, - sandbox.name = %sandbox.name, - image.ref = %image_ref, - ); - let parent_span_context = parent.span().span_context().clone(); - if parent_span_context.is_valid() { - let parent = opentelemetry::Context::new().with_remote_span_context(parent_span_context); - let _ = span.set_parent(parent); - } - span -} - -/// Operator-owned networking mode for the trusted supervisor companion. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum DockerSupervisorNetworkMode { - /// Use the default host networking mode. - Auto, - #[default] - Host, - Bridge, -} - -/// Gateway-local configuration for the Docker compute driver. -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(default, deny_unknown_fields)] -pub struct DockerComputeConfig { - /// Permit caller-supplied driver JSON. Does not waive resource admission. - pub allow_driver_config: bool, - /// Operator-owned external attachment approval policy. - pub resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig, - /// Docker API Unix socket. When unset, use the socket selected by gateway - /// auto-detection, falling back to `/var/run/docker.sock` for an explicitly - /// configured Docker driver. - pub socket_path: Option, - - /// Default OCI image for sandboxes. - pub default_image: String, - - /// Image pull policy for sandbox images. - pub image_pull_policy: ImagePullPolicy, - - /// Value of the `openshell.sandbox_namespace` label applied to Docker sandboxes. - pub sandbox_label: String, - - /// Gateway gRPC endpoint the sandbox connects back to. - pub grpc_endpoint: String, - - /// Networking mode for the supervisor only. Workloads always use network=none. - pub supervisor_network_mode: DockerSupervisorNetworkMode, - - /// Override the trusted host address. Bridge mode otherwise resolves Docker's host-gateway. - pub host_gateway_ip: Option, - - /// OTLP exports passed to supervisors. The gateway supplies them from - /// `[otlp]`; driver TOML cannot set them. - #[serde(skip)] - pub supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, - - /// Gateway name passed to supervisors for their telemetry. The gateway - /// supplies its own name; driver TOML cannot set it. - #[serde(skip)] - pub supervisor_gateway_name: Option, - - /// Image containing the trusted `openshell-sandbox` binary. - pub sandbox_runtime_image: Option, - - /// Optional host path to the trusted `openshell-sandbox` binary. - /// - /// This preserves the original `supervisor_bin` configuration name while - /// the split runtime transitions to the explicit sandbox image setting. - pub supervisor_bin: Option, - - /// Image containing the trusted `openshell-supervisor` binary. - pub supervisor_image: Option, - - /// Host-side CA certificate for sandbox-to-gateway TLS. - pub guest_tls_ca: Option, - - /// Deprecated. Sandboxes authenticate with bearer tokens and must not - /// receive a user client certificate. - pub guest_tls_cert: Option, - - /// Deprecated. Sandboxes authenticate with bearer tokens and must not - /// receive a user client private key. - pub guest_tls_key: Option, - - /// Unix socket path used for interactive sandbox access. - pub ssh_socket_path: String, - - /// Container cgroup PID limit for Docker-managed sandboxes. - /// - /// Omit the field to use `OpenShell`'s default sandbox process limit. - /// Explicit zero is invalid. - #[serde( - default = "openshell_core::config::default_sandbox_pids_limit", - skip_serializing_if = "Option::is_none" - )] - pub sandbox_pids_limit: Option, - - /// Allow sandbox requests to attach host bind mounts through - /// `template.driver_config`. - #[serde(default)] - pub enable_bind_mounts: bool, - - /// Give newly created default /sandbox workspaces dedicated persistent storage. - /// Existing writable-layer workspaces are not migrated by this setting. - pub persist_workspace: bool, - - /// Corporate forward-proxy settings supplied to the supervisor. - #[serde(flatten)] - pub upstream_proxy: UpstreamProxyConfig, - - /// Gateway-host PEM CA bundle trusted for the corporate proxy and for - /// server certificates re-signed by a TLS-intercepting proxy. - pub proxy_ca_bundle: Option, - /// Policy DNS IPv6 egress mode and NAT64 prefixes supplied to the - /// supervisor. - #[serde(flatten)] - pub ipv6_egress: SupervisorIpv6EgressConfig, - - /// Host UNIX socket projected into the supervisor for provider identity. - pub provider_spiffe_workload_api_socket: Option, - - /// `AppArmor` confinement requested for the workload container. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub app_armor_profile: Option, -} - -impl DockerComputeConfig { - /// Validate startup configuration without connecting to Docker. - pub fn validate_configuration(&self, gateway_bind_address: SocketAddr) -> CoreResult<()> { - self.validate_table()?; - if gateway_bind_address.port() == 0 { - return Err(Error::config( - "docker compute driver requires a fixed non-zero gateway bind port", - )); - } - Ok(()) - } - - /// The checks that need neither the gateway nor Docker: everything about - /// the operator's table. - pub fn validate_table(&self) -> CoreResult<()> { - self.resource_admission.validate().map_err(Error::config)?; - if let Some(socket_path) = self.socket_path.as_deref() - && socket_path.to_str().is_none() - { - return Err(Error::config(format!( - "Docker socket path is not valid UTF-8: {}", - socket_path.display() - ))); - } - validate_sandbox_pids_limit(self.sandbox_pids_limit)?; - validate_image_pull_policy(self.image_pull_policy)?; - self.upstream_proxy.validate().map_err(Error::config)?; - validate_docker_proxy_auth_file(&self.upstream_proxy)?; - validate_docker_proxy_ca_bundle(self)?; - self.ipv6_egress.validate().map_err(Error::config)?; - if let Some(socket) = self.provider_spiffe_workload_api_socket.as_deref() { - openshell_core::driver_utils::validate_provider_spiffe_unix_socket(socket) - .map_err(Error::config)?; - } - Ok(()) - } -} - -impl Default for DockerComputeConfig { - fn default() -> Self { - Self { - socket_path: None, - allow_driver_config: false, - resource_admission: - openshell_core::resource_admission::ResourceAdmissionConfig::default(), - default_image: openshell_core::image::default_sandbox_image(), - image_pull_policy: ImagePullPolicy::default(), - sandbox_label: "default".to_string(), - grpc_endpoint: String::new(), - supervisor_network_mode: DockerSupervisorNetworkMode::Host, - host_gateway_ip: None, - supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp::default(), - supervisor_gateway_name: None, - sandbox_runtime_image: None, - supervisor_bin: None, - supervisor_image: None, - guest_tls_ca: None, - guest_tls_cert: None, - guest_tls_key: None, - ssh_socket_path: openshell_core::container_paths::SSH_SOCKET_PATH.to_string(), - sandbox_pids_limit: openshell_core::config::default_sandbox_pids_limit(), - enable_bind_mounts: false, - persist_workspace: false, - upstream_proxy: UpstreamProxyConfig::default(), - proxy_ca_bundle: None, - ipv6_egress: SupervisorIpv6EgressConfig::default(), - provider_spiffe_workload_api_socket: None, - app_armor_profile: None, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub(crate) struct DockerGuestTlsPaths { - pub(crate) ca: PathBuf, -} - -#[derive(Debug, Clone)] -struct DockerDriverRuntimeConfig { - allow_driver_config: bool, - resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig, - default_image: String, - image_pull_policy: ImagePullPolicy, - sandbox_namespace: String, - stop_timeout_secs: u32, - log_level: String, - sandbox_binary: Arc>, - supervisor_image_id: String, - supervisor_grpc_endpoint: String, - supervisor_network_mode: DockerSupervisorNetworkMode, - supervisor_endpoint_explicit: bool, - bridge_default_endpoint: Option, - host_gateway_ip: Option, - supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, - supervisor_gateway_name: Option, - ssh_socket_path: String, - guest_tls: Option, - gpu: DockerGpuRuntimeCapabilities, - sandbox_pids_limit: Option, - enable_bind_mounts: bool, - workspace_storage: workspace::Storage, - upstream_proxy: UpstreamProxyConfig, - proxy_ca_bundle: Option, - ipv6_egress: SupervisorIpv6EgressConfig, - provider_spiffe_workload_api_socket: Option, - app_armor_profile: Option, - /// Immutable gateway-normalized additional destination trust. This is - /// deliberately separate from `DockerComputeConfig` and sandbox input. - network_trust: Option, -} - -#[derive(Debug, Clone, Copy)] -struct DockerGpuRuntimeCapabilities { - cdi_supported: bool, - wsl_all_gpu_fallback_enabled: bool, -} - -#[derive(Clone)] -pub struct DockerComputeDriver { - docker: Arc, - config: DockerDriverRuntimeConfig, - events: broadcast::Sender, - pending: Arc>>, - gpu_selector: Arc, - lifecycle_event_fences: DockerLifecycleEventFences, - control_processes: Arc>>, - runtime_failures: Arc>>, - image_update_gates: Arc, -} - -struct DockerControlProcess { - shutdown: Option>, - intentional_shutdown: Arc, - task: JoinHandle<()>, -} - -#[derive(Clone)] -struct DockerRuntimeFailure { - reason: &'static str, - message: String, -} - -#[derive(Clone)] -struct DockerRuntimeFailureContext { - docker: Arc, - events: broadcast::Sender, - failures: Arc>>, - sandbox: DriverSandbox, - sandbox_namespace: String, - container_id: String, - stop_timeout_secs: u32, -} - -/// Per-sandbox container exit timestamps that fence snapshots from an earlier run. -/// -/// Docker's polling loop can observe the stopped container before a restart and -/// publish that snapshot after the gateway has moved the sandbox to `Starting`. -/// Comparing the container's transition timestamp prevents that old observation -/// from regressing the new lifecycle operation to `Error`. -#[derive(Clone, Debug, Default)] -struct DockerLifecycleEventFences { - state: Arc>, -} - -#[derive(Debug, Default)] -struct DockerLifecycleFenceState { - previous_finished_at: HashMap, - starts_in_progress: HashSet, - stops_requested: HashSet, -} - -impl DockerLifecycleEventFences { - fn begin_start(&self, sandbox_id: &str) { - self.state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .starts_in_progress - .insert(sandbox_id.to_string()); - } - - fn finish_start(&self, sandbox_id: &str) { - self.state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .starts_in_progress - .remove(sandbox_id); - } - - fn start_in_progress(&self, sandbox_id: &str) -> bool { - self.state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .starts_in_progress - .contains(sandbox_id) - } - - fn request_stop(&self, sandbox_id: &str, sandbox_name: &str) { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if !sandbox_id.is_empty() { - state.stops_requested.insert(format!("id:{sandbox_id}")); - } - if !sandbox_name.is_empty() { - state.stops_requested.insert(format!("name:{sandbox_name}")); - } - } - - fn clear_stop(&self, sandbox_id: &str, sandbox_name: &str) { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if !sandbox_id.is_empty() { - state.stops_requested.remove(&format!("id:{sandbox_id}")); - } - if !sandbox_name.is_empty() { - state - .stops_requested - .remove(&format!("name:{sandbox_name}")); - } - } - - fn stop_requested(&self, sandbox_id: &str, sandbox_name: &str) -> bool { - let state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - (!sandbox_id.is_empty() && state.stops_requested.contains(&format!("id:{sandbox_id}"))) - || (!sandbox_name.is_empty() - && state - .stops_requested - .contains(&format!("name:{sandbox_name}"))) - } - - fn record_previous_exit(&self, sandbox_id: &str, finished_at: Option<&str>) { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - match finished_at.filter(|finished_at| !finished_at.is_empty()) { - Some(finished_at) => { - state - .previous_finished_at - .insert(sandbox_id.to_string(), finished_at.to_string()); - } - None => { - state.previous_finished_at.remove(sandbox_id); - } - } - } - - fn previous_exit(&self, sandbox_id: &str) -> Option { - self.state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .previous_finished_at - .get(sandbox_id) - .cloned() - } - - fn remove(&self, sandbox_id: &str, sandbox_name: &str) { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - state.previous_finished_at.remove(sandbox_id); - state.starts_in_progress.remove(sandbox_id); - state.stops_requested.remove(&format!("id:{sandbox_id}")); - state - .stops_requested - .remove(&format!("name:{sandbox_name}")); - } -} - -struct PendingSandboxRecord { - sandbox: DriverSandbox, - task: Option>, -} - -#[derive(Debug, Clone)] -struct DockerProvisioningFailure { - reason: &'static str, - message: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct DockerImageMetadata { - id: String, - user: String, - working_dir: String, - volumes: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct DockerPasswdEntry { - name: String, - uid: u32, - gid: u32, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct DockerGroupEntry { - name: String, - gid: u32, - members: Vec, -} - -fn parse_docker_passwd(bytes: &[u8]) -> Result, Status> { - let contents = std::str::from_utf8(bytes).map_err(|error| { - Status::failed_precondition(format!("image /etc/passwd is not UTF-8: {error}")) - })?; - let mut entries = Vec::new(); - for (index, line) in contents.lines().enumerate() { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - let fields = line.split(':').collect::>(); - if fields.len() < 4 || fields[0].is_empty() { - return Err(Status::failed_precondition(format!( - "image /etc/passwd line {} is malformed", - index + 1 - ))); - } - let uid = fields[2].parse::().map_err(|_| { - Status::failed_precondition(format!( - "image /etc/passwd line {} has an invalid UID", - index + 1 - )) - })?; - let gid = fields[3].parse::().map_err(|_| { - Status::failed_precondition(format!( - "image /etc/passwd line {} has an invalid GID", - index + 1 - )) - })?; - entries.push(DockerPasswdEntry { - name: fields[0].to_string(), - uid, - gid, - }); - } - Ok(entries) -} - -fn parse_docker_group(bytes: &[u8]) -> Result, Status> { - let contents = std::str::from_utf8(bytes).map_err(|error| { - Status::failed_precondition(format!("image /etc/group is not UTF-8: {error}")) - })?; - let mut entries = Vec::new(); - for (index, line) in contents.lines().enumerate() { - let line = line.trim(); - if line.is_empty() || line.starts_with('#') { - continue; - } - let fields = line.split(':').collect::>(); - if fields.len() < 4 || fields[0].is_empty() { - return Err(Status::failed_precondition(format!( - "image /etc/group line {} is malformed", - index + 1 - ))); - } - let gid = fields[2].parse::().map_err(|_| { - Status::failed_precondition(format!( - "image /etc/group line {} has an invalid GID", - index + 1 - )) - })?; - entries.push(DockerGroupEntry { - name: fields[0].to_string(), - gid, - members: fields[3] - .split(',') - .filter(|member| !member.is_empty()) - .map(str::to_string) - .collect(), - }); - } - Ok(entries) -} - -fn resolve_numeric_or_named_user<'a>( - selector: &str, - passwd: &'a [DockerPasswdEntry], -) -> Result<(u32, Option<&'a DockerPasswdEntry>), Status> { - if let Ok(uid) = selector.parse::() { - return Ok((uid, passwd.iter().find(|entry| entry.uid == uid))); - } - let entry = passwd - .iter() - .find(|entry| entry.name == selector) - .ok_or_else(|| { - Status::failed_precondition(format!( - "workload user '{selector}' does not exist in the pinned image" - )) - })?; - Ok((entry.uid, Some(entry))) -} - -fn resolve_numeric_or_named_group( - selector: &str, - groups: &[DockerGroupEntry], -) -> Result { - if let Ok(gid) = selector.parse::() { - return Ok(gid); - } - groups - .iter() - .find(|entry| entry.name == selector) - .map(|entry| entry.gid) - .ok_or_else(|| { - Status::failed_precondition(format!( - "workload group '{selector}' does not exist in the pinned image" - )) - }) -} - -fn resolve_docker_identity_from_accounts( - sandbox: &DriverSandbox, - image: &DockerImageMetadata, - passwd_bytes: &[u8], - group_bytes: &[u8], -) -> Result { - let passwd = parse_docker_passwd(passwd_bytes)?; - let groups = parse_docker_group(group_bytes)?; - let request = sandbox - .spec - .as_ref() - .and_then(|spec| spec.workload_identity.as_ref()); - let requested_user = request.map_or("", |request| request.user.trim()); - let requested_group = request.map_or("", |request| request.group.trim()); - let (image_user, image_group) = image.user.split_once(':').unwrap_or((&image.user, "")); - let user_selector = if requested_user.is_empty() { - image_user.trim() - } else { - requested_user - }; - if user_selector.is_empty() { - // The image declares no USER (for example, a minimal base image) and the policy - // requested none. Synthesize a numeric non-root identity instead of - // rejecting, matching the Podman driver's USER-less default and the - // numeric-identity behavior of the Kubernetes and VM drivers. - return ResolvedWorkloadIdentity::new( - openshell_core::sandbox_env::DEFAULT_SANDBOX_UID, - openshell_core::sandbox_env::DEFAULT_SANDBOX_GID, - Vec::new(), - "default".to_string(), - image.id.clone(), - ) - .map_err(|error| Status::failed_precondition(error.to_string())); - } - let (uid, passwd_entry) = resolve_numeric_or_named_user(user_selector, &passwd)?; - let username = passwd_entry.map(|entry| entry.name.as_str()); - let group_selector = if requested_group.is_empty() { - image_group.trim() - } else { - requested_group - }; - let gid = if group_selector.is_empty() { - passwd_entry.map(|entry| entry.gid).ok_or_else(|| { - Status::failed_precondition(format!( - "numeric workload UID {uid} has no passwd entry; configure process.run_as_group" - )) - })? - } else { - resolve_numeric_or_named_group(group_selector, &groups)? - }; - let supplementary_gids = username.map_or_else(Vec::new, |username| { - groups - .iter() - .filter(|entry| { - entry.gid != gid && entry.members.iter().any(|member| member == username) - }) - .map(|entry| entry.gid) - .collect() - }); - let source = if !requested_user.is_empty() || !requested_group.is_empty() { - "policy" - } else { - "image" - }; - ResolvedWorkloadIdentity::new( - uid, - gid, - supplementary_gids, - source.to_string(), - image.id.clone(), - ) - .map_err(|error| Status::failed_precondition(error.to_string())) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -struct DockerResourceLimits { - nano_cpus: Option, - memory_bytes: Option, -} - -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(default, deny_unknown_fields)] -struct DockerSandboxDriverConfig { - #[serde( - default, - deserialize_with = "deserialize_optional_non_empty_string_list" - )] - cdi_devices: Option>, - mounts: Vec, -} - -struct ValidatedDockerSandbox<'a> { - template: &'a DriverSandboxTemplate, - driver_config: DockerSandboxDriverConfig, - gpu_requirements: Option<&'a GpuResourceRequirements>, -} - -impl DockerSandboxDriverConfig { - fn from_template(template: &DriverSandboxTemplate) -> Result { - let Some(config) = template.driver_config.as_ref() else { - return Ok(Self::default()); - }; - - from_struct(config).map_err(|err| format!("invalid docker driver_config: {err}")) - } -} - -use openshell_core::driver_mounts::SelinuxLabel; - -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] -enum DockerDriverMountConfig { - Bind { - source: String, - target: String, - #[serde(default = "default_true")] - read_only: bool, - #[serde(default)] - selinux_label: Option, - }, - Volume { - source: String, - target: String, - #[serde(default = "default_true")] - read_only: bool, - #[serde(default)] - subpath: Option, - }, - Tmpfs { - target: String, - #[serde(default)] - options: Vec, - #[serde(default)] - size_bytes: Option, - #[serde(default)] - mode: Option, - }, - Image { - source: String, - target: String, - #[serde(default = "default_true")] - read_only: bool, - #[serde(default)] - subpath: Option, - }, -} - -fn default_true() -> bool { - true -} - -type WatchStream = - Pin> + Send + 'static>>; - -#[cfg(test)] -type TracedWatchStream = openshell_otel::TracedGrpcStream; - -/// Compute-driver service wrapper that preserves the standalone RPC trace -/// boundary while Docker runs in the gateway process. -#[derive(Clone)] -pub struct ComputeDriverService { - driver: DockerComputeDriver, - rpc_tracer: openshell_otel::InProcessRpcTracer, -} - -impl ComputeDriverService { - #[must_use] - pub fn new(driver: DockerComputeDriver) -> Self { - Self { - driver, - rpc_tracer: openshell_otel::InProcessRpcTracer::disabled(), - } - } - - #[must_use] - pub fn new_in_process(driver: DockerComputeDriver) -> Self { - Self { - driver, - rpc_tracer: openshell_otel::InProcessRpcTracer::enabled(), - } - } -} - -/// Return the first responsive local Docker API socket. -#[must_use] -pub fn detect_socket() -> Option { - let mut candidates = Vec::new(); - if let Ok(host) = std::env::var("DOCKER_HOST") - && let Some(path) = host.trim().strip_prefix("unix://") - && !path.is_empty() - { - candidates.push(PathBuf::from(path)); - } - candidates.push(PathBuf::from("/var/run/docker.sock")); - if let Some(home) = std::env::var_os("HOME") { - candidates.push(PathBuf::from(home).join(".docker/run/docker.sock")); - } - if let Some(runtime_dir) = std::env::var_os("XDG_RUNTIME_DIR") { - candidates.push(PathBuf::from(runtime_dir).join("docker.sock")); - } - openshell_core::local_api_socket::first_responsive_socket(&candidates, |response| { - openshell_core::local_api_socket::http_response_is_success(response) - && openshell_core::local_api_socket::contains_ascii(response, b"Api-Version:") - && !openshell_core::local_api_socket::contains_ascii(response, b"Libpod-Api-Version:") - }) -} - -#[must_use] -pub fn is_available() -> bool { - detect_socket().is_some() -} - -impl DockerComputeDriver { - pub async fn new( - gateway_bind_address: SocketAddr, - gateway_log_level: &str, - docker_config: &DockerComputeConfig, - network_trust: Option, - ) -> CoreResult { - docker_config.validate_configuration(gateway_bind_address)?; - let socket_path = docker_config - .socket_path - .clone() - .or_else(detect_socket) - .unwrap_or_else(|| PathBuf::from("/var/run/docker.sock")); - let socket_path_str = socket_path.to_str().ok_or_else(|| { - Error::config(format!( - "Docker socket path is not valid UTF-8: {}", - socket_path.display() - )) - })?; - let docker = - Docker::connect_with_socket(socket_path_str, 120, bollard::API_DEFAULT_VERSION) - .map_err(|err| { - Error::execution(format!("failed to create Docker client: {err}")) - })?; - let version = docker.version().await.map_err(|err| { - Error::execution(format!("failed to query Docker daemon version: {err}")) - })?; - if let Some(warning) = unsupported_docker_engine_warning(&version) { - warn!("{warning}"); - } - let info = docker.info().await.map_err(|err| { - Error::execution(format!("failed to query Docker daemon info: {err}")) - })?; - let cdi_supported = info - .cdi_spec_dirs - .as_ref() - .is_some_and(|dirs| !dirs.is_empty()); - let cdi_gpu_inventory = docker_cdi_gpu_inventory(&info); - let wsl_all_gpu_fallback_enabled = docker_info_reports_wsl2(&info); - let gpu = DockerGpuRuntimeCapabilities { - cdi_supported, - wsl_all_gpu_fallback_enabled, - }; - validate_docker_app_armor_profile(docker_config.app_armor_profile.as_ref(), &info)?; - let gateway_port = gateway_bind_address.port(); - let supervisor_endpoint_explicit = !docker_config.grpc_endpoint.trim().is_empty(); - let bridge_default_endpoint = default_docker_bridge_endpoint( - gateway_bind_address, - docker_guest_tls_configured(docker_config), - info.operating_system - .as_deref() - .is_some_and(|os| os.to_ascii_lowercase().contains("docker desktop")), - ); - let mut docker_config = docker_config.clone(); - if docker_config.grpc_endpoint.trim().is_empty() { - docker_config.grpc_endpoint = default_docker_supervisor_grpc_endpoint( - gateway_port, - docker_guest_tls_configured(&docker_config), - ); - } - Url::parse(&docker_config.grpc_endpoint).map_err(|error| { - Error::config(format!( - "invalid docker grpc_endpoint '{}': {error}", - docker_config.grpc_endpoint - )) - })?; - let supervisor_grpc_endpoint = docker_config.grpc_endpoint.clone(); - let supervisor_image = docker_config - .supervisor_image - .clone() - .unwrap_or_else(openshell_core::config::default_supervisor_image); - let supervisor_image_id = - ensure_runtime_image(&docker, &supervisor_image, "supervisor").await?; - let host_gateway_ip = if let Some(ip) = docker_config.host_gateway_ip { - Some(validate_docker_host_gateway_ip( - ip, - docker_config.supervisor_network_mode, - )?) - } else if docker_config.supervisor_network_mode == DockerSupervisorNetworkMode::Bridge - || Url::parse(&supervisor_grpc_endpoint).is_ok_and(|endpoint| { - matches!(endpoint.host(), Some(url::Host::Domain(host)) if host.eq_ignore_ascii_case(HOST_DOCKER_INTERNAL)) - }) - { - Some(resolve_docker_host_gateway(&docker, &supervisor_image_id, &docker_config.sandbox_label).await?) - } else { - docker_supervisor_host_address(&supervisor_grpc_endpoint) - }; - let sandbox_binary = if let Some(path) = docker_config.supervisor_bin.as_deref() { - validate_linux_elf_binary(path).map_err(Error::config)?; - Arc::new(tokio::fs::read(path).await.map_err(|error| { - Error::config(format!( - "failed to read trusted sandbox binary '{}': {error}", - path.display() - )) - })?) - } else { - let sandbox_runtime_image = docker_config - .sandbox_runtime_image - .clone() - .unwrap_or_else(openshell_core::config::default_sandbox_runtime_image); - let sandbox_runtime_image_id = - ensure_runtime_image(&docker, &sandbox_runtime_image, "sandbox runtime").await?; - Arc::new( - extract_sandbox_binary_bytes(&docker, &sandbox_runtime_image_id) - .await - .map_err(|error| { - Error::config(format!( - "failed to load trusted sandbox binary from Docker image '{sandbox_runtime_image}': {error}" - )) - })?, - ) - }; - let guest_tls = docker_guest_tls_paths(&docker_config)?; - let driver = Self { - docker: Arc::new(docker), - config: DockerDriverRuntimeConfig { - default_image: docker_config.default_image.clone(), - image_pull_policy: docker_config.image_pull_policy, - sandbox_namespace: docker_config.sandbox_label.clone(), - stop_timeout_secs: DEFAULT_STOP_TIMEOUT_SECS, - log_level: gateway_log_level.to_string(), - sandbox_binary, - supervisor_image_id, - supervisor_grpc_endpoint, - supervisor_otlp: docker_config.supervisor_otlp.clone(), - supervisor_network_mode: docker_config.supervisor_network_mode, - supervisor_endpoint_explicit, - bridge_default_endpoint, - host_gateway_ip, - supervisor_gateway_name: docker_config.supervisor_gateway_name.clone(), - ssh_socket_path: docker_config.ssh_socket_path.clone(), - guest_tls, - gpu, - sandbox_pids_limit: docker_config.sandbox_pids_limit, - enable_bind_mounts: docker_config.enable_bind_mounts, - workspace_storage: if docker_config.persist_workspace { - workspace::Storage::Persistent - } else { - workspace::Storage::WritableLayer - }, - allow_driver_config: docker_config.allow_driver_config, - resource_admission: docker_config.resource_admission.clone(), - upstream_proxy: docker_config.upstream_proxy.clone(), - proxy_ca_bundle: docker_config.proxy_ca_bundle.clone(), - ipv6_egress: docker_config.ipv6_egress.clone(), - provider_spiffe_workload_api_socket: docker_config - .provider_spiffe_workload_api_socket - .clone(), - app_armor_profile: docker_config.app_armor_profile.clone(), - network_trust, - }, - events: broadcast::channel(WATCH_BUFFER).0, - pending: Arc::new(Mutex::new(HashMap::new())), - gpu_selector: Arc::new(CdiGpuDefaultSelector::new( - cdi_gpu_inventory, - gpu.wsl_all_gpu_fallback_enabled, - )), - lifecycle_event_fences: DockerLifecycleEventFences::default(), - control_processes: Arc::new(Mutex::new(HashMap::new())), - runtime_failures: Arc::new(Mutex::new(HashMap::new())), - image_update_gates: Arc::new(image_update::Gates::default()), - }; - - Box::pin(driver.reconcile_runtime_resources_at_startup()) - .await - .map_err(|error| { - Error::config(format!( - "failed to reconcile Docker isolation resources: {}", - error.message() - )) - })?; - - let poll_driver = driver.clone(); - tokio::spawn(async move { - poll_driver.poll_loop().await; - }); - - Ok(driver) - } - - fn capabilities(&self) -> GetCapabilitiesResponse { - GetCapabilitiesResponse { - resource_admission_policy: openshell_core::resource_admission::DriverAdmissionConfig { - allow_driver_config: self.config.allow_driver_config, - resource_admission: self.config.resource_admission.clone(), - } - .acknowledgement(), - driver_name: "docker".to_string(), - driver_version: openshell_core::VERSION.to_string(), - default_image: self.config.default_image.clone(), - gateway_manages_lifecycle: true, - supports_sandbox_authentication: false, - driver_reports_runtime_readiness: false, - resource_capabilities: Some(ResourceCapabilities { - cpu: Some(CpuResourceCapabilities { - limit_supported: true, - }), - memory: Some(MemoryResourceCapabilities { - limit_supported: true, - }), - gpu: Some(GpuResourceCapabilities { - default_selection_supported: self.config.gpu.cdi_supported, - count_selection_supported: self.config.gpu.cdi_supported, - }), - }), - rootfs_tar_staging_dir: String::new(), - rootfs_tar_max_bytes: 0, - extension: Some(openshell_core::extension_protocol::extension_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - "openshell/docker", - openshell_core::VERSION, - if self.config.workspace_storage == workspace::Storage::Persistent { - vec![ - openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION - .to_string(), - ] - } else { - Vec::new() - }, - )), - } - } - - #[cfg(test)] - fn validate_sandbox( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - ) -> Result<(), Status> { - let _ = Self::validated_sandbox(sandbox, config)?; - Ok(()) - } - - fn validated_sandbox<'a>( - sandbox: &'a DriverSandbox, - config: &DockerDriverRuntimeConfig, - ) -> Result, Status> { - openshell_core::resource_admission::check_sandbox_driver_config( - config.allow_driver_config, - sandbox, - )?; - let spec = sandbox - .spec - .as_ref() - .ok_or_else(|| Status::invalid_argument("sandbox.spec is required"))?; - let template = spec - .template - .as_ref() - .ok_or_else(|| Status::invalid_argument("sandbox.spec.template is required"))?; - - Self::validate_sandbox_template_base(template)?; - let _ = docker_resource_limits(template)?; - let driver_config = - DockerSandboxDriverConfig::from_template(template).map_err(Status::invalid_argument)?; - validate_docker_driver_mounts(&driver_config.mounts, config.enable_bind_mounts)?; - for mount in &driver_config.mounts { - if matches!( - mount, - DockerDriverMountConfig::Bind { .. } | DockerDriverMountConfig::Image { .. } - ) { - config - .resource_admission - .reject_unlabelable("host bind or image mount")?; - } - } - let gpu_requirements = driver_gpu_requirements(spec.resource_requirements.as_ref()); - Self::validate_gpu_request(gpu_requirements, config.gpu.cdi_supported, &driver_config)?; - Ok(ValidatedDockerSandbox { - template, - driver_config, - gpu_requirements, - }) - } - - fn validate_sandbox_template_base(template: &DriverSandboxTemplate) -> Result<(), Status> { - if template.image.trim().is_empty() { - return Err(Status::failed_precondition( - "docker sandboxes require a template image", - )); - } - if !template.agent_socket_path.trim().is_empty() { - return Err(Status::failed_precondition( - "docker compute driver does not support template.agent_socket_path", - )); - } - if template - .platform_config - .as_ref() - .is_some_and(|config| !config.fields.is_empty()) - { - return Err(Status::failed_precondition( - "docker compute driver does not support template.platform_config", - )); - } - - Ok(()) - } - - fn validate_sandbox_auth(sandbox: &DriverSandbox) -> Result<(), Status> { - let authentication = sandbox - .spec - .as_ref() - .filter(|spec| !spec.launch_authentication.is_empty()) - .ok_or_else(|| { - Status::failed_precondition( - "docker sandboxes require launch-scoped gateway authentication", - ) - })?; - decode_docker_launch_authentication(&authentication.launch_authentication).map(|_| ()) - } - - fn validate_gpu_request( - gpu_requirements: Option<&GpuResourceRequirements>, - supports_gpu: bool, - driver_config: &DockerSandboxDriverConfig, - ) -> Result<(), Status> { - let requested_count = - effective_driver_gpu_count(gpu_requirements).map_err(Status::invalid_argument)?; - if requested_count.is_some() && !supports_gpu { - return Err(Status::failed_precondition( - "docker GPU sandboxes require Docker CDI support. Enable CDI on the Docker daemon, then restart the OpenShell gateway/server so GPU capability is detected.", - )); - } - - if let Some(cdi_devices) = driver_config.cdi_devices.as_deref() { - validate_cdi_gpu_device_request( - gpu_requirements, - cdi_devices, - "driver_config.cdi_devices", - ) - .map_err(Status::invalid_argument)?; - } - - Ok(()) - } - - async fn validate_user_volume_mounts_available( - &self, - driver_config: &DockerSandboxDriverConfig, - workspace: &str, - ) -> Result, Status> { - let mut identities = std::collections::BTreeMap::new(); - for mount in &driver_config.mounts { - if let DockerDriverMountConfig::Volume { source, .. } = mount { - match self.docker.inspect_volume(source).await { - Ok(volume) => { - identities.insert(source.clone(), docker_volume_identity(&volume)); - self.config - .resource_admission - .admit(workspace, &volume.labels) - .map_err(|error| { - Status::new( - error.code(), - format!("docker volume '{source}': {}", error.message()), - ) - })?; - if !self.config.enable_bind_mounts && docker_volume_is_bind_backed(&volume) - { - return Err(Status::failed_precondition(format!( - "docker volume '{source}' is backed by a host bind mount and requires enable_bind_mounts = true in [openshell.drivers.docker]" - ))); - } - } - Err(err) if is_not_found_error(&err) => { - return Err(Status::failed_precondition(format!( - "docker volume '{source}' does not exist" - ))); - } - Err(err) => { - return Err(internal_status("inspect docker volume", err)); - } - } - } - } - Ok(identities) - } - - async fn refresh_gpu_inventory(&self) -> Result<(), Status> { - let info = self - .docker - .info() - .await - .map_err(|err| internal_status("query Docker daemon info", err))?; - self.gpu_selector.refresh( - docker_cdi_gpu_inventory(&info), - self.config.gpu.wsl_all_gpu_fallback_enabled, - ); - Ok(()) - } - - async fn admit_container_resources( - &self, - container: &bollard::models::ContainerInspectResponse, - ) -> Result<(), Status> { - // Driver-owned state remains checked even when caller resource - // admission is explicitly disabled by an operator. - let persistent_workspace = workspace::admit(&self.docker, container, &self.config).await?; - if self.config.allow_driver_config && !self.config.resource_admission.enabled { - return Ok(()); - } - let labels = container - .config - .as_ref() - .and_then(|config| config.labels.as_ref()) - .ok_or_else(|| Status::failed_precondition("sandbox lacks admission metadata"))?; - openshell_core::resource_admission::check_config_provenance( - self.config.allow_driver_config, - labels - .get(openshell_core::resource_admission::CONFIG_USED_LABEL) - .map(String::as_str), - )?; - if !self.config.resource_admission.enabled { - return Ok(()); - } - let workspace = labels - .get(LABEL_SANDBOX_WORKSPACE) - .ok_or_else(|| Status::failed_precondition("sandbox lacks workspace"))?; - let sandbox_id = labels - .get(LABEL_SANDBOX_ID) - .ok_or_else(|| Status::failed_precondition("sandbox lacks identity"))?; - let expected: std::collections::BTreeMap = labels - .get(openshell_core::resource_admission::IDENTITIES_LABEL) - .and_then(|value| serde_json::from_str(value).ok()) - .ok_or_else(|| Status::failed_precondition("sandbox lacks resource identity record"))?; - let mut actual = std::collections::BTreeMap::new(); - let anonymous_targets: Vec = labels - .get("openshell.ai/private-image-volume-targets") - .and_then(|value| serde_json::from_str(value).ok()) - .unwrap_or_default(); - for mount in container.mounts.as_deref().unwrap_or_default() { - match mount.typ { - Some(bollard::models::MountPointTypeEnum::VOLUME) => { - let name = mount - .name - .as_deref() - .ok_or_else(|| Status::failed_precondition("volume lacks identity"))?; - let volume = self.docker.inspect_volume(name).await.map_err(|error| { - if is_not_found_error(&error) { - Status::failed_precondition("attached volume no longer exists") - } else { - Status::unavailable("volume admission lookup failed") - } - })?; - if name == docker_channel_volume_name_by_id(sandbox_id, &self.config) - || name == docker_control_volume_name_by_id(sandbox_id, &self.config) - { - if volume.driver != "local" - || !volume.options.is_empty() - || volume.labels.get(LABEL_SANDBOX_ID) != Some(sandbox_id) - || volume.labels.get(LABEL_MANAGED_BY).map(String::as_str) - != Some(LABEL_MANAGED_BY_VALUE) - { - return Err(Status::failed_precondition( - "sandbox-private volume ownership changed", - )); - } - } else if mount.destination.as_deref() - == Some(driver_mounts::DEFAULT_WORKSPACE_ROOT) - && persistent_workspace - { - // Independently checked above, including exact volume - // identity and the admitted workload UID/GID. - } else if !expected.contains_key(name) - && mount - .destination - .as_ref() - .is_some_and(|destination| anonymous_targets.contains(destination)) - { - // The immutable create spec requested a fresh anonymous - // image volume at this target, never an existing name. - if volume.driver != "local" || !volume.options.is_empty() { - return Err(Status::failed_precondition( - "image-private volume backing changed", - )); - } - } else { - actual.insert(name.to_string(), docker_volume_identity(&volume)); - self.config - .resource_admission - .admit(workspace, &volume.labels) - .map_err(|error| { - Status::new( - error.code(), - format!("docker volume '{name}': {}", error.message()), - ) - })?; - if !self.config.enable_bind_mounts && docker_volume_is_bind_backed(&volume) - { - return Err(Status::failed_precondition( - "bind-backed volume is disabled", - )); - } - } - } - Some(bollard::models::MountPointTypeEnum::TMPFS) => {} - _ => self - .config - .resource_admission - .reject_unlabelable("effective container mount")?, - } - } - if actual != expected { - return Err(Status::failed_precondition( - "external volume identity or attachment inventory changed", - )); - } - Ok(()) - } - - async fn resolve_gpu_cdi_devices( - &self, - gpu_requirements: Option<&GpuResourceRequirements>, - driver_config: &DockerSandboxDriverConfig, - select_default_devices: fn( - &CdiGpuDefaultSelector, - u32, - ) -> Result, CdiGpuSelectionError>, - ) -> Result>, Status> { - if let Some(cdi_devices) = driver_config.cdi_devices.as_deref() { - validate_cdi_gpu_device_request( - gpu_requirements, - cdi_devices, - "driver_config.cdi_devices", - ) - .map_err(Status::invalid_argument)?; - return Ok(Some(cdi_devices.to_vec())); - } - - let Some(count) = - effective_driver_gpu_count(gpu_requirements).map_err(Status::invalid_argument)? - else { - return Ok(None); - }; - - self.refresh_gpu_inventory().await?; - select_default_devices(&self.gpu_selector, count) - .map(Some) - .map_err(docker_gpu_selection_status) - } - - async fn resolve_docker_workload_identity( - &self, - sandbox: &DriverSandbox, - image: &DockerImageMetadata, - ) -> Result { - let container_name = format!("{}-identity", temp_extract_container_name()); - self.docker - .create_container( - Some( - CreateContainerOptionsBuilder::default() - .name(container_name.as_str()) - .build(), - ), - ContainerCreateBody { - image: Some(image.id.clone()), - labels: Some(docker_auxiliary_container_labels( - sandbox, - &self.config, - LABEL_ISOLATION_ROLE_IDENTITY, - )), - ..Default::default() - }, - ) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "create Docker identity resolver container: {error}" - )) - })?; - - let result = async { - let passwd = - download_path_from_container(&self.docker, &container_name, "/etc/passwd", true) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "read immutable image /etc/passwd for workload identity: {error}" - )) - })?; - let group = - download_path_from_container(&self.docker, &container_name, "/etc/group", true) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "read immutable image /etc/group for workload identity: {error}" - )) - })?; - resolve_docker_identity_from_accounts(sandbox, image, &passwd, &group) - } - .await; - - if let Err(error) = self - .docker - .remove_container( - &container_name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await - { - warn!( - container = container_name, - %error, - "Failed to remove Docker identity resolver container" - ); - } - result - } - - async fn get_sandbox_snapshot( - &self, - sandbox_id: &str, - sandbox_name: &str, - ) -> Result, Status> { - if let Some(pending) = self.pending_snapshot(sandbox_id, sandbox_name).await? { - return Ok(Some(pending)); - } - if let Some(pending) = - image_update::pending_snapshot(&self.config, sandbox_id, sandbox_name)? - { - return Ok(Some(pending)); - } - let container = self - .find_managed_container_summary(sandbox_id, sandbox_name) - .await?; - if let Some(mut sandbox) = - container.and_then(|summary| sandbox_from_container_summary(&summary)) - { - self.apply_runtime_failure(&mut sandbox).await; - return Ok(Some(sandbox)); - } - - Ok(None) - } - - async fn resolve_lifecycle_id(&self, id: &str, name: &str) -> Result, Status> { - if !id.is_empty() { - return Ok(Some(id.to_string())); - } - Ok(self - .get_sandbox_snapshot(id, name) - .await? - .map(|sandbox| sandbox.id)) - } - - async fn current_snapshots(&self) -> Result, Status> { - let containers = self.list_managed_container_summaries().await?; - let mut container_sandboxes = Vec::with_capacity(containers.len()); - for summary in &containers { - let Some(mut sandbox) = sandbox_from_container_summary(summary) else { - continue; - }; - if let Some(container_id) = summary.id.as_deref() { - match self.docker.inspect_container(container_id, None).await { - Ok(inspected) if summary.state == Some(ContainerSummaryStateEnum::EXITED) => { - // Docker's list summary carries no exit code. Inspect - // exited containers so daemon-restart kills remain - // distinguishable from terminal application exits. - if let Some(state) = inspected.state.as_ref() { - apply_docker_exit_classification(&mut sandbox, state); - } - } - Ok(inspected) if summary.state == Some(ContainerSummaryStateEnum::RUNNING) => { - let admission = match validate_docker_outer_fence(&inspected) { - Ok(()) => self.admit_container_resources(&inspected).await, - Err(error) => Err(error), - }; - if let Err(status) = admission - && status.code() == tonic::Code::FailedPrecondition - { - let context = self - .control_failure_context(sandbox.clone(), container_id.to_string()); - handle_docker_runtime_failure( - context, - "OuterFenceViolation", - status.message().to_string(), - ) - .await; - } - } - Ok(_) => {} - Err(err) => { - debug!( - container_id, - error = %err, - "Could not inspect Docker sandbox container during reconciliation" - ); - } - } - } - self.apply_runtime_failure(&mut sandbox).await; - container_sandboxes.push(sandbox); - } - let mut by_id = container_sandboxes - .into_iter() - .map(|sandbox| (sandbox.id.clone(), sandbox)) - .collect::>(); - // Provisioning state is authoritative until the supervisor has - // attached to both the sandbox and gateway. A running workload - // container alone is not a usable sandbox. - by_id.extend(self.pending_snapshot_map().await); - for pending in image_update::pending_snapshots(&self.config)? { - by_id.insert(pending.id.clone(), pending); - } - let mut sandboxes = by_id.into_values().collect::>(); - sandboxes.sort_by(|left, right| left.id.cmp(&right.id)); - Ok(sandboxes) - } - - async fn create_sandbox_inner(&self, sandbox: &DriverSandbox) -> Result<(), Status> { - self.verify_network_trust()?; - let validated = Self::validated_sandbox(sandbox, &self.config)?; - Self::validate_sandbox_auth(sandbox)?; - self.validate_user_volume_mounts_available(&validated.driver_config, &sandbox.workspace) - .await?; - let _ = self - .resolve_gpu_cdi_devices( - validated.gpu_requirements, - &validated.driver_config, - CdiGpuDefaultSelector::peek_device_ids, - ) - .await?; - - if self - .find_managed_container_summary(&sandbox.id, &sandbox.name) - .await? - .is_some() - { - return Err(Status::already_exists("sandbox already exists")); - } - - self.reserve_pending_sandbox(sandbox).await?; - let image = sandbox_image(sandbox).unwrap_or_default(); - self.publish_docker_progress( - &sandbox.id, - "Scheduled", - format!("Docker sandbox accepted for image \"{image}\""), - HashMap::from([("image_ref".to_string(), image.clone())]), - ); - self.publish_sandbox_snapshot(pending_sandbox_snapshot( - sandbox, - &self.config.sandbox_namespace, - provisioning_condition(), - false, - )); - - let driver = self.clone(); - let sandbox_for_task = sandbox.clone(); - let sandbox_id = sandbox.id.clone(); - let parent = tracing::Span::current().context(); - let provisioning_span = provisioning_span(&parent, sandbox, &image); - let task = tokio::spawn( - async move { - Box::pin(driver.provision_sandbox(sandbox_for_task)).await; - } - .instrument(provisioning_span), - ); - - let mut pending = self.pending.lock().await; - if let Some(record) = pending.get_mut(&sandbox_id) { - record.task = Some(task); - } else { - task.abort(); - } - - Ok(()) - } - - async fn provision_sandbox(&self, sandbox: DriverSandbox) { - match Box::pin(self.provision_sandbox_inner(&sandbox)).await { - Ok(()) => { - self.clear_pending_sandbox(&sandbox.id).await; - if let Err(error) = self - .publish_container_snapshot(&sandbox.id, &sandbox.name) - .await - { - warn!( - sandbox_id = %sandbox.id, - %error, - "Failed to publish Docker sandbox snapshot after provisioning" - ); - } - } - Err(failure) => { - self.fail_pending_sandbox(&sandbox, &failure).await; - } - } - } - - /// Provision from gateway-owned immutable input. - async fn provision_sandbox_inner( - &self, - sandbox: &DriverSandbox, - ) -> Result<(), DockerProvisioningFailure> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let validated = Self::validated_sandbox(sandbox, &self.config).map_err(|status| { - DockerProvisioningFailure::new("ContainerCreateFailed", status.message()) - })?; - let template = validated.template; - let cleanup_runtime_volumes = || async { - let _ = - remove_docker_channel_volume_by_id(&self.docker, &sandbox.id, &self.config).await; - }; - let image = async { - openshell_otel::record_error_result( - self.ensure_image_available(&sandbox.id, &template.image) - .await - .map_err(|status| { - DockerProvisioningFailure::new("ImagePullFailed", status.message()) - }), - ) - } - .instrument(tracing::info_span!( - "docker.prepare_image", - otel.name = "docker.prepare_image", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox.id, - image.ref = %template.image, - )) - .await?; - let workload_identity = self - .resolve_docker_workload_identity(sandbox, &image) - .await - .map_err(|status| { - DockerProvisioningFailure::new("IdentityResolutionFailed", status.message()) - })?; - prepare_docker_boundary_state_dir(sandbox, &self.config).map_err(|status| { - DockerProvisioningFailure::new("BoundaryStateCreateFailed", status.message()) - })?; - create_docker_channel_volume(&self.docker, sandbox, &self.config, true) - .await - .map_err(|status| { - cleanup_failed_docker_boundary_state(sandbox, &self.config); - DockerProvisioningFailure::new("BoundaryChannelCreateFailed", status.message()) - })?; - let token_file_created = match write_sandbox_token_file(sandbox, &self.config).await { - Ok(created) => created, - Err(status) => { - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::new( - "SandboxTokenWriteFailed", - status.message(), - )); - } - }; - if !token_file_created { - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::new( - "SandboxTokenWriteFailed", - "Docker control mode requires a gateway sandbox token", - )); - } - - let container_name = container_name_for_sandbox(sandbox); - let gpu_devices = match self - .resolve_gpu_cdi_devices( - validated.gpu_requirements, - &validated.driver_config, - CdiGpuDefaultSelector::next_device_ids, - ) - .await - { - Ok(devices) => devices, - Err(status) => { - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::new( - "ContainerCreateFailed", - status.message(), - )); - } - }; - let mut create_body = match build_container_create_body_for_image( - sandbox, - &self.config, - &validated.driver_config, - gpu_devices.as_deref(), - &image, - &workload_identity, - ) { - Ok(body) => body, - Err(status) => { - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::new( - "ContainerCreateFailed", - status.message(), - )); - } - }; - let identities = match self - .validate_user_volume_mounts_available(&validated.driver_config, &sandbox.workspace) - .await - { - Ok(identities) => identities, - Err(status) => { - let _ = remove_docker_channel_volume_by_id(&self.docker, &sandbox.id, &self.config) - .await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::from_admission_status(status)); - } - }; - create_body - .labels - .get_or_insert_with(Default::default) - .insert( - openshell_core::resource_admission::IDENTITIES_LABEL.into(), - serde_json::to_string(&identities).map_err(|error| { - DockerProvisioningFailure::new("ResourceAdmissionDenied", error.to_string()) - })?, - ); - match workspace::prepare( - &self.docker, - sandbox, - &self.config, - &image, - &workload_identity, - ) - .await - { - Ok(_) => {} - Err(status) => { - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::from_status( - "WorkspaceStorageFailed", - status, - )); - } - } - let create_result = async { - openshell_otel::record_error_result( - self.docker - .create_container( - Some( - CreateContainerOptionsBuilder::default() - .name(container_name.as_str()) - .build(), - ), - create_body, - ) - .await, - ) - } - .instrument(tracing::info_span!( - "docker.create_container", - otel.name = "docker.create_container", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox.id, - container.name = %container_name, - )) - .await; - let created = match create_result { - Ok(created) => created, - Err(error) => { - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::from_status( - "ContainerCreateFailed", - create_status_from_docker_error("create docker sandbox container", error), - )); - } - }; - let inspected = match self.docker.inspect_container(&created.id, None).await { - Ok(inspected) => inspected, - Err(error) => { - let _ = self - .docker - .remove_container( - &created.id, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::from_status( - "OuterFenceInspectFailed", - internal_status("inspect Docker sandbox outer fence", error), - )); - } - }; - let outer_fence_error = match validate_docker_outer_fence(&inspected) { - Ok(()) => self.admit_container_resources(&inspected).await.err(), - Err(error) => Some(error), - }; - drop(inspected); - if let Some(status) = outer_fence_error { - let _ = self - .docker - .remove_container( - &created.id, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::from_status( - "OuterFenceRejected", - status, - )); - } - self.publish_docker_progress( - &sandbox.id, - "Created", - format!("Created Docker container \"{container_name}\""), - HashMap::from([("container_name".to_string(), container_name.clone())]), - ); - - match prepare_docker_boundary_files( - &self.docker, - sandbox, - &self.config, - &created.id, - &image, - &workload_identity, - gpu_devices.is_some(), - ) - .await - { - Ok(()) => {} - Err(status) => { - let _ = self - .docker - .remove_container( - &container_name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::new( - "BoundaryConfigWriteFailed", - status.message(), - )); - } - } - - let start_result = async { - openshell_otel::record_error_result( - self.docker.start_container(&container_name, None).await, - ) - } - .instrument(tracing::info_span!( - "docker.start_container", - otel.name = "docker.start_container", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox.id, - container.name = %container_name, - )) - .await; - if let Err(err) = start_result { - let cleanup = self - .docker - .remove_container( - &container_name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - if let Err(cleanup_err) = cleanup { - warn!( - sandbox_id = %sandbox.id, - container_name, - error = %cleanup_err, - "Failed to clean up Docker container after start failure" - ); - } - cleanup_failed_docker_boundary_state(sandbox, &self.config); - cleanup_runtime_volumes().await; - return Err(DockerProvisioningFailure::from_status( - "ContainerStartFailed", - create_status_from_docker_error("start docker sandbox container", err), - )); - } - self.clear_runtime_failure(&sandbox.id).await; - let failure_context = self.control_failure_context(sandbox.clone(), created.id.clone()); - let control = match spawn_docker_control_process( - &self.docker, - sandbox, - &self.config, - failure_context, - ) - .await - { - Ok(control) => control, - Err(status) => { - if self - .lifecycle_event_fences - .stop_requested(&sandbox.id, &sandbox.name) - { - debug!( - sandbox_id = %sandbox.id, - "Ignoring Docker supervisor startup interruption after an explicit stop" - ); - return span_status.finish(Ok(())); - } - let _ = self - .docker - .remove_container( - &container_name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - cleanup_runtime_volumes().await; - cleanup_failed_docker_boundary_state(sandbox, &self.config); - return Err(DockerProvisioningFailure::new( - supervisor_start_failure_reason(&status, "ControlSupervisorStartFailed"), - status.message(), - )); - } - }; - if self - .lifecycle_event_fences - .stop_requested(&sandbox.id, &sandbox.name) - { - stop_docker_control_process(control).await; - debug!( - sandbox_id = %sandbox.id, - "Discarded Docker supervisor that became ready after an explicit stop" - ); - return span_status.finish(Ok(())); - } - self.replace_control_process(&sandbox.id, control).await; - self.publish_docker_progress( - &sandbox.id, - "Started", - format!("Started Docker container \"{container_name}\""), - HashMap::from([("container_name".to_string(), container_name)]), - ); - span_status.finish(Ok(())) - } - - async fn replace_control_process(&self, sandbox_id: &str, process: DockerControlProcess) { - let previous = self - .control_processes - .lock() - .await - .insert(sandbox_id.to_string(), process); - if let Some(previous) = previous { - stop_docker_control_process(previous).await; - } - } - - async fn clear_runtime_failure(&self, sandbox_id: &str) { - self.runtime_failures.lock().await.remove(sandbox_id); - } - - /// Re-read the immutable artifact directly before any container launch or - /// stopped-pair reconciliation. The bundle never appears in a sandbox - /// request or workload environment, and errors redact its PEM contents. - fn verify_network_trust(&self) -> Result<(), Status> { - if let Some(bundle) = self.config.network_trust.as_ref() { - bundle.verify_artifact().map_err(|error| { - Status::failed_precondition(format!( - "verify gateway-owned network additional CA artifact: {error}" - )) - })?; - } - Ok(()) - } - - fn control_failure_context( - &self, - sandbox: DriverSandbox, - container_id: String, - ) -> DockerRuntimeFailureContext { - DockerRuntimeFailureContext { - docker: self.docker.clone(), - events: self.events.clone(), - failures: self.runtime_failures.clone(), - sandbox, - sandbox_namespace: self.config.sandbox_namespace.clone(), - container_id, - stop_timeout_secs: self.config.stop_timeout_secs, - } - } - - async fn apply_runtime_failure(&self, sandbox: &mut DriverSandbox) { - let container_is_running = sandbox.status.as_ref().is_some_and(|status| { - status.conditions.iter().any(|condition| { - condition.r#type == "Ready" - && condition.status == "True" - && condition.reason == "BackendReady" - }) - }); - if !container_is_running { - return; - } - let failure = self.runtime_failures.lock().await.get(&sandbox.id).cloned(); - if let Some(failure) = failure { - set_sandbox_ready_condition(sandbox, error_condition(failure.reason, &failure.message)); - } - } - - async fn stop_control_process(&self, sandbox_id: &str) { - let process = self.control_processes.lock().await.remove(sandbox_id); - if let Some(process) = process { - stop_docker_control_process(process).await; - } - } - - async fn remove_auxiliary_containers_for_sandbox( - &self, - sandbox_id: &str, - ) -> Result { - let filters = managed_resource_label_filters( - &self.config.sandbox_namespace, - [format!("{LABEL_SANDBOX_ID}={sandbox_id}")], - ); - let containers = self - .docker - .list_containers(Some( - ListContainersOptionsBuilder::default() - .all(true) - .filters(&filters) - .build(), - )) - .await - .map_err(|error| internal_status("list Docker auxiliary containers", error))?; - let mut removed = false; - for container in containers { - let role = container - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_ISOLATION_ROLE)) - .map(String::as_str); - if !matches!( - role, - Some( - LABEL_ISOLATION_ROLE_SUPERVISOR - | LABEL_ISOLATION_ROLE_STAGING - | LABEL_ISOLATION_ROLE_IDENTITY - ) - ) { - continue; - } - let Some(target) = summary_container_target(&container) else { - continue; - }; - self.docker - .remove_container( - &target, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await - .or_else(|error| { - if is_not_found_error(&error) || is_removal_in_progress_error(&error) { - Ok(()) - } else { - Err(error) - } - }) - .map_err(|error| internal_status("remove Docker auxiliary container", error))?; - removed = true; - } - Ok(removed) - } - - async fn reconcile_runtime_resources_at_startup(&self) -> Result<(), Status> { - // Startup reconciliation must not inspect a changed artifact and then - // leave a trusted supervisor eligible for launch. - self.verify_network_trust()?; - let sandboxes = self.list_managed_container_summaries().await?; - let mut sandbox_ids = sandboxes - .iter() - .filter_map(|container| { - container - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) - .cloned() - }) - .collect::>(); - // A valid accepted update can temporarily have no workload container. - // Its runtime channel/key resources are not orphans during that gap. - sandbox_ids.extend(image_update::pending_ids(&self.config)?); - - let filters = managed_resource_label_filters(&self.config.sandbox_namespace, []); - let auxiliary = self - .docker - .list_containers(Some( - ListContainersOptionsBuilder::default() - .all(true) - .filters(&filters) - .build(), - )) - .await - .map_err(|error| internal_status("list Docker startup resources", error))?; - for container in auxiliary { - let role = container - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_ISOLATION_ROLE)) - .map(String::as_str); - if !matches!( - role, - Some( - LABEL_ISOLATION_ROLE_SUPERVISOR - | LABEL_ISOLATION_ROLE_STAGING - | LABEL_ISOLATION_ROLE_IDENTITY - ) - ) { - continue; - } - let Some(target) = summary_container_target(&container) else { - continue; - }; - self.docker - .remove_container( - &target, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await - .or_else(|error| { - if is_not_found_error(&error) { - Ok(()) - } else { - Err(error) - } - }) - .map_err(|error| internal_status("remove stale Docker auxiliary", error))?; - } - - let volume_filters = label_filters([ - format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE}"), - format!( - "{LABEL_SANDBOX_NAMESPACE}={}", - self.config.sandbox_namespace - ), - format!("{LABEL_ISOLATION_BACKEND}={LABEL_ISOLATION_BACKEND_OPEN_SHELL}"), - ]); - let volumes = self - .docker - .list_volumes(Some( - ListVolumesOptionsBuilder::default() - .filters(&volume_filters) - .build(), - )) - .await - .map_err(|error| internal_status("list Docker startup volumes", error))?; - for volume in volumes.volumes.unwrap_or_default() { - // Workspace storage is retained independently of disposable runtime - // resources, including a future interrupted replacement gap. - if volume.labels.get(workspace::ROLE_LABEL).map(String::as_str) == Some(workspace::ROLE) - { - continue; - } - let sandbox_id = volume.labels.get(LABEL_SANDBOX_ID); - if sandbox_id.is_some_and(|id| sandbox_ids.contains(id)) { - continue; - } - self.docker - .remove_volume( - &volume.name, - None::, - ) - .await - .or_else(|error| { - if is_not_found_error(&error) { - Ok(()) - } else { - Err(error) - } - }) - .map_err(|error| internal_status("remove orphan Docker channel volume", error))?; - } - - Ok(()) - } - - async fn ensure_control_process_for_container( - &self, - container: &ContainerSummary, - ) -> Result<(), Status> { - let Some(sandbox) = sandbox_from_container_summary(container) else { - return Err(Status::internal( - "managed Docker container is missing sandbox identity labels", - )); - }; - let stale = { - let mut processes = self.control_processes.lock().await; - match processes.get(&sandbox.id) { - Some(process) if !process.task.is_finished() => return Ok(()), - Some(_) => processes.remove(&sandbox.id), - None => None, - } - }; - if let Some(stale) = stale { - stop_docker_control_process(stale).await; - } - if read_docker_runtime_descriptor(&sandbox.id, &self.config) - .await? - .is_none() - { - let container_id = summary_container_target(container) - .ok_or_else(|| Status::internal("managed Docker container has no id or name"))?; - let failure_context = self.control_failure_context(sandbox.clone(), container_id); - let status = Status::failed_precondition( - "Docker sandbox runtime descriptor is missing; refusing to leave the workload running without its supervisor", - ); - handle_docker_runtime_failure( - failure_context, - "ControlSupervisorExited", - status.message().to_string(), - ) - .await; - return Err(status); - } - let container_id = summary_container_target(container) - .ok_or_else(|| Status::internal("managed Docker container has no id or name"))?; - self.clear_runtime_failure(&sandbox.id).await; - let failure_context = self.control_failure_context(sandbox.clone(), container_id); - let process = match spawn_docker_control_process( - &self.docker, - &sandbox, - &self.config, - failure_context.clone(), - ) - .await - { - Ok(process) => process, - Err(status) => { - handle_docker_runtime_failure( - failure_context, - supervisor_start_failure_reason(&status, "ControlSupervisorExited"), - format!( - "failed to start Docker control supervisor: {}", - status.message() - ), - ) - .await; - return Err(status); - } - }; - self.replace_control_process(&sandbox.id, process).await; - Ok(()) - } - - async fn delete_sandbox_inner( - &self, - sandbox_id: &str, - sandbox_name: &str, - ) -> Result { - let pending = self - .remove_pending_sandbox(sandbox_id, sandbox_name) - .await?; - if let Some(record) = pending.as_ref() - && let Some(task) = record.task.as_ref() - { - task.abort(); - } - if let Some(record) = pending.as_ref() { - self.stop_control_process(&record.sandbox.id).await; - self.remove_auxiliary_containers_for_sandbox(&record.sandbox.id) - .await?; - } - - let Some(container) = self - .find_managed_container_summary(sandbox_id, sandbox_name) - .await? - else { - if let Some(record) = pending { - let container_name = container_name_for_sandbox(&record.sandbox); - match self - .docker - .remove_container( - &container_name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await - { - Ok(()) => { - self.clear_runtime_failure(&record.sandbox.id).await; - remove_docker_owned_storage_by_id( - &self.docker, - &record.sandbox.id, - &self.config, - ) - .await?; - cleanup_docker_boundary_state(&record.sandbox, &self.config); - return Ok(true); - } - Err(err) if is_not_found_error(&err) => { - self.clear_runtime_failure(&record.sandbox.id).await; - remove_docker_owned_storage_by_id( - &self.docker, - &record.sandbox.id, - &self.config, - ) - .await?; - cleanup_docker_boundary_state(&record.sandbox, &self.config); - return Ok(true); - } - Err(err) => { - return Err(internal_status("delete docker sandbox container", err)); - } - } - } - if !sandbox_id.is_empty() { - let removed_update = - image_update::pending_snapshot(&self.config, sandbox_id, sandbox_name)? - .is_some(); - self.stop_control_process(sandbox_id).await; - let removed = self - .remove_auxiliary_containers_for_sandbox(sandbox_id) - .await?; - remove_docker_owned_storage_by_id(&self.docker, sandbox_id, &self.config).await?; - cleanup_docker_boundary_state_by_id(sandbox_id, &self.config); - self.clear_runtime_failure(sandbox_id).await; - return Ok(removed || removed_update); - } - return Ok(false); - }; - let Some(target) = summary_container_target(&container) else { - return Ok(pending.is_some()); - }; - let resolved_sandbox_id = container - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) - .map_or(sandbox_id, String::as_str); - self.stop_control_process(resolved_sandbox_id).await; - self.remove_auxiliary_containers_for_sandbox(resolved_sandbox_id) - .await?; - - match self - .docker - .remove_container( - &target, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await - { - Ok(()) => { - self.clear_runtime_failure(resolved_sandbox_id).await; - remove_docker_owned_storage_by_id(&self.docker, resolved_sandbox_id, &self.config) - .await?; - cleanup_docker_boundary_state_by_id(resolved_sandbox_id, &self.config); - Ok(true) - } - Err(err) if is_not_found_error(&err) => { - self.clear_runtime_failure(resolved_sandbox_id).await; - remove_docker_owned_storage_by_id(&self.docker, resolved_sandbox_id, &self.config) - .await?; - cleanup_docker_boundary_state_by_id(resolved_sandbox_id, &self.config); - Ok(pending.is_some()) - } - Err(err) => Err(internal_status("delete docker sandbox container", err)), - } - } - - async fn stop_sandbox_inner(&self, sandbox_id: &str, sandbox_name: &str) -> Result<(), Status> { - let container = self - .find_managed_container_summary(sandbox_id, sandbox_name) - .await?; - // Startup can still be waiting for supervisor readiness after the - // workload container exists. Cancel it before removing the supervisor - // so its failure path cannot delete retained workload storage. - let mut pending = self - .remove_pending_sandbox(sandbox_id, sandbox_name) - .await?; - if let Some(task) = pending.as_mut().and_then(|record| record.task.take()) { - task.abort(); - let _ = task.await; - } - let Some(container) = container else { - if let Some(record) = pending { - self.stop_control_process(&record.sandbox.id).await; - self.remove_auxiliary_containers_for_sandbox(&record.sandbox.id) - .await?; - self.clear_runtime_failure(&record.sandbox.id).await; - remove_docker_channel_volume_by_id(&self.docker, &record.sandbox.id, &self.config) - .await?; - cleanup_failed_docker_boundary_state(&record.sandbox, &self.config); - self.publish_deleted(record.sandbox.id); - return Ok(()); - } - if !sandbox_id.is_empty() { - self.stop_control_process(sandbox_id).await; - self.remove_auxiliary_containers_for_sandbox(sandbox_id) - .await?; - } - if image_update::pending_snapshot(&self.config, sandbox_id, sandbox_name)?.is_some() { - return Ok(()); - } - return Err(Status::not_found("sandbox not found")); - }; - let Some(target) = summary_container_target(&container) else { - return Err(Status::not_found("sandbox container has no id or name")); - }; - let resolved_sandbox_id = container - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) - .map_or(sandbox_id, String::as_str); - self.stop_control_process(resolved_sandbox_id).await; - self.remove_auxiliary_containers_for_sandbox(resolved_sandbox_id) - .await?; - - let result = match self - .docker - .stop_container( - &target, - Some( - StopContainerOptionsBuilder::default() - .t(docker_stop_timeout_secs(self.config.stop_timeout_secs)) - .build(), - ), - ) - .await - { - Ok(()) => Ok(()), - Err(err) if is_not_modified_error(&err) => Ok(()), - Err(err) if is_not_found_error(&err) => Err(Status::not_found("sandbox not found")), - Err(err) => Err(internal_status("stop docker sandbox container", err)), - }; - if result.is_ok() { - self.clear_runtime_failure(resolved_sandbox_id).await; - } - result - } - - /// Start a managed sandbox container that was previously stopped. Used - /// by the gateway to start sandboxes after a restart so that running - /// state in the gateway store is matched by an actually-running - /// container. - /// - /// Returns `Ok(true)` when a container existed and was started (or was - /// already running), `Ok(false)` when no managed container is found for - /// the sandbox, and `Err(...)` for any Docker failure. - #[tracing::instrument( - name = "docker.start_sandbox", - skip_all, - fields( - otel.name = "docker.start_sandbox", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - sandbox.name = %sandbox_name, - ) - )] - pub async fn start_sandbox( - &self, - sandbox_id: &str, - sandbox_name: &str, - generation_id: &str, - launch_authentication: &[u8], - durable_sandbox: Option<&DriverSandbox>, - ) -> Result { - let span_status = openshell_otel::ErrorStatusGuard::current(); - require_sandbox_identifier(sandbox_id, sandbox_name)?; - let generation = openshell_core::sandbox_generation::SandboxGenerationId::parse( - generation_id.to_string(), - ) - .map_err(|error| Status::invalid_argument(error.to_string()))?; - let resolved_id = self - .resolve_lifecycle_id(sandbox_id, sandbox_name) - .await? - .ok_or_else(|| Status::not_found("sandbox not found"))?; - let _lifecycle = self - .image_update_gates - .gate_for(&resolved_id) - .lock_owned() - .await; - image_update::require_settled(&self.config, &resolved_id)?; - self.lifecycle_event_fences - .clear_stop(&resolved_id, sandbox_name); - self.lifecycle_event_fences.begin_start(&resolved_id); - let result = Box::pin(self.start_sandbox_with_lifecycle_fence( - &resolved_id, - sandbox_name, - &generation, - launch_authentication, - durable_sandbox, - )) - .await; - self.lifecycle_event_fences.finish_start(&resolved_id); - span_status.finish(result) - } - - async fn start_sandbox_with_lifecycle_fence( - &self, - sandbox_id: &str, - sandbox_name: &str, - generation: &openshell_core::sandbox_generation::SandboxGenerationId, - launch_authentication: &[u8], - _durable_sandbox: Option<&DriverSandbox>, - ) -> Result { - self.verify_network_trust()?; - let Some(container) = self - .find_managed_container_summary(sandbox_id, sandbox_name) - .await? - else { - return Ok(false); - }; - let Some(target) = summary_container_target(&container) else { - return Ok(false); - }; - let inspected = self - .docker - .inspect_container(&target, None) - .await - .map_err(|error| internal_status("inspect Docker sandbox outer fence", error))?; - validate_docker_outer_fence(&inspected)?; - self.admit_container_resources(&inspected).await?; - let state = container.state.unwrap_or(ContainerSummaryStateEnum::EMPTY); - let validation = if container_state_needs_start(state) && !launch_authentication.is_empty() - { - image_update::LaunchValidation::BeforeStoppedRotation - } else { - image_update::LaunchValidation::Complete - }; - image_update::validate_committed_resource( - &self.config, - sandbox_id, - &inspected, - validation, - )?; - let previous_finished_at = if state == ContainerSummaryStateEnum::EXITED { - inspected - .state - .as_ref() - .filter(|state| state.status == Some(ContainerStateStatusEnum::EXITED)) - .and_then(|state| state.finished_at.clone()) - } else { - None - }; - drop(inspected); - let resolved_sandbox_id = container - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) - .map_or(sandbox_id, String::as_str); - // No destination-trust gating here: the trusted supervisor container - // is re-created from the gateway's current configuration on every - // start (see `ensure_control_process_for_container`), so stop/start - // picks up the current additional CA bundle without ever touching - // the workload container or its data. - if !container_state_needs_start(state) { - adopt_or_verify_docker_start_generation(resolved_sandbox_id, &self.config, generation) - .await?; - if launch_authentication.is_empty() { - self.ensure_control_process_for_container(&container) - .await?; - return Ok(true); - } - - // A gateway restart refreshes the supervisor-facing credentials. - // The running sandbox keeps its driver-owned channel identity, - // TLS identity, and process tree. - self.stop_control_process(resolved_sandbox_id).await; - refresh_docker_supervisor_authentication( - resolved_sandbox_id, - &self.config, - launch_authentication, - ) - .await?; - self.ensure_control_process_for_container(&container) - .await?; - return Ok(true); - } - - // Fence a poll that observed this stopped run but has not published it - // yet. Use Docker's transition timestamp so a later, genuine exit from - // the restarted container remains observable. - self.lifecycle_event_fences - .record_previous_exit(sandbox_id, previous_finished_at.as_deref()); - - write_docker_boundary_file( - &docker_boundary_state_dir_by_id(resolved_sandbox_id, &self.config)? - .join(START_GENERATION_FILE), - generation.as_str().as_bytes(), - ) - .await?; - // Rotate launch-scoped credentials before either process starts. - if !launch_authentication.is_empty() { - refresh_docker_boundary_authentication( - resolved_sandbox_id, - &self.config, - launch_authentication, - ) - .await?; - } - image_update::validate_committed_boundary(&self.config, resolved_sandbox_id)?; - let Some(runtime_descriptor) = - read_docker_runtime_descriptor(resolved_sandbox_id, &self.config).await? - else { - return Err(Status::failed_precondition( - "Docker sandbox runtime descriptor is missing; refusing to start the workload without its supervisor", - )); - }; - let boundary_config = tokio::fs::read( - docker_boundary_state_dir_by_id(resolved_sandbox_id, &self.config)? - .join(BOUNDARY_CONFIG_FILE), - ) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "read Docker sandbox bootstrap for restart: {error}" - )) - })?; - let boundary_directory = - docker_boundary_state_dir_by_id(resolved_sandbox_id, &self.config)?; - let boundary_certificate = - tokio::fs::read(boundary_directory.join(BOUNDARY_CERTIFICATE_FILE)) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "read Docker sandbox channel certificate for restart: {error}" - )) - })?; - let boundary_private_key = - tokio::fs::read(boundary_directory.join(BOUNDARY_PRIVATE_KEY_FILE)) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "read Docker sandbox channel private key for restart: {error}" - )) - })?; - let workspace_root = tokio::fs::read_to_string( - docker_boundary_state_dir_by_id(resolved_sandbox_id, &self.config)? - .join(WORKSPACE_ROOT_FILE), - ) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "read Docker sandbox workspace for restart: {error}" - )) - })?; - stage_docker_sandbox_bundle( - &self.docker, - &target, - &self.config, - &runtime_descriptor.workload_identity, - &boundary_config, - DockerSandboxTls { - certificate: &boundary_certificate, - private_key: &boundary_private_key, - }, - &workspace_root, - ) - .await?; - - match self.docker.start_container(&target, None).await { - Ok(()) => {} - // Already running — race with another start path or the - // restart policy. Treat as success. - Err(err) if is_not_modified_error(&err) => {} - Err(err) if is_not_found_error(&err) => return Ok(false), - Err(err) => return Err(internal_status("start docker sandbox container", err)), - } - adopt_or_verify_docker_start_generation(resolved_sandbox_id, &self.config, generation) - .await?; - self.ensure_control_process_for_container(&container) - .await?; - Ok(true) - } - - async fn reserve_pending_sandbox(&self, sandbox: &DriverSandbox) -> Result<(), Status> { - let mut pending = self.pending.lock().await; - if pending - .values() - .any(|record| record.sandbox.id == sandbox.id) - { - return Err(Status::already_exists("sandbox already exists")); - } - - pending.insert( - sandbox.id.clone(), - PendingSandboxRecord { - sandbox: pending_sandbox_snapshot( - sandbox, - &self.config.sandbox_namespace, - provisioning_condition(), - false, - ), - task: None, - }, - ); - Ok(()) - } - - async fn pending_snapshot( - &self, - sandbox_id: &str, - sandbox_name: &str, - ) -> Result, Status> { - let pending = self.pending.lock().await; - let id = pending_sandbox_record_id(&pending, sandbox_id, sandbox_name)?; - Ok(id.and_then(|id| pending.get(&id).map(|record| record.sandbox.clone()))) - } - - async fn pending_snapshot_map(&self) -> HashMap { - let pending = self.pending.lock().await; - pending - .iter() - .map(|(sandbox_id, record)| (sandbox_id.clone(), record.sandbox.clone())) - .collect() - } - - async fn clear_pending_sandbox(&self, sandbox_id: &str) { - let mut pending = self.pending.lock().await; - pending.remove(sandbox_id); - } - - async fn remove_pending_sandbox( - &self, - sandbox_id: &str, - sandbox_name: &str, - ) -> Result, Status> { - let mut pending = self.pending.lock().await; - let Some(id) = pending_sandbox_record_id(&pending, sandbox_id, sandbox_name)? else { - return Ok(None); - }; - Ok(pending.remove(&id)) - } - - async fn fail_pending_sandbox( - &self, - sandbox: &DriverSandbox, - failure: &DockerProvisioningFailure, - ) { - cleanup_failed_docker_boundary_state(sandbox, &self.config); - let snapshot = pending_sandbox_snapshot( - sandbox, - &self.config.sandbox_namespace, - error_condition(failure.reason, &failure.message), - false, - ); - { - let mut pending = self.pending.lock().await; - if let Some(record) = pending.get_mut(&sandbox.id) { - record.sandbox = snapshot.clone(); - record.task = None; - } else { - return; - } - } - - self.publish_platform_event( - sandbox.id.clone(), - platform_event( - "docker", - "Warning", - failure.reason, - format!("Docker sandbox provisioning failed: {}", failure.message), - ), - ); - self.publish_sandbox_snapshot(snapshot); - } - - async fn publish_container_snapshot( - &self, - sandbox_id: &str, - sandbox_name: &str, - ) -> Result<(), Status> { - if let Some(sandbox) = self.get_sandbox_snapshot(sandbox_id, sandbox_name).await? { - self.publish_sandbox_snapshot(sandbox); - } - Ok(()) - } - - fn publish_sandbox_snapshot(&self, sandbox: DriverSandbox) { - let _ = self.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Sandbox( - WatchSandboxesSandboxEvent { - sandbox: Some(sandbox), - }, - )), - }); - } - - fn publish_deleted(&self, sandbox_id: String) { - let _ = self.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Deleted( - WatchSandboxesDeletedEvent { sandbox_id }, - )), - }); - } - - fn publish_platform_event(&self, sandbox_id: String, event: DriverPlatformEvent) { - let _ = self.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::PlatformEvent( - WatchSandboxesPlatformEvent { - sandbox_id, - event: Some(event), - }, - )), - }); - } - - fn publish_docker_progress( - &self, - sandbox_id: &str, - reason: &str, - message: String, - mut metadata: HashMap, - ) { - attach_docker_progress_metadata(&mut metadata, reason, &message); - self.publish_platform_event( - sandbox_id.to_string(), - DriverPlatformEvent { - event_time: openshell_core::time::timestamp_from_millis( - openshell_core::time::now_ms(), - ) - .ok(), - source: "docker".to_string(), - r#type: "Normal".to_string(), - reason: reason.to_string(), - message, - metadata, - }, - ); - } - - async fn poll_loop(self) { - let mut previous = match self.current_snapshot_map().await { - Ok(snapshots) => snapshots, - Err(err) => { - warn!(error = %err, "Failed to seed Docker sandbox watch state"); - HashMap::new() - } - }; - - // Exponential backoff on consecutive Docker failures to avoid a 2s - // warn-log flood when the daemon is unreachable for an extended - // period (e.g. restart, socket removed). - let mut backoff = WATCH_POLL_INTERVAL; - loop { - tokio::time::sleep(backoff).await; - match self.current_snapshot_map().await { - Ok(current) => { - self.publish_snapshot_diff(&previous, ¤t).await; - previous = current; - backoff = WATCH_POLL_INTERVAL; - } - Err(err) => { - warn!( - error = %err, - backoff_secs = backoff.as_secs(), - "Failed to poll Docker sandboxes" - ); - backoff = (backoff * 2).min(WATCH_POLL_MAX_BACKOFF); - } - } - } - } - - async fn current_snapshot_map(&self) -> Result, Status> { - self.current_snapshots().await.map(|snapshots| { - snapshots - .into_iter() - .map(|sandbox| (sandbox.id.clone(), sandbox)) - .collect() - }) - } - - async fn publish_snapshot_diff( - &self, - previous: &HashMap, - current: &HashMap, - ) { - for (sandbox_id, sandbox) in current { - if previous.get(sandbox_id) == Some(sandbox) { - continue; - } - if self.stale_polled_exit(sandbox).await { - continue; - } - self.publish_sandbox_snapshot(sandbox.clone()); - } - - for sandbox_id in previous.keys() { - if current.contains_key(sandbox_id) { - continue; - } - self.publish_deleted(sandbox_id.clone()); - } - } - - async fn stale_polled_exit(&self, sandbox: &DriverSandbox) -> bool { - if !driver_sandbox_reports_container_exit(sandbox) { - return false; - } - if self.lifecycle_event_fences.start_in_progress(&sandbox.id) { - debug!( - sandbox_id = %sandbox.id, - "Ignoring Docker container exit snapshot while sandbox start is in progress" - ); - return true; - } - let Some(previous_finished_at) = self.lifecycle_event_fences.previous_exit(&sandbox.id) - else { - return false; - }; - let Some(container_id) = sandbox - .status - .as_ref() - .map(|status| status.instance_id.as_str()) - .filter(|container_id| !container_id.is_empty()) - else { - return false; - }; - - let inspected = match self.docker.inspect_container(container_id, None).await { - Ok(inspected) => inspected, - Err(err) => { - debug!( - sandbox_id = %sandbox.id, - container_id, - error = %err, - "Could not verify whether polled Docker exit predates sandbox start" - ); - return false; - } - }; - if !docker_polled_exit_is_stale(&previous_finished_at, inspected.state.as_ref()) { - return false; - } - - debug!( - sandbox_id = %sandbox.id, - container_id, - previous_finished_at, - "Ignoring Docker container exit snapshot from before the latest sandbox start" - ); - true - } - - async fn list_managed_container_summaries(&self) -> Result, Status> { - let filters = managed_container_label_filters(&self.config.sandbox_namespace, []); - self.docker - .list_containers(Some( - ListContainersOptionsBuilder::default() - .all(true) - .filters(&filters) - .build(), - )) - .await - .map_err(|err| internal_status("list Docker sandbox containers", err)) - } - - async fn find_managed_container_summary( - &self, - sandbox_id: &str, - sandbox_name: &str, - ) -> Result, Status> { - let mut label_filter_values = Vec::new(); - if !sandbox_id.is_empty() { - label_filter_values.push(format!("{LABEL_SANDBOX_ID}={sandbox_id}")); - } else if !sandbox_name.is_empty() { - label_filter_values.push(format!("{LABEL_SANDBOX_NAME}={sandbox_name}")); - } - - let filters = - managed_container_label_filters(&self.config.sandbox_namespace, label_filter_values); - let containers = self - .docker - .list_containers(Some( - ListContainersOptionsBuilder::default() - .all(true) - .filters(&filters) - .build(), - )) - .await - .map_err(|err| internal_status("find Docker sandbox container", err))?; - - let mut matches = containers.into_iter().filter(|summary| { - let Some(labels) = summary.labels.as_ref() else { - return false; - }; - let namespace_matches = labels - .get(LABEL_SANDBOX_NAMESPACE) - .is_some_and(|value| value == &self.config.sandbox_namespace); - let id_matches = sandbox_id.is_empty() - || labels - .get(LABEL_SANDBOX_ID) - .is_some_and(|value| value == sandbox_id); - let name_matches = sandbox_name.is_empty() - || labels - .get(LABEL_SANDBOX_NAME) - .is_some_and(|value| value == sandbox_name); - namespace_matches && id_matches && name_matches - }); - let selected = matches.next(); - if matches.next().is_some() { - return Err(Status::failed_precondition( - "multiple managed Docker workloads match the native identity", - )); - } - Ok(selected) - } - - async fn ensure_image_available( - &self, - sandbox_id: &str, - image: &str, - ) -> Result { - let inspect = match self.config.image_pull_policy { - ImagePullPolicy::IfNotPresent => { - if let Ok(inspect) = self.docker.inspect_image(image).await { - self.publish_docker_progress( - sandbox_id, - "ImagePresent", - format!("Docker image \"{image}\" is already present"), - HashMap::from([("image_ref".to_string(), image.to_string())]), - ); - inspect - } else { - self.pull_image(sandbox_id, image).await?; - self.docker - .inspect_image(image) - .await - .map_err(|err| internal_status("inspect Docker image after pull", err))? - } - } - ImagePullPolicy::Always => { - self.pull_image(sandbox_id, image).await?; - self.docker - .inspect_image(image) - .await - .map_err(|err| internal_status("inspect Docker image after pull", err))? - } - ImagePullPolicy::Never => match self.docker.inspect_image(image).await { - Ok(inspect) => { - self.publish_docker_progress( - sandbox_id, - "ImagePresent", - format!("Docker image \"{image}\" is already present"), - HashMap::from([("image_ref".to_string(), image.to_string())]), - ); - inspect - } - Err(err) if is_not_found_error(&err) => { - return Err(Status::failed_precondition(format!( - "docker image '{image}' is not present locally and image_pull_policy=Never" - ))); - } - Err(err) => return Err(internal_status("inspect Docker image", err)), - }, - ImagePullPolicy::Newer => { - return Err(Status::failed_precondition( - "docker image_pull_policy = \"newer\" is supported only by the Podman compute driver", - )); - } - }; - - let id = inspect.id.ok_or_else(|| { - Status::failed_precondition(format!( - "docker image '{image}' inspection did not return an immutable image ID" - )) - })?; - let (user, working_dir, volumes) = inspect.config.map_or_else( - || (String::new(), String::new(), Vec::new()), - |config| { - ( - config.user.unwrap_or_default(), - config.working_dir.unwrap_or_default(), - config.volumes.unwrap_or_default(), - ) - }, - ); - Ok(DockerImageMetadata { - id, - user, - working_dir, - volumes, - }) - } - - async fn pull_image(&self, sandbox_id: &str, image: &str) -> Result<(), Status> { - self.publish_docker_progress( - sandbox_id, - "Pulling", - format!("Pulling Docker image \"{image}\""), - HashMap::from([("image_ref".to_string(), image.to_string())]), - ); - let mut stream = self.docker.create_image( - Some(CreateImageOptions { - from_image: Some(normalize_pull_reference(image).into_owned()), - ..Default::default() - }), - None, - None, - ); - while let Some(result) = stream.next().await { - let info = result.map_err(|err| internal_status("pull Docker image", err))?; - if let Some(message) = info - .error_detail - .as_ref() - .and_then(|detail| detail.message.as_ref()) - { - return Err(Status::failed_precondition(format!( - "pull Docker image '{image}' failed: {message}" - ))); - } - if let Some(event) = docker_pull_progress_event(image, &info) { - self.publish_platform_event(sandbox_id.to_string(), event); - } - } - self.publish_docker_progress( - sandbox_id, - "Pulled", - format!("Pulled Docker image \"{image}\""), - HashMap::from([("image_ref".to_string(), image.to_string())]), - ); - Ok(()) - } -} - -// Standalone and in-process servers both use this wrapper. Delegating to the -// driver's canonical tonic implementation keeps request validation and Docker -// operation spans identical across both deployment modes. -fn validate_docker_outer_fence( - inspected: &bollard::models::ContainerInspectResponse, -) -> Result<(), Status> { - let network_mode = inspected - .host_config - .as_ref() - .and_then(|config| config.network_mode.as_deref()); - if network_mode != Some("none") { - return Err(Status::failed_precondition(format!( - "Docker sandbox outer fence requires network_mode=none, got {}", - network_mode.unwrap_or("") - ))); - } - let unexpected_networks = inspected - .network_settings - .as_ref() - .and_then(|settings| settings.networks.as_ref()) - .into_iter() - .flat_map(HashMap::keys) - .filter(|network| network.as_str() != "none") - .cloned() - .collect::>(); - if !unexpected_networks.is_empty() { - return Err(Status::failed_precondition(format!( - "Docker sandbox outer fence found attached networks: {}", - unexpected_networks.join(", ") - ))); - } - Ok(()) -} -#[tonic::async_trait] -impl ComputeDriver for ComputeDriverService { - type WatchSandboxesStream = WatchStream; - - async fn authenticate_sandbox( - &self, - request: Request, - ) -> Result, Status> - { - self.rpc_tracer - .trace( - openshell_otel::rpc::AUTHENTICATE_SANDBOX, - ComputeDriver::authenticate_sandbox(&self.driver, request), - ) - .await - } - - async fn get_capabilities( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::GET_CAPABILITIES, - ComputeDriver::get_capabilities(&self.driver, request), - ) - .await - } - - async fn validate_sandbox_create( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::VALIDATE_SANDBOX_CREATE, - ComputeDriver::validate_sandbox_create(&self.driver, request), - ) - .await - } - - async fn get_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::GET_SANDBOX, - ComputeDriver::get_sandbox(&self.driver, request), - ) - .await - } - - async fn list_sandboxes( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::LIST_SANDBOXES, - ComputeDriver::list_sandboxes(&self.driver, request), - ) - .await - } - - async fn create_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::CREATE_SANDBOX, - ComputeDriver::create_sandbox(&self.driver, request), - ) - .await - } - - async fn suspend_sandbox( - &self, - _request: Request, - ) -> Result, Status> { - Err(Status::unimplemented( - "the Docker compute driver does not support sandbox suspend", - )) - } - - async fn stop_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::STOP_SANDBOX, - ComputeDriver::stop_sandbox(&self.driver, request), - ) - .await - } - - async fn start_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::START_SANDBOX, - ComputeDriver::start_sandbox(&self.driver, request), - ) - .await - } - - async fn delete_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::DELETE_SANDBOX, - ComputeDriver::delete_sandbox(&self.driver, request), - ) - .await - } - - async fn watch_sandboxes( - &self, - request: Request, - ) -> Result, Status> { - let create_stream = async { - ComputeDriver::watch_sandboxes(&self.driver, request) - .await - .map(Response::into_inner) - }; - self.rpc_tracer - .trace_stream(openshell_otel::rpc::WATCH_SANDBOXES, create_stream) - .await - .map(Response::new) - } - - async fn ensure_workspace( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::ENSURE_WORKSPACE, - ComputeDriver::ensure_workspace(&self.driver, request), - ) - .await - } - - async fn delete_workspace( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace( - openshell_otel::rpc::DELETE_WORKSPACE, - ComputeDriver::delete_workspace(&self.driver, request), - ) - .await - } -} - -#[tonic::async_trait] -impl openshell_core::compute::ComputeDriver for DockerComputeDriver { - async fn update_sandbox_configuration( - &self, - request: Request, - ) -> Result< - Response, - Status, - > { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let result = Box::pin(self.update_workload_image(&request.into_inner())).await; - span_status.finish(result.map(|()| { - Response::new(openshell_core::proto::compute::v1::UpdateSandboxConfigurationResponse {}) - })) - } -} - -#[tonic::async_trait] -impl openshell_core::compute::ComputeDriver for ComputeDriverService { - async fn update_sandbox_configuration( - &self, - request: Request, - ) -> Result< - Response, - Status, - > { - self.rpc_tracer - .trace( - openshell_otel::rpc::UPDATE_SANDBOX_CONFIGURATION, - openshell_core::compute::ComputeDriver::update_sandbox_configuration( - &self.driver, - request, - ), - ) - .await - } -} - -#[tonic::async_trait] -impl openshell_core::proto::compute::v1::compute_driver_configuration_updates_server::ComputeDriverConfigurationUpdates for ComputeDriverService { - async fn update_sandbox_configuration( - &self, request: Request, - ) -> Result, Status> { - openshell_core::compute::ComputeDriver::update_sandbox_configuration(self, request).await - } -} - -#[tonic::async_trait] -impl ComputeDriver for DockerComputeDriver { - async fn authenticate_sandbox( - &self, - _request: Request, - ) -> Result, Status> - { - Err(Status::unimplemented( - "docker does not authenticate sandbox credentials", - )) - } - - type WatchSandboxesStream = WatchStream; - - async fn get_capabilities( - &self, - request: Request, - ) -> Result, Status> { - let capabilities = self.capabilities(); - openshell_core::extension_protocol::validate_gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - "docker", - capabilities.extension.as_ref(), - request.into_inner().gateway, - ) - .map_err(|error| Status::failed_precondition(error.to_string()))?; - Ok(Response::new(capabilities)) - } - - async fn validate_sandbox_create( - &self, - request: Request, - ) -> Result, Status> { - let sandbox = request - .into_inner() - .sandbox - .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; - let validated = Self::validated_sandbox(&sandbox, &self.config)?; - self.validate_user_volume_mounts_available(&validated.driver_config, &sandbox.workspace) - .await?; - let _ = self - .resolve_gpu_cdi_devices( - validated.gpu_requirements, - &validated.driver_config, - CdiGpuDefaultSelector::peek_device_ids, - ) - .await?; - Ok(Response::new(ValidateSandboxCreateResponse {})) - } - - async fn get_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let request = request.into_inner(); - require_sandbox_identifier(&request.sandbox_id, &request.name)?; - - let sandbox = self - .get_sandbox_snapshot(&request.sandbox_id, &request.name) - .await? - .ok_or_else(|| Status::not_found("sandbox not found"))?; - - if !request.sandbox_id.is_empty() && request.sandbox_id != sandbox.id { - return Err(Status::failed_precondition( - "sandbox_id did not match the fetched sandbox", - )); - } - - Ok(Response::new(GetSandboxResponse { - sandbox: Some(sandbox), - })) - } - - async fn list_sandboxes( - &self, - _request: Request, - ) -> Result, Status> { - Ok(Response::new(ListSandboxesResponse { - sandboxes: self.current_snapshots().await?, - })) - } - - #[tracing::instrument( - name = "docker.schedule_sandbox", - skip(self, request), - fields( - otel.name = "docker.schedule_sandbox", - otel.status_code = tracing::field::Empty, - sandbox.id = %request.get_ref().sandbox.as_ref().map_or("", |sandbox| sandbox.id.as_str()), - sandbox.name = %request.get_ref().sandbox.as_ref().map_or("", |sandbox| sandbox.name.as_str()), - ) - )] - async fn create_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let sandbox = request - .into_inner() - .sandbox - .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; - self.create_sandbox_inner(&sandbox).await?; - span_status.finish(Ok(Response::new(CreateSandboxResponse::default()))) - } - - async fn suspend_sandbox( - &self, - _request: Request, - ) -> Result, Status> { - Err(Status::unimplemented( - "the Docker compute driver does not support sandbox suspend", - )) - } - - #[tracing::instrument( - name = "docker.stop_sandbox", - skip(self, request), - fields( - otel.name = "docker.stop_sandbox", - otel.status_code = tracing::field::Empty, - sandbox.id = %request.get_ref().sandbox_id, - sandbox.name = %request.get_ref().name, - ) - )] - async fn stop_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let mut request = request.into_inner(); - require_sandbox_identifier(&request.sandbox_id, &request.name)?; - - let Some(id) = self - .resolve_lifecycle_id(&request.sandbox_id, &request.name) - .await? - else { - return Err(Status::not_found("sandbox not found")); - }; - request.sandbox_id = id; - let _lifecycle = self - .image_update_gates - .gate_for(&request.sandbox_id) - .lock_owned() - .await; - self.lifecycle_event_fences - .request_stop(&request.sandbox_id, &request.name); - if let Err(error) = self - .stop_sandbox_inner(&request.sandbox_id, &request.name) - .await - { - self.lifecycle_event_fences - .clear_stop(&request.sandbox_id, &request.name); - return Err(error); - } - if let Err(error) = self - .publish_container_snapshot(&request.sandbox_id, &request.name) - .await - { - self.lifecycle_event_fences - .clear_stop(&request.sandbox_id, &request.name); - return Err(error); - } - span_status.finish(Ok(Response::new(StopSandboxResponse {}))) - } - - async fn start_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let request = request.into_inner(); - if !Box::pin(Self::start_sandbox( - self, - &request.sandbox_id, - &request.name, - &request.generation_id, - &request.launch_authentication, - request.sandbox.as_ref(), - )) - .await? - { - return Err(Status::not_found("sandbox not found")); - } - self.publish_container_snapshot(&request.sandbox_id, &request.name) - .await?; - Ok(Response::new(StartSandboxResponse::default())) - } - - #[tracing::instrument( - name = "docker.delete_sandbox", - skip(self, request), - fields( - otel.name = "docker.delete_sandbox", - otel.status_code = tracing::field::Empty, - sandbox.id = %request.get_ref().sandbox_id, - sandbox.name = %request.get_ref().name, - ) - )] - async fn delete_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let mut request = request.into_inner(); - require_sandbox_identifier(&request.sandbox_id, &request.name)?; - - let Some(id) = self - .resolve_lifecycle_id(&request.sandbox_id, &request.name) - .await? - else { - return Ok(Response::new(DeleteSandboxResponse { deleted: false })); - }; - request.sandbox_id = id; - let _lifecycle = self - .image_update_gates - .gate_for(&request.sandbox_id) - .lock_owned() - .await; - let event_sandbox_id = request.sandbox_id.clone(); - let deleted = self - .delete_sandbox_inner(&request.sandbox_id, &request.name) - .await?; - self.lifecycle_event_fences - .remove(&event_sandbox_id, &request.name); - if deleted && !event_sandbox_id.is_empty() { - let _ = self.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Deleted( - WatchSandboxesDeletedEvent { - sandbox_id: event_sandbox_id, - }, - )), - }); - } - - span_status.finish(Ok(Response::new(DeleteSandboxResponse { deleted }))) - } - - async fn watch_sandboxes( - &self, - _request: Request, - ) -> Result, Status> { - // Subscribe before taking the initial snapshot so any event emitted - // between the snapshot and this subscriber becoming active is still - // delivered. Downstream consumers treat sandbox events as - // idempotent (keyed by sandbox id), so a duplicate event is benign - // while a missed one leaks state. - let mut rx = self.events.subscribe(); - let initial = self.current_snapshots().await?; - let (tx, out_rx) = mpsc::channel(WATCH_BUFFER); - tokio::spawn(async move { - for sandbox in initial { - if tx - .send(Ok(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Sandbox( - WatchSandboxesSandboxEvent { - sandbox: Some(sandbox), - }, - )), - })) - .await - .is_err() - { - return; - } - } - - loop { - match rx.recv().await { - Ok(event) => { - if tx.send(Ok(event)).await.is_err() { - return; - } - } - Err(broadcast::error::RecvError::Lagged(_)) => {} - Err(broadcast::error::RecvError::Closed) => return, - } - } - }); - - Ok(Response::new(Box::pin(ReceiverStream::new(out_rx)))) - } - - async fn ensure_workspace( - &self, - _request: Request, - ) -> Result, Status> { - Ok(Response::new(EnsureWorkspaceResponse {})) - } - - async fn delete_workspace( - &self, - _request: Request, - ) -> Result, Status> { - Ok(Response::new(DeleteWorkspaceResponse {})) - } -} - -impl DockerProvisioningFailure { - fn new(reason: &'static str, message: impl Into) -> Self { - Self { - reason, - message: message.into(), - } - } - - fn from_status(reason: &'static str, status: Status) -> Self { - Self::new(reason, status.message()) - } - - fn from_admission_status(status: Status) -> Self { - let reason = if status.code() == tonic::Code::FailedPrecondition { - "ResourceAdmissionDenied" - } else { - "ResourceAdmissionLookupFailed" - }; - Self::from_status(reason, status) - } -} - -fn sandbox_image(sandbox: &DriverSandbox) -> Option { - sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - .map(|template| template.image.clone()) - .filter(|image| !image.trim().is_empty()) -} - -fn pending_sandbox_snapshot( - sandbox: &DriverSandbox, - namespace: &str, - condition: DriverCondition, - deleting: bool, -) -> DriverSandbox { - DriverSandbox { - id: sandbox.id.clone(), - name: sandbox.name.clone(), - namespace: namespace.to_string(), - spec: None, - status: Some(DriverSandboxStatus { - name: sandbox.name.clone(), - instance_id: String::new(), - agent_fd: String::new(), - sandbox_fd: String::new(), - conditions: vec![condition], - deleting, - ..Default::default() - }), - workspace: sandbox.workspace.clone(), - } -} - -fn pending_sandbox_record_id( - pending: &HashMap, - sandbox_id: &str, - sandbox_name: &str, -) -> Result, Status> { - if !sandbox_id.is_empty() { - return Ok(pending - .get(sandbox_id) - .map(|record| record.sandbox.id.clone())); - } - - let mut matches = pending - .values() - .filter(|record| !sandbox_name.is_empty() && record.sandbox.name == sandbox_name) - .map(|record| record.sandbox.id.clone()); - let first = matches.next(); - if first.is_some() && matches.next().is_some() { - return Err(Status::failed_precondition(format!( - "multiple pending Docker sandboxes are named '{sandbox_name}'; use sandbox_id" - ))); - } - Ok(first) -} - -fn provisioning_condition() -> DriverCondition { - DriverCondition { - r#type: "Ready".to_string(), - status: "False".to_string(), - reason: "Starting".to_string(), - message: "Docker container is starting".to_string(), - transition_time: None, - } -} - -fn error_condition(reason: &str, message: &str) -> DriverCondition { - DriverCondition { - r#type: "Ready".to_string(), - status: "False".to_string(), - reason: reason.to_string(), - message: message.to_string(), - transition_time: None, - } -} - -fn set_sandbox_ready_condition(sandbox: &mut DriverSandbox, condition: DriverCondition) { - let Some(status) = sandbox.status.as_mut() else { - return; - }; - if let Some(existing) = status - .conditions - .iter_mut() - .find(|existing| existing.r#type == "Ready") - { - *existing = condition; - } else { - status.conditions.push(condition); - } -} - -fn platform_event( - source: &str, - event_type: &str, - reason: &str, - message: String, -) -> DriverPlatformEvent { - DriverPlatformEvent { - event_time: openshell_core::time::timestamp_from_millis(openshell_core::time::now_ms()) - .ok(), - source: source.to_string(), - r#type: event_type.to_string(), - reason: reason.to_string(), - message, - metadata: HashMap::new(), - } -} - -fn docker_pull_progress_event(image: &str, info: &CreateImageInfo) -> Option { - let status = info.status.as_deref().map(str::trim)?; - if status.is_empty() { - return None; - } - - let mut metadata = HashMap::from([ - ("image_ref".to_string(), image.to_string()), - ("docker_status".to_string(), status.to_string()), - ]); - if let Some(layer_id) = info.id.as_deref().filter(|id| !id.is_empty()) { - metadata.insert("layer_id".to_string(), layer_id.to_string()); - } - if let Some(detail) = docker_pull_progress_detail(info) { - metadata.insert("detail".to_string(), detail); - } - attach_docker_progress_metadata(&mut metadata, "PullingLayer", status); - - Some(DriverPlatformEvent { - event_time: openshell_core::time::timestamp_from_millis(openshell_core::time::now_ms()) - .ok(), - source: "docker".to_string(), - r#type: "Normal".to_string(), - reason: "PullingLayer".to_string(), - message: docker_pull_message(info, status), - metadata, - }) -} - -fn docker_pull_message(info: &CreateImageInfo, status: &str) -> String { - info.id.as_deref().filter(|id| !id.is_empty()).map_or_else( - || format!("Docker image pull: {status}"), - |layer_id| format!("Docker image pull {layer_id}: {status}"), - ) -} - -fn docker_pull_progress_detail(info: &CreateImageInfo) -> Option { - let status = info.status.as_deref().unwrap_or("Pulling"); - let layer_id = info.id.as_deref().filter(|id| !id.is_empty()); - let progress = info - .progress_detail - .as_ref() - .and_then(format_progress_detail); - - match (layer_id, progress) { - (Some(layer_id), Some(progress)) => Some(format!("{status} {layer_id} ({progress})")), - (Some(layer_id), None) => Some(format!("{status} {layer_id}")), - (None, Some(progress)) => Some(format!("{status} ({progress})")), - (None, None) => (!status.is_empty()).then(|| status.to_string()), - } -} - -fn format_progress_detail(progress: &ProgressDetail) -> Option { - let current = progress.current.and_then(|value| u64::try_from(value).ok()); - let total = progress - .total - .and_then(|value| u64::try_from(value).ok()) - .filter(|value| *value > 0); - - match (current, total) { - (Some(current), Some(total)) => { - Some(format!("{}/{}", format_bytes(current), format_bytes(total))) - } - (Some(current), _) if current > 0 => Some(format_bytes(current)), - _ => None, - } -} - -fn attach_docker_progress_metadata( - metadata: &mut HashMap, - reason: &str, - message: &str, -) { - match reason { - "Scheduled" => { - mark_progress_complete( - metadata, - PROGRESS_STEP_REQUESTING_SANDBOX, - "Sandbox allocated", - ); - mark_progress_active(metadata, PROGRESS_STEP_PULLING_IMAGE); - if let Some(image) = metadata.get("image_ref").cloned() { - mark_progress_detail(metadata, image); - } - } - "Pulling" => { - mark_progress_active(metadata, PROGRESS_STEP_PULLING_IMAGE); - if let Some(image) = metadata.get("image_ref").cloned() { - mark_progress_detail(metadata, image); - } - } - "PullingLayer" => { - mark_progress_active(metadata, PROGRESS_STEP_PULLING_IMAGE); - if let Some(detail) = metadata - .get("detail") - .cloned() - .filter(|detail| !detail.is_empty()) - { - mark_progress_detail(metadata, detail); - } else if !message.is_empty() { - mark_progress_detail(metadata, message); - } - } - "ImagePresent" => { - mark_progress_complete( - metadata, - PROGRESS_STEP_PULLING_IMAGE, - "Image already present", - ); - mark_progress_active(metadata, PROGRESS_STEP_STARTING_SANDBOX); - } - "Pulled" => { - mark_progress_complete(metadata, PROGRESS_STEP_PULLING_IMAGE, "Image pulled"); - mark_progress_active(metadata, PROGRESS_STEP_STARTING_SANDBOX); - } - "Created" => { - mark_progress_active(metadata, PROGRESS_STEP_STARTING_SANDBOX); - mark_progress_detail(metadata, "Container created"); - } - "Started" => { - mark_progress_active(metadata, PROGRESS_STEP_STARTING_SANDBOX); - mark_progress_detail(metadata, "Waiting for supervisor relay"); - } - _ => {} - } -} - -#[cfg(test)] -fn docker_driver_config( - template: &DriverSandboxTemplate, - enable_bind_mounts: bool, -) -> Result { - let config = - DockerSandboxDriverConfig::from_template(template).map_err(Status::invalid_argument)?; - validate_docker_driver_mounts(&config.mounts, enable_bind_mounts)?; - Ok(config) -} - -/// Collect user-supplied bind mounts as string-format binds. -/// -/// Bind mounts use the legacy `Binds` field (`-v` syntax) rather than the -/// structured `Mount` API because the Docker Engine Mount object does not -/// support `SELinux` relabelling (`:z` / `:Z`). The string format does. -fn docker_driver_bind_strings(config: &DockerSandboxDriverConfig) -> Result, Status> { - config - .mounts - .iter() - .filter_map(|m| match m { - DockerDriverMountConfig::Bind { - source, - target, - read_only, - selinux_label, - } => Some(docker_bind_string( - source, - target, - *read_only, - *selinux_label, - )), - _ => None, - }) - .collect() -} - -fn docker_bind_string( - source: &str, - target: &str, - read_only: bool, - selinux_label: Option, -) -> Result { - driver_mounts::validate_absolute_mount_source(source, "bind source") - .map_err(Status::failed_precondition)?; - // Legacy `-v` binds silently create missing source directories as empty, - // root-owned paths. The structured `--mount` API that was used before this - // change rejected missing sources at container-create time. Preserve that - // fail-fast behaviour with an explicit existence check. - if !Path::new(source).exists() { - return Err(Status::failed_precondition(format!( - "bind source path does not exist: {source}" - ))); - } - driver_mounts::validate_container_mount_target(target).map_err(Status::failed_precondition)?; - let normalized_target = driver_mounts::normalize_mount_target(target); - - let mut opts = Vec::new(); - if read_only { - opts.push("ro"); - } - match selinux_label { - Some(SelinuxLabel::Shared) => opts.push("z"), - Some(SelinuxLabel::Private) => opts.push("Z"), - None => {} - } - - if opts.is_empty() { - Ok(format!("{source}:{normalized_target}")) - } else { - Ok(format!("{source}:{normalized_target}:{}", opts.join(","))) - } -} - -/// Collect user-supplied non-bind mounts as structured `Mount` objects. -fn docker_driver_mounts(config: &DockerSandboxDriverConfig) -> Result, Status> { - config - .mounts - .iter() - .filter_map(|m| docker_mount_from_config(m).transpose()) - .collect() -} - -fn docker_mount_from_config(config: &DockerDriverMountConfig) -> Result, Status> { - match config { - DockerDriverMountConfig::Bind { .. } => { - // Bind mounts are handled via docker_driver_bind_strings. - Ok(None) - } - DockerDriverMountConfig::Volume { - source, - target, - read_only, - subpath, - } => Ok(Some(Mount { - typ: Some(MountTypeEnum::VOLUME), - source: Some(source.clone()), - target: Some(target.clone()), - read_only: Some(*read_only), - volume_options: subpath.as_ref().map(|subpath| MountVolumeOptions { - subpath: Some(subpath.clone()), - ..Default::default() - }), - ..Default::default() - })), - DockerDriverMountConfig::Tmpfs { - target, - options, - size_bytes, - mode, - } => Ok(Some(Mount { - typ: Some(MountTypeEnum::TMPFS), - target: Some(target.clone()), - tmpfs_options: Some(MountTmpfsOptions { - size_bytes: validate_optional_positive_integral_i64( - *size_bytes, - "tmpfs size_bytes", - )?, - mode: validate_optional_nonnegative_integral_i64(*mode, "tmpfs mode")?, - options: (!options.is_empty()) - .then(|| { - options - .iter() - .map(|option| docker_tmpfs_option(option)) - .collect::, _>>() - }) - .transpose()?, - }), - ..Default::default() - })), - DockerDriverMountConfig::Image { .. } => Err(Status::failed_precondition( - "invalid docker driver_config: docker image mounts are not supported", - )), - } -} - -fn validate_docker_driver_mounts( - mounts: &[DockerDriverMountConfig], - enable_bind_mounts: bool, -) -> Result<(), Status> { - let mut targets = HashSet::new(); - for mount in mounts { - let target = match mount { - DockerDriverMountConfig::Bind { source, target, .. } => { - if !enable_bind_mounts { - return Err(Status::failed_precondition( - "docker bind mounts require enable_bind_mounts = true in [openshell.drivers.docker]", - )); - } - driver_mounts::validate_absolute_mount_source(source, "bind source") - .map_err(Status::failed_precondition)?; - target - } - DockerDriverMountConfig::Volume { - source, - target, - subpath, - .. - } => { - driver_mounts::validate_mount_source(source, "volume source") - .map_err(Status::failed_precondition)?; - if let Some(subpath) = subpath { - driver_mounts::validate_mount_subpath(subpath) - .map_err(Status::failed_precondition)?; - } - target - } - DockerDriverMountConfig::Tmpfs { - target, - options, - size_bytes, - mode, - } => { - validate_optional_positive_integral_i64(*size_bytes, "tmpfs size_bytes")?; - validate_optional_nonnegative_integral_i64(*mode, "tmpfs mode")?; - for option in options { - docker_tmpfs_option(option)?; - } - target - } - DockerDriverMountConfig::Image { - source, - target, - read_only, - subpath, - } => { - let _ = (source, target, read_only, subpath); - return Err(Status::failed_precondition( - "invalid docker driver_config: docker image mounts are not supported", - )); - } - }; - driver_mounts::validate_container_mount_target(target) - .map_err(Status::failed_precondition)?; - let normalized_target = driver_mounts::normalize_mount_target(target); - if !targets.insert(normalized_target.clone()) { - return Err(Status::failed_precondition(format!( - "duplicate docker driver_config mount target '{normalized_target}'" - ))); - } - } - Ok(()) -} - -fn validate_optional_positive_integral_i64( - value: Option, - field: &str, -) -> Result, Status> { - let Some(value) = validate_optional_integral_i64(value, field)? else { - return Ok(None); - }; - if value <= 0 { - return Err(Status::failed_precondition(format!( - "{field} must be positive" - ))); - } - Ok(Some(value)) -} - -fn validate_optional_nonnegative_integral_i64( - value: Option, - field: &str, -) -> Result, Status> { - let Some(value) = validate_optional_integral_i64(value, field)? else { - return Ok(None); - }; - if value < 0 { - return Err(Status::failed_precondition(format!( - "{field} must be zero or greater" - ))); - } - Ok(Some(value)) -} - -fn validate_optional_integral_i64(value: Option, field: &str) -> Result, Status> { - let Some(value) = value else { - return Ok(None); - }; - if !value.is_finite() || value.fract() != 0.0 { - return Err(Status::failed_precondition(format!( - "{field} must be an integer" - ))); - } - value.to_string().parse::().map(Some).map_err(|_| { - Status::failed_precondition(format!("{field} must be representable as an i64")) - }) -} - -fn docker_tmpfs_option(option: &str) -> Result, Status> { - let option = option.trim(); - if option.is_empty() { - return Err(Status::failed_precondition( - "tmpfs options must not contain empty values", - )); - } - if let Some((key, value)) = option.split_once('=') { - let key = key.trim(); - let value = value.trim(); - if key.is_empty() || value.is_empty() { - return Err(Status::failed_precondition( - "tmpfs key=value options must include both key and value", - )); - } - Ok(vec![key.to_string(), value.to_string()]) - } else { - Ok(vec![option.to_string()]) - } -} - -fn docker_volume_identity(volume: &bollard::models::Volume) -> serde_json::Value { - serde_json::json!({"name": volume.name, "driver": volume.driver, "options": volume.options, - "created_at": volume.created_at, "mountpoint": volume.mountpoint}) -} - -fn docker_volume_is_bind_backed(volume: &bollard::models::Volume) -> bool { - volume.driver == "local" - && volume.options.get("o").is_some_and(|options| { - options.split(',').any(|option| { - let option = option.trim(); - option.eq_ignore_ascii_case("bind") || option.eq_ignore_ascii_case("rbind") - }) - }) -} - -fn build_binds(_sandbox: &DriverSandbox, _config: &DockerDriverRuntimeConfig) -> Vec { - Vec::new() -} - -fn docker_boundary_state_dir( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> Result { - docker_boundary_state_dir_by_id(&sandbox.id, config) -} - -fn docker_boundary_state_dir_by_id( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result { - sandbox_token_host_path_by_id(sandbox_id, config).and_then(|path| { - path.parent() - .map(Path::to_path_buf) - .ok_or_else(|| Status::internal("docker boundary state path has no parent")) - }) -} - -fn docker_channel_volume_name( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> String { - docker_channel_volume_name_by_id(&sandbox.id, config) -} - -fn docker_channel_volume_name_by_id( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> String { - let mut hasher = Sha256::new(); - hasher.update(config.sandbox_namespace.as_bytes()); - hasher.update([0]); - hasher.update(sandbox_id.as_bytes()); - let digest = format!("{:x}", hasher.finalize()); - format!("openshell-channel-{}", &digest[..32]) -} - -fn docker_supervisor_volume_name( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> String { - docker_supervisor_volume_name_by_id(&sandbox.id, config) -} - -fn docker_supervisor_volume_name_by_id( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> String { - let mut hasher = Sha256::new(); - hasher.update(config.sandbox_namespace.as_bytes()); - hasher.update([0]); - hasher.update(sandbox_id.as_bytes()); - let digest = format!("{:x}", hasher.finalize()); - format!("openshell-supervisor-{}", &digest[..32]) -} - -fn docker_control_volume_name_by_id( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> String { - docker_channel_volume_name_by_id(sandbox_id, config).replacen( - "openshell-channel-", - "openshell-control-", - 1, - ) -} - -async fn create_docker_channel_volume( - docker: &Docker, - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - create: bool, -) -> Result<(), Status> { - let names = [ - docker_channel_volume_name(sandbox, config), - docker_supervisor_volume_name(sandbox, config), - docker_control_volume_name_by_id(&sandbox.id, config), - ]; - for (index, name) in names.iter().enumerate() { - if let Err(error) = - create_docker_runtime_volume(docker, sandbox, config, name.clone(), create).await - { - for created in &names[..index] { - let _ = remove_docker_volume(docker, created).await; - } - return Err(error); - } - } - Ok(()) -} - -async fn create_docker_runtime_volume( - docker: &Docker, - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - name: String, - create: bool, -) -> Result<(), Status> { - let expected_labels = HashMap::from([ - ( - LABEL_MANAGED_BY.to_string(), - LABEL_MANAGED_BY_VALUE.to_string(), - ), - (LABEL_SANDBOX_ID.to_string(), sandbox.id.clone()), - ( - LABEL_SANDBOX_NAMESPACE.to_string(), - config.sandbox_namespace.clone(), - ), - ( - LABEL_ISOLATION_BACKEND.to_string(), - LABEL_ISOLATION_BACKEND_OPEN_SHELL.to_string(), - ), - ]); - if create { - docker - .create_volume(VolumeCreateRequest { - name: Some(name.clone()), - labels: Some(expected_labels.clone()), - ..Default::default() - }) - .await - .map_err(|error| { - Status::internal(format!("create Docker sandbox runtime volume: {error}")) - })?; - } - let volume = docker.inspect_volume(&name).await.map_err(|error| { - Status::internal(format!("inspect Docker sandbox channel volume: {error}")) - })?; - if volume.driver != "local" - || !volume.options.is_empty() - || expected_labels - .iter() - .any(|(key, value)| volume.labels.get(key) != Some(value)) - { - return Err(Status::failed_precondition(format!( - "Docker sandbox runtime volume '{name}' already exists without the expected local-driver ownership labels" - ))); - } - Ok(()) -} - -async fn remove_docker_owned_storage_by_id( - docker: &Docker, - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result<(), Status> { - workspace::remove(docker, sandbox_id, config).await?; - remove_docker_channel_volume_by_id(docker, sandbox_id, config).await -} - -async fn remove_docker_channel_volume_by_id( - docker: &Docker, - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result<(), Status> { - remove_docker_volume( - docker, - &docker_channel_volume_name_by_id(sandbox_id, config), - ) - .await?; - remove_docker_volume( - docker, - &docker_supervisor_volume_name_by_id(sandbox_id, config), - ) - .await?; - remove_docker_volume( - docker, - &docker_control_volume_name_by_id(sandbox_id, config), - ) - .await -} - -async fn remove_docker_volume(docker: &Docker, name: &str) -> Result<(), Status> { - docker - .remove_volume(name, None::) - .await - .or_else(|error| { - if is_not_found_error(&error) { - Ok(()) - } else { - Err(error) - } - }) - .map_err(|error| Status::internal(format!("remove Docker sandbox runtime volume: {error}"))) -} - -fn sandbox_token_host_path( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> Result { - sandbox_token_host_path_by_id(&sandbox.id, config) -} - -fn sandbox_token_host_path_by_id( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result { - openshell_core::driver_utils::sandbox_token_path( - "docker-sandbox-tokens", - Some(&config.sandbox_namespace), - sandbox_id, - ) - .map_err(|err| { - Status::internal(format!( - "resolve sandbox token state directory failed: {err}" - )) - }) -} - -async fn write_sandbox_token_file( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> Result { - let Some(spec) = sandbox.spec.as_ref() else { - return Ok(false); - }; - let path = sandbox_token_host_path(sandbox, config)?; - if spec.sandbox_token.is_empty() { - // Restart reconciliation receives a durable public Sandbox, which - // intentionally excludes the bearer token. Its existing private token - // file remains the source of truth while the stopped workload is held - // as rollback state. - return Ok(path.is_file()); - } - if let Some(parent) = path.parent() { - openshell_core::paths::create_dir_restricted(parent).map_err(|err| { - Status::internal(format!( - "create sandbox token directory {} failed: {err}", - parent.display() - )) - })?; - } - tokio::fs::write(&path, format!("{}\n", spec.sandbox_token)) - .await - .map_err(|err| { - Status::internal(format!( - "write sandbox token file {} failed: {err}", - path.display() - )) - })?; - openshell_core::paths::set_file_owner_only(&path).map_err(|err| { - Status::internal(format!( - "restrict sandbox token file {} failed: {err}", - path.display() - )) - })?; - Ok(true) -} - -fn prepare_docker_boundary_state_dir( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> Result { - let directory = docker_boundary_state_dir(sandbox, config)?; - openshell_core::paths::create_dir_restricted(&directory).map_err(|error| { - Status::internal(format!( - "create Docker boundary state directory {}: {error}", - directory.display() - )) - })?; - Ok(directory) -} - -async fn write_docker_boundary_file(path: &Path, contents: &[u8]) -> Result<(), Status> { - tokio::fs::write(path, contents).await.map_err(|error| { - Status::internal(format!( - "write Docker boundary file {}: {error}", - path.display() - )) - })?; - openshell_core::paths::set_file_owner_only(path).map_err(|error| { - Status::internal(format!( - "restrict Docker boundary file {}: {error}", - path.display() - )) - }) -} - -async fn adopt_or_verify_docker_start_generation( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, - requested: &openshell_core::sandbox_generation::SandboxGenerationId, -) -> Result<(), Status> { - let path = docker_boundary_state_dir_by_id(sandbox_id, config)?.join(START_GENERATION_FILE); - adopt_or_verify_docker_start_generation_path(&path, requested).await -} - -async fn adopt_or_verify_docker_start_generation_path( - path: &Path, - requested: &openshell_core::sandbox_generation::SandboxGenerationId, -) -> Result<(), Status> { - let active = match tokio::fs::read_to_string(&path).await { - Ok(active) => active, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - let mut marker = match tokio::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) - .await - { - Ok(marker) => marker, - Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { - let active = tokio::fs::read_to_string(&path).await.map_err(|error| { - Status::failed_precondition(format!( - "read concurrently adopted Docker sandbox generation {}: {error}", - path.display() - )) - })?; - return verify_docker_start_generation_value(&active, requested); - } - Err(error) => { - return Err(Status::failed_precondition(format!( - "adopt active Docker sandbox generation {}: {error}", - path.display() - ))); - } - }; - marker - .write_all(requested.as_str().as_bytes()) - .await - .map_err(|error| { - Status::internal(format!( - "write adopted Docker sandbox generation {}: {error}", - path.display() - )) - })?; - marker.flush().await.map_err(|error| { - Status::internal(format!( - "flush adopted Docker sandbox generation {}: {error}", - path.display() - )) - })?; - openshell_core::paths::set_file_owner_only(path).map_err(|error| { - Status::internal(format!( - "restrict adopted Docker sandbox generation {}: {error}", - path.display() - )) - })?; - return Ok(()); - } - Err(error) => { - return Err(Status::failed_precondition(format!( - "read active Docker sandbox generation {}: {error}", - path.display() - ))); - } - }; - verify_docker_start_generation_value(&active, requested) -} - -fn verify_docker_start_generation_value( - active: &str, - requested: &openshell_core::sandbox_generation::SandboxGenerationId, -) -> Result<(), Status> { - if active.trim() == requested.as_str() { - return Ok(()); - } - Err(Status::failed_precondition(format!( - "Docker sandbox is already running generation {}", - active.trim() - ))) -} - -fn append_docker_archive_directory( - archive: &mut tar::Builder>, - path: &str, - mode: u32, - uid: u32, - gid: u32, -) -> Result<(), Status> { - let mut header = tar::Header::new_gnu(); - header.set_entry_type(tar::EntryType::Directory); - header.set_mode(mode); - header.set_uid(u64::from(uid)); - header.set_gid(u64::from(gid)); - header.set_mtime(0); - header.set_size(0); - header.set_cksum(); - archive - .append_data(&mut header, path, std::io::empty()) - .map_err(|error| Status::internal(format!("build Docker sandbox archive: {error}"))) -} - -fn append_docker_archive_file( - archive: &mut tar::Builder>, - path: &str, - mode: u32, - uid: u32, - gid: u32, - contents: &[u8], -) -> Result<(), Status> { - let mut header = tar::Header::new_gnu(); - header.set_entry_type(tar::EntryType::Regular); - header.set_mode(mode); - header.set_uid(u64::from(uid)); - header.set_gid(u64::from(gid)); - header.set_mtime(0); - header.set_size(contents.len() as u64); - header.set_cksum(); - archive - .append_data(&mut header, path, contents) - .map_err(|error| Status::internal(format!("build Docker sandbox archive: {error}"))) -} - -#[derive(Clone, Copy)] -struct DockerSandboxTls<'a> { - certificate: &'a [u8], - private_key: &'a [u8], -} - -fn docker_sandbox_bundle_archive( - sandbox_binary: &[u8], - boundary_config: &[u8], - boundary_tls: DockerSandboxTls<'_>, - identity: &ResolvedWorkloadIdentity, - workspace_root: &str, -) -> Result, Status> { - let mut archive = tar::Builder::new(Vec::new()); - append_docker_archive_directory(&mut archive, ".openshell", 0o755, 0, 0)?; - append_docker_archive_directory(&mut archive, ".openshell/runtime", 0o555, 0, 0)?; - append_docker_archive_directory(&mut archive, ".openshell/channel", 0o755, 0, 0)?; - append_docker_archive_directory( - &mut archive, - ".openshell/channel/sandbox", - // The sandbox owns this directory so it can consume bootstrap files - // and create the control socket. The separate non-root supervisor - // needs execute-only traversal to that known socket path; mutual TLS - // authenticates the endpoint and the files beneath remain 0600. - 0o711, - identity.uid, - identity.gid, - )?; - // The control volume is read-only in the runtime container; the - // supervisor stager initializes it. - append_docker_archive_file( - &mut archive, - ".openshell/runtime/openshell-sandbox", - 0o555, - 0, - 0, - sandbox_binary, - )?; - append_docker_archive_file( - &mut archive, - ".openshell/channel/sandbox/bootstrap.json", - 0o600, - identity.uid, - identity.gid, - boundary_config, - )?; - for (path, contents) in [ - ( - ".openshell/channel/sandbox/server.crt", - boundary_tls.certificate, - ), - ( - ".openshell/channel/sandbox/server.key", - boundary_tls.private_key, - ), - ] { - append_docker_archive_file( - &mut archive, - path, - 0o600, - identity.uid, - identity.gid, - contents, - )?; - } - if workspace_root == driver_mounts::DEFAULT_WORKSPACE_ROOT { - // The default workspace is driver-managed. Create it before the - // capability-free sandbox starts because that process deliberately - // has no authority to create or chown a directory beneath `/`. - append_docker_archive_directory( - &mut archive, - workspace_root.trim_start_matches('/'), - 0o700, - identity.uid, - identity.gid, - )?; - } - archive - .into_inner() - .map_err(|error| Status::internal(format!("finish Docker sandbox archive: {error}"))) -} - -async fn stage_docker_sandbox_bundle( - docker: &Docker, - container_id: &str, - config: &DockerDriverRuntimeConfig, - identity: &ResolvedWorkloadIdentity, - boundary_config: &[u8], - boundary_tls: DockerSandboxTls<'_>, - workspace_root: &str, -) -> Result<(), Status> { - let archive = docker_sandbox_bundle_archive( - config.sandbox_binary.as_slice(), - boundary_config, - boundary_tls, - identity, - workspace_root, - )?; - let options = UploadToContainerOptionsBuilder::default() - .path("/") - .copy_uidgid("true") - .build(); - docker - .upload_to_container( - container_id, - Some(options), - bollard::body_full(Bytes::from(archive)), - ) - .await - .map_err(|error| Status::internal(format!("stage Docker sandbox bundle: {error}")))?; - Ok(()) -} - -/// Restore the old stopped workload's authenticated channel from the private -/// rollback state. This is used only after a replacement failure; its input is -/// driver-owned files saved before the mutation, never inspected container -/// configuration. -/// Stream a stopped workload's workspace through one bounded anonymous file. -/// Docker's archive endpoint returns an untrusted tar stream, so reject every -/// entry outside the original workspace and all non-file/non-directory entry -/// types before uploading the same filtered archive to the replacement. -fn decode_docker_launch_authentication( - encoded: &[u8], -) -> Result { - let authentication = - serde_json::from_slice::(encoded) - .map_err(|error| { - Status::failed_precondition(format!( - "decode Docker sandbox launch authentication: {error}" - )) - })?; - authentication.validate().map_err(|error| { - Status::failed_precondition(format!( - "validate Docker sandbox launch authentication: {error}" - )) - })?; - Ok(authentication) -} - -fn gateway_verification_keys( - keys: &[openshell_core::jwt::SessionVerificationKey], -) -> Result, Status> { - keys.iter() - .map(|key| { - String::from_utf8(key.public_key_pem.clone()) - .map(|public_key_pem| GatewayVerificationKey { - key_id: key.key_id.clone(), - public_key_pem, - }) - .map_err(|error| { - Status::failed_precondition(format!( - "Docker sandbox verification key is not UTF-8 PEM: {error}" - )) - }) - }) - .collect() -} - -async fn prepare_docker_boundary_files( - docker: &Docker, - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - container_id: &str, - image: &DockerImageMetadata, - workload_identity: &ResolvedWorkloadIdentity, - gpu_requested: bool, -) -> Result<(), Status> { - let directory = docker_boundary_state_dir(sandbox, config)?; - let workspace_root = driver_mounts::resolve_oci_workspace_root(&image.working_dir) - .map_err(Status::failed_precondition)?; - let launch_authentication = sandbox - .spec - .as_ref() - .filter(|spec| !spec.launch_authentication.is_empty()) - .ok_or_else(|| { - Status::failed_precondition("Docker sandbox launch authentication is required") - }) - .and_then(|spec| decode_docker_launch_authentication(&spec.launch_authentication))?; - let session_id = launch_authentication.supervisor.session_id; - let tls = generate_sandbox_tls_material(session_id) - .map_err(|error| Status::internal(format!("generate Docker boundary TLS: {error}")))?; - let verification_keys = gateway_verification_keys(&launch_authentication.verification_keys)?; - let mut provisioning = isolation::DockerBoundarySpec { - boundary_id: sandbox.id.clone(), - generation: launch_authentication - .supervisor - .runtime_generation - .to_string(), - session_id, - session_rotation: launch_authentication.supervisor.session_rotation, - auth_epoch: launch_authentication.supervisor.auth_epoch, - gateway_id: launch_authentication.gateway_id, - verification_keys, - container_id: container_id.to_string(), - image_identity: image.id.clone(), - gpu_requested, - listener_socket: PathBuf::from(BOUNDARY_SOCKET_MOUNT_PATH), - control_socket: PathBuf::from(BOUNDARY_SOCKET_MOUNT_PATH), - sandbox_tls: SandboxTlsServerConfig { - certificate_chain_path: PathBuf::from(BOUNDARY_CERTIFICATE_MOUNT_PATH), - private_key_path: PathBuf::from(BOUNDARY_PRIVATE_KEY_MOUNT_PATH), - }, - supervisor_tls: SandboxTlsClientConfig { - server_name: tls.server_name.clone(), - trust_anchor_pem: tls.trust_anchor_pem.clone(), - }, - host_gateway_ip: config.host_gateway_ip, - workload_identity: workload_identity.clone(), - child_env: docker_child_environment(sandbox), - } - .provision() - .map_err(|error| Status::failed_precondition(error.to_string()))?; - if config.workspace_storage == workspace::Storage::Persistent { - let record = workspace::record_claim(&sandbox.id, config)?.ok_or_else(|| { - Status::failed_precondition( - "private Docker workspace record is missing during provisioning", - ) - })?; - for claims in [ - &mut provisioning.boundary_config.resource_claims, - &mut provisioning.runtime_descriptor.resource_claims, - ] { - claims.insert(workspace::RECORD_CLAIM.into(), record.clone()); - } - } - let boundary_config = provisioning - .boundary_config - .encode() - .map_err(|error| Status::internal(error.to_string()))?; - write_docker_boundary_file(&directory.join(BOUNDARY_CONFIG_FILE), &boundary_config).await?; - write_docker_boundary_file( - &directory.join(BOUNDARY_CERTIFICATE_FILE), - tls.certificate_chain_pem.as_bytes(), - ) - .await?; - write_docker_boundary_file( - &directory.join(BOUNDARY_PRIVATE_KEY_FILE), - tls.private_key_pem.as_bytes(), - ) - .await?; - stage_docker_sandbox_bundle( - docker, - container_id, - config, - workload_identity, - &boundary_config, - DockerSandboxTls { - certificate: tls.certificate_chain_pem.as_bytes(), - private_key: tls.private_key_pem.as_bytes(), - }, - &workspace_root, - ) - .await?; - let descriptor = provisioning - .runtime_descriptor - .backend_descriptor() - .map_err(|error| Status::internal(error.to_string()))?; - write_docker_boundary_file( - &directory.join(RUNTIME_DESCRIPTOR_FILE), - &descriptor.payload, - ) - .await?; - let supervisor_auth = serde_json::to_vec(&launch_authentication.supervisor) - .map_err(|error| Status::internal(format!("encode Docker supervisor auth: {error}")))?; - write_docker_boundary_file( - &directory.join(SUPERVISOR_AUTH_BUNDLE_FILE), - &supervisor_auth, - ) - .await?; - let main_process_spec = openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec( - sandbox.spec.as_ref(), - ) - .map_err(|error| Status::internal(format!("encode Docker main process spec: {error}")))?; - write_docker_boundary_file( - &directory.join(MAIN_PROCESS_SPEC_FILE), - main_process_spec.as_bytes(), - ) - .await?; - write_docker_boundary_file( - &directory.join(WORKSPACE_ROOT_FILE), - workspace_root.as_bytes(), - ) - .await?; - Ok(()) -} - -async fn docker_supervisor_bundle_archive( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> Result, Status> { - let directory = docker_boundary_state_dir(sandbox, config)?; - let runtime_descriptor = tokio::fs::read(directory.join(RUNTIME_DESCRIPTOR_FILE)) - .await - .map_err(|error| Status::internal(format!("read Docker runtime descriptor: {error}")))?; - let auth_bundle = tokio::fs::read(directory.join(SUPERVISOR_AUTH_BUNDLE_FILE)) - .await - .map_err(|error| { - Status::failed_precondition(format!("read Docker supervisor auth bundle: {error}")) - })?; - if auth_bundle.is_empty() { - return Err(Status::failed_precondition( - "Docker supervisor requires launch authentication", - )); - } - let mut archive = tar::Builder::new(Vec::new()); - append_docker_archive_file( - &mut archive, - "runtime-descriptor.json", - 0o600, - SUPERVISOR_UID, - SUPERVISOR_GID, - &runtime_descriptor, - )?; - append_docker_archive_file( - &mut archive, - "auth.json", - 0o600, - SUPERVISOR_UID, - SUPERVISOR_GID, - &auth_bundle, - )?; - if let Some(tls) = &config.guest_tls { - append_docker_archive_directory( - &mut archive, - "tls", - 0o700, - SUPERVISOR_UID, - SUPERVISOR_GID, - )?; - for (name, path) in [("ca.pem", &tls.ca)] { - let contents = tokio::fs::read(path).await.map_err(|error| { - Status::internal(format!( - "read Docker supervisor TLS file {}: {error}", - path.display() - )) - })?; - append_docker_archive_file( - &mut archive, - &format!("tls/{name}"), - 0o600, - SUPERVISOR_UID, - SUPERVISOR_GID, - &contents, - )?; - } - } - if let Some(path) = config.upstream_proxy.proxy_auth_file.as_ref() { - let contents = tokio::fs::read(path).await.map_err(|error| { - Status::internal(format!( - "read Docker upstream proxy credential {}: {error}", - path.display() - )) - })?; - append_docker_archive_file( - &mut archive, - "upstream-proxy-auth", - 0o600, - SUPERVISOR_UID, - SUPERVISOR_GID, - &contents, - )?; - } - append_docker_proxy_ca_bundle(&mut archive, config.proxy_ca_bundle.as_deref())?; - archive - .into_inner() - .map_err(|error| Status::internal(format!("finish Docker supervisor archive: {error}"))) -} - -fn append_docker_proxy_ca_bundle( - archive: &mut tar::Builder>, - path: Option<&Path>, -) -> Result<(), Status> { - let Some(path) = path else { - return Ok(()); - }; - let path = path - .to_str() - .ok_or_else(|| Status::failed_precondition("proxy_ca_bundle must be valid UTF-8"))?; - let contents = - openshell_core::driver_utils::read_upstream_proxy_ca_bundle_file(path, "proxy_ca_bundle") - .map_err(Status::failed_precondition)?; - append_docker_archive_file( - archive, - "upstream-proxy-ca-bundle.pem", - 0o644, - SUPERVISOR_UID, - SUPERVISOR_GID, - contents.as_bytes(), - ) -} - -async fn refresh_docker_boundary_authentication( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, - encoded_authentication: &[u8], -) -> Result<(), Status> { - let authentication = decode_docker_launch_authentication(encoded_authentication)?; - let directory = docker_boundary_state_dir_by_id(sandbox_id, config)?; - let mut boundary_config = serde_json::from_slice::( - &tokio::fs::read(directory.join(BOUNDARY_CONFIG_FILE)) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "read Docker sandbox bootstrap for authentication rotation: {error}" - )) - })?, - ) - .map_err(|error| { - Status::failed_precondition(format!( - "decode Docker sandbox bootstrap for authentication rotation: {error}" - )) - })?; - let Some(mut runtime_descriptor) = read_docker_runtime_descriptor(sandbox_id, config).await? - else { - return Err(Status::failed_precondition( - "Docker sandbox runtime descriptor is missing during authentication rotation", - )); - }; - let session_id = authentication.supervisor.session_id; - let tls = generate_sandbox_tls_material(session_id) - .map_err(|error| Status::internal(format!("rotate Docker boundary TLS: {error}")))?; - boundary_config.session_id = session_id; - boundary_config.generation = authentication.supervisor.runtime_generation.to_string(); - // The stopped container retains its resource identity, but each new launch - // binds both protocol peers and their provisioning evidence to a fresh generation. - let container_id = boundary_config - .resource_claims - .get("docker.container_id") - .ok_or_else(|| Status::failed_precondition("Docker sandbox container claim is missing"))?; - boundary_config.provisioning_evidence = - isolation::provisioning_evidence(container_id, &boundary_config.generation) - .map_err(|error| Status::failed_precondition(error.to_string()))?; - runtime_descriptor.generation = boundary_config.generation.clone(); - runtime_descriptor.provisioning_evidence = boundary_config.provisioning_evidence.clone(); - boundary_config.session_rotation = authentication.supervisor.session_rotation; - boundary_config.auth_epoch = authentication.supervisor.auth_epoch; - boundary_config.gateway_id = authentication.gateway_id; - boundary_config.verification_keys = - gateway_verification_keys(&authentication.verification_keys)?; - runtime_descriptor.session_id = session_id; - runtime_descriptor.tls = SandboxTlsClientConfig { - server_name: tls.server_name, - trust_anchor_pem: tls.trust_anchor_pem, - }; - let encoded_boundary_config = boundary_config - .encode() - .map_err(|error| Status::internal(error.to_string()))?; - let descriptor = runtime_descriptor - .backend_descriptor() - .map_err(|error| Status::internal(error.to_string()))?; - let supervisor_auth = serde_json::to_vec(&authentication.supervisor) - .map_err(|error| Status::internal(format!("encode Docker supervisor auth: {error}")))?; - write_docker_boundary_file( - &directory.join(BOUNDARY_CONFIG_FILE), - &encoded_boundary_config, - ) - .await?; - write_docker_boundary_file( - &directory.join(BOUNDARY_CERTIFICATE_FILE), - tls.certificate_chain_pem.as_bytes(), - ) - .await?; - write_docker_boundary_file( - &directory.join(BOUNDARY_PRIVATE_KEY_FILE), - tls.private_key_pem.as_bytes(), - ) - .await?; - write_docker_boundary_file( - &directory.join(RUNTIME_DESCRIPTOR_FILE), - &descriptor.payload, - ) - .await?; - write_docker_boundary_file( - &directory.join(SUPERVISOR_AUTH_BUNDLE_FILE), - &supervisor_auth, - ) - .await -} - -async fn refresh_docker_supervisor_authentication( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, - encoded_authentication: &[u8], -) -> Result<(), Status> { - let authentication = decode_docker_launch_authentication(encoded_authentication)?; - let directory = docker_boundary_state_dir_by_id(sandbox_id, config)?; - let Some(runtime_descriptor) = read_docker_runtime_descriptor(sandbox_id, config).await? else { - return Err(Status::failed_precondition( - "Docker sandbox runtime descriptor is missing during supervisor authentication rotation", - )); - }; - let descriptor = runtime_descriptor - .backend_descriptor() - .map_err(|error| Status::internal(error.to_string()))?; - let supervisor_auth = serde_json::to_vec(&authentication.supervisor) - .map_err(|error| Status::internal(format!("encode Docker supervisor auth: {error}")))?; - write_docker_boundary_file( - &directory.join(RUNTIME_DESCRIPTOR_FILE), - &descriptor.payload, - ) - .await?; - write_docker_boundary_file( - &directory.join(SUPERVISOR_AUTH_BUNDLE_FILE), - &supervisor_auth, - ) - .await -} - -async fn read_docker_runtime_descriptor( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result, Status> { - let path = docker_boundary_state_dir_by_id(sandbox_id, config)?.join(RUNTIME_DESCRIPTOR_FILE); - let bytes = match tokio::fs::read(&path).await { - Ok(bytes) => bytes, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => { - return Err(Status::internal(format!( - "read Docker runtime descriptor {}: {error}", - path.display() - ))); - } - }; - serde_json::from_slice(&bytes).map(Some).map_err(|error| { - Status::internal(format!( - "decode Docker runtime descriptor {}: {error}", - path.display() - )) - }) -} - -async fn stage_docker_supervisor_bundle( - docker: &Docker, - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - archive: Vec, -) -> Result<(), Status> { - let stager_name = format!("{}-supervisor-stage", container_name_for_sandbox(sandbox)); - let _ = docker - .remove_container( - &stager_name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - let runtime_initiated = read_docker_runtime_descriptor(&sandbox.id, config).await? - .is_some_and(|descriptor| matches!(descriptor.transport, openshell_sandbox_backend::boundary_protocol::SandboxTransport::RuntimeInitiatedUnix { .. })); - let mut mounts = vec![Mount { - target: Some(SUPERVISOR_STATE_MOUNT_PATH.to_string()), - source: Some(docker_supervisor_volume_name(sandbox, config)), - typ: Some(MountTypeEnum::VOLUME), - read_only: Some(false), - volume_options: Some(MountVolumeOptions { - no_copy: Some(true), - ..Default::default() - }), - ..Default::default() - }]; - if runtime_initiated { - mounts.push(Mount { - target: Some(BOUNDARY_CONTROL_MOUNT_PATH.to_string()), - source: Some(docker_control_volume_name_by_id(&sandbox.id, config)), - typ: Some(MountTypeEnum::VOLUME), - read_only: Some(false), - volume_options: Some(MountVolumeOptions { - no_copy: Some(true), - ..Default::default() - }), - ..Default::default() - }); - } - let created = docker - .create_container( - Some( - CreateContainerOptionsBuilder::default() - .name(stager_name.as_str()) - .build(), - ), - ContainerCreateBody { - image: Some(config.supervisor_image_id.clone()), - // Docker's copyUIDGID upload uses Config.User when it is set, - // overriding the archive's numeric ownership. Match the reader - // explicitly instead of inheriting the staging image's user. - user: Some(format!("{SUPERVISOR_UID}:{SUPERVISOR_GID}")), - entrypoint: Some(vec![SUPERVISOR_IMAGE_CONTROL_BINARY_PATH.to_string()]), - labels: Some(docker_auxiliary_container_labels( - sandbox, - config, - LABEL_ISOLATION_ROLE_STAGING, - )), - host_config: Some(HostConfig { - network_mode: Some("none".to_string()), - mounts: Some(mounts), - cap_drop: Some(vec!["ALL".to_string()]), - security_opt: Some(vec!["no-new-privileges:true".to_string()]), - ..Default::default() - }), - ..Default::default() - }, - ) - .await - .map_err(|error| { - Status::internal(format!( - "create Docker supervisor staging container: {error}" - )) - })?; - let options = UploadToContainerOptionsBuilder::default() - .path(SUPERVISOR_STATE_MOUNT_PATH) - .copy_uidgid("true") - .build(); - let result: Result<(), Status> = async { - docker - .upload_to_container( - &created.id, - Some(options), - bollard::body_full(Bytes::from(archive)), - ) - .await - .map_err(|error| { - Status::internal(format!("stage Docker supervisor bundle: {error}")) - })?; - if runtime_initiated { - // Initialize the socket volume using the supervisor's staging user. - // Docker preserves the existing volume root's ownership, so use - // a child directory created by the supervisor's staging user. - let mut archive = tar::Builder::new(Vec::new()); - append_docker_archive_directory( - &mut archive, - "supervisor", - 0o711, - SUPERVISOR_UID, - SUPERVISOR_GID, - )?; - let bytes = archive.into_inner().map_err(|error| { - Status::internal(format!("finish control socket archive: {error}")) - })?; - let options = UploadToContainerOptionsBuilder::default() - .path(BOUNDARY_CONTROL_MOUNT_PATH) - .copy_uidgid("true") - .build(); - docker - .upload_to_container( - &created.id, - Some(options), - bollard::body_full(Bytes::from(bytes)), - ) - .await - .map_err(|error| { - Status::internal(format!("stage Docker control socket volume: {error}")) - })?; - } - Ok(()) - } - .await; - let cleanup = docker - .remove_container( - &created.id, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await - .map_err(|error| { - Status::internal(format!( - "remove Docker supervisor staging container: {error}" - )) - }); - result?; - cleanup -} - -fn docker_auxiliary_container_labels( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - role: &str, -) -> HashMap { - HashMap::from([ - ( - LABEL_MANAGED_BY.to_string(), - LABEL_MANAGED_BY_VALUE.to_string(), - ), - (LABEL_SANDBOX_ID.to_string(), sandbox.id.clone()), - (LABEL_SANDBOX_NAME.to_string(), sandbox.name.clone()), - ( - LABEL_SANDBOX_NAMESPACE.to_string(), - config.sandbox_namespace.clone(), - ), - (LABEL_ISOLATION_ROLE.to_string(), role.to_string()), - ]) -} - -fn docker_supervisor_healthcheck() -> HealthConfig { - HealthConfig { - test: Some(vec![ - "CMD".to_string(), - SUPERVISOR_IMAGE_CONTROL_BINARY_PATH.to_string(), - "health".to_string(), - "--socket".to_string(), - SUPERVISOR_HEALTH_SOCKET_PATH.to_string(), - ]), - interval: Some(SUPERVISOR_HEALTH_INTERVAL_NS), - timeout: Some(SUPERVISOR_HEALTH_TIMEOUT_NS), - retries: Some(3), - start_period: Some(SUPERVISOR_HEALTH_START_PERIOD_NS), - start_interval: Some(SUPERVISOR_HEALTH_START_INTERVAL_NS), - } -} - -fn docker_supervisor_host_config( - mounts: Vec, - grpc_endpoint: &str, - network_mode: DockerSupervisorNetworkMode, - host_gateway_ip: Option, -) -> HostConfig { - HostConfig { - // The supervisor is trusted infrastructure and originates every - // approved upstream connection. Host networking lets it reach the - // configured gateway and host-side services directly; the workload - // remains fenced by network=none. - network_mode: Some( - if network_mode == DockerSupervisorNetworkMode::Bridge { - "bridge" - } else { - "host" - } - .to_string(), - ), - extra_hosts: host_gateway_ip - .map(|ip| { - let address = match ip { - IpAddr::V4(ip) => ip.to_string(), - IpAddr::V6(ip) => format!("[{ip}]"), - }; - vec![ - format!("{HOST_OPEN_SHELL_INTERNAL}:{address}"), - format!("{HOST_DOCKER_INTERNAL}:{address}"), - ] - }) - .or_else(|| docker_supervisor_host_aliases(grpc_endpoint)), - mounts: Some(mounts), - cap_drop: Some(vec!["ALL".to_string()]), - cap_add: None, - security_opt: Some(vec!["no-new-privileges:true".to_string()]), - readonly_rootfs: Some(true), - tmpfs: Some(HashMap::from([ - ( - "/run".to_string(), - format!( - "rw,noexec,nosuid,size=64m,uid={SUPERVISOR_UID},gid={SUPERVISOR_GID},mode=0700" - ), - ), - ( - "/tmp".to_string(), - "rw,noexec,nosuid,size=64m,mode=1777".to_string(), - ), - ( - "/var/log".to_string(), - format!( - "rw,noexec,nosuid,size=64m,uid={SUPERVISOR_UID},gid={SUPERVISOR_GID},mode=0700" - ), - ), - ])), - restart_policy: None, - ..Default::default() - } -} - -fn docker_supervisor_host_aliases(grpc_endpoint: &str) -> Option> { - let address = docker_supervisor_host_address(grpc_endpoint)?; - Some(vec![ - format!("{HOST_OPEN_SHELL_INTERNAL}:{address}"), - format!("{HOST_DOCKER_INTERNAL}:{address}"), - ]) -} - -fn docker_supervisor_host_address(grpc_endpoint: &str) -> Option { - let endpoint = Url::parse(grpc_endpoint).ok()?; - match endpoint.host()? { - url::Host::Ipv4(address) => Some(IpAddr::V4(address)), - url::Host::Domain(domain) if domain.eq_ignore_ascii_case("localhost") => { - Some(IpAddr::V4(Ipv4Addr::LOCALHOST)) - } - // Docker's extra-host syntax for IPv6 differs across daemon versions. - // Leave IPv6 and named remote endpoints to normal name resolution. - url::Host::Ipv6(_) | url::Host::Domain(_) => None, - } -} - -fn docker_network_trust_supervisor_args( - bundle: Option<&NetworkSupervisorTrustBundle>, -) -> Vec { - bundle.map_or_else(Vec::new, |_bundle| { - vec![ - "--additional-ca-bundle".to_string(), - ADDITIONAL_CA_MOUNT_PATH.to_string(), - ] - }) -} - -fn docker_network_trust_supervisor_mount( - bundle: &NetworkSupervisorTrustBundle, -) -> Result { - bundle.verify_artifact().map_err(|error| { - Status::failed_precondition(format!( - "verify gateway-owned network additional CA artifact: {error}" - )) - })?; - let source = bundle.artifact_path().to_str().ok_or_else(|| { - Status::failed_precondition(format!( - "network additional CA artifact path is not valid UTF-8: {}", - bundle.artifact_path().display() - )) - })?; - driver_mounts::validate_absolute_mount_source(source, "network additional CA artifact") - .map_err(Status::failed_precondition)?; - Ok(Mount { - target: Some(ADDITIONAL_CA_MOUNT_PATH.to_string()), - source: Some(source.to_string()), - typ: Some(MountTypeEnum::BIND), - read_only: Some(true), - ..Default::default() - }) -} - -/// Read the image identity pinned at provisioning, including after a restart. -/// Re-resolving the template's tag here could identify a different image. -async fn docker_workload_image_environment( - sandbox: &DriverSandbox, - directory: &Path, -) -> Result, Status> { - let bytes = tokio::fs::read(directory.join(BOUNDARY_CONFIG_FILE)) - .await - .map_err(|error| Status::internal(format!("read Docker image launch identity: {error}")))?; - let bootstrap: BoundaryConfig = serde_json::from_slice(&bytes) - .map_err(|_| Status::internal("decode Docker image launch identity"))?; - let mut environment = Vec::new(); - if let Some(image) = sandbox_image(sandbox) { - environment.push(format!( - "{}={image}", - openshell_core::sandbox_env::CONTAINER_IMAGE - )); - } - if let Some(uid) = bootstrap - .resource_claims - .get("docker.image_identity") - .filter(|uid| !uid.trim().is_empty()) - { - environment.push(format!( - "{}={uid}", - openshell_core::sandbox_env::CONTAINER_IMAGE_UID - )); - } - Ok(environment) -} - -async fn spawn_docker_control_process( - docker: &Docker, - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - failure_context: DockerRuntimeFailureContext, -) -> Result { - // This is the last gateway-side check before the trusted container gets a - // bind mount. It catches replacement/tamper after workload preparation - // without ever exposing the artifact to that workload. - if let Some(bundle) = config.network_trust.as_ref() { - bundle.verify_artifact().map_err(|error| { - Status::failed_precondition(format!( - "verify gateway-owned network additional CA artifact: {error}" - )) - })?; - } - let (network_mode, supervisor_endpoint) = docker_supervisor_networking(config)?; - info!(sandbox_id = %sandbox.id, ?network_mode, endpoint = %supervisor_endpoint, - "Selected Docker supervisor networking"); - let directory = docker_boundary_state_dir(sandbox, config)?; - let main_process_spec = tokio::fs::read_to_string(directory.join(MAIN_PROCESS_SPEC_FILE)) - .await - .map_err(|error| Status::internal(format!("read Docker main process spec: {error}")))?; - let workspace_root = tokio::fs::read_to_string(directory.join(WORKSPACE_ROOT_FILE)) - .await - .map_err(|error| Status::internal(format!("read Docker workspace root: {error}")))?; - let image_environment = docker_workload_image_environment(sandbox, &directory).await?; - let supervisor_name = format!("{}-supervisor", container_name_for_sandbox(sandbox)); - let _ = docker - .remove_container( - &supervisor_name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - let runtime_descriptor_path = format!("{SUPERVISOR_STATE_MOUNT_PATH}/runtime-descriptor.json"); - let auth_bundle_path = format!("{SUPERVISOR_STATE_MOUNT_PATH}/auth.json"); - let mut environment = vec![ - format!( - "{}={DRIVER_ADMITTED_BACKEND}", - openshell_core::sandbox_env::ADMITTED_ISOLATION_BACKEND - ), - format!( - "{}={main_process_spec}", - openshell_core::sandbox_env::MAIN_PROCESS_SPEC - ), - format!( - "{}={}", - openshell_core::sandbox_env::ENDPOINT, - supervisor_endpoint - ), - format!("{}={}", openshell_core::sandbox_env::SANDBOX_ID, sandbox.id), - format!("{}={}", openshell_core::sandbox_env::SANDBOX, sandbox.name), - format!( - "{}={}", - openshell_core::sandbox_env::SSH_SOCKET_PATH, - config.ssh_socket_path - ), - format!( - "{}=/run/openshell/proxy-tls", - openshell_core::sandbox_env::PROXY_TLS_DIR - ), - format!( - "{}={}", - openshell_core::sandbox_env::NETWORK_RUNTIME_CAPABILITIES, - openshell_core::sandbox_env::POLICY_DNS_TRANSPARENT_TCP_CAPABILITY - ), - format!( - "{}={}", - openshell_core::sandbox_env::LOG_LEVEL, - openshell_core::driver_utils::sandbox_log_level(sandbox, &config.log_level) - ), - format!( - "{}={}", - openshell_core::sandbox_env::TELEMETRY_ENABLED, - openshell_core::telemetry::enabled_env_value() - ), - ]; - environment.extend(image_environment); - environment.extend(supervisor_otlp_environment(config)); - if config.guest_tls.is_some() { - environment.push(format!( - "{}={SUPERVISOR_STATE_MOUNT_PATH}/tls/ca.pem", - openshell_core::sandbox_env::TLS_CA - )); - } - if let Some(socket) = config.provider_spiffe_workload_api_socket.as_ref() { - let projected = openshell_core::driver_utils::projected_provider_spiffe_socket_path(socket) - .map_err(Status::failed_precondition)?; - environment.push(format!( - "{}={projected}", - openshell_core::sandbox_env::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET - )); - } - let supervisor_archive = docker_supervisor_bundle_archive(sandbox, config).await?; - stage_docker_supervisor_bundle(docker, sandbox, config, supervisor_archive).await?; - let labels = HashMap::from([ - (LABEL_MANAGED_BY.to_string(), "openshell".to_string()), - (LABEL_SANDBOX_ID.to_string(), sandbox.id.clone()), - (LABEL_SANDBOX_NAME.to_string(), sandbox.name.clone()), - ( - LABEL_SANDBOX_NAMESPACE.to_string(), - config.sandbox_namespace.clone(), - ), - ( - LABEL_ISOLATION_ROLE.to_string(), - LABEL_ISOLATION_ROLE_SUPERVISOR.to_string(), - ), - ]); - let mut command = vec![ - "--backend-descriptor-file".to_string(), - runtime_descriptor_path, - "--auth-bundle-file".to_string(), - auth_bundle_path, - "--workdir".to_string(), - workspace_root, - format!("--health-socket-path={SUPERVISOR_HEALTH_SOCKET_PATH}"), - ]; - command.extend(docker_upstream_proxy_cli_args( - &config.upstream_proxy, - config.proxy_ca_bundle.is_some(), - )); - command.extend(config.ipv6_egress.supervisor_args()); - let runtime_initiated = read_docker_runtime_descriptor(&sandbox.id, config).await? - .is_some_and(|descriptor| matches!(descriptor.transport, openshell_sandbox_backend::boundary_protocol::SandboxTransport::RuntimeInitiatedUnix { .. })); - command.extend(docker_network_trust_supervisor_args( - config.network_trust.as_ref(), - )); - let mut supervisor_mounts = vec![ - Mount { - target: Some(BOUNDARY_MOUNT_PATH.to_string()), - source: Some(docker_channel_volume_name(sandbox, config)), - typ: Some(MountTypeEnum::VOLUME), - read_only: Some(true), - volume_options: Some(MountVolumeOptions { - no_copy: Some(true), - ..Default::default() - }), - ..Default::default() - }, - Mount { - target: Some(SUPERVISOR_STATE_MOUNT_PATH.to_string()), - source: Some(docker_supervisor_volume_name(sandbox, config)), - typ: Some(MountTypeEnum::VOLUME), - read_only: Some(true), - volume_options: Some(MountVolumeOptions { - no_copy: Some(true), - ..Default::default() - }), - ..Default::default() - }, - ]; - if runtime_initiated { - supervisor_mounts.push(Mount { - target: Some(BOUNDARY_CONTROL_MOUNT_PATH.to_string()), - source: Some(docker_control_volume_name_by_id(&sandbox.id, config)), - typ: Some(MountTypeEnum::VOLUME), - read_only: Some(false), - volume_options: Some(MountVolumeOptions { - no_copy: Some(true), - ..Default::default() - }), - ..Default::default() - }); - } - - if let Some(bundle) = config.network_trust.as_ref() { - supervisor_mounts.push(docker_network_trust_supervisor_mount(bundle)?); - } - if let Some(socket) = config.provider_spiffe_workload_api_socket.as_ref() { - let parent = socket.parent().ok_or_else(|| { - Status::failed_precondition("provider SPIFFE socket has no parent directory") - })?; - supervisor_mounts.push(Mount { - target: Some(PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR.to_string()), - source: Some(parent.display().to_string()), - typ: Some(MountTypeEnum::BIND), - read_only: Some(true), - ..Default::default() - }); - } - let create = ContainerCreateBody { - image: Some(config.supervisor_image_id.clone()), - user: Some(format!("{SUPERVISOR_UID}:{SUPERVISOR_GID}")), - entrypoint: Some(vec![SUPERVISOR_IMAGE_CONTROL_BINARY_PATH.to_string()]), - cmd: Some(command), - env: Some(environment), - labels: Some(labels), - healthcheck: Some(docker_supervisor_healthcheck()), - host_config: Some(docker_supervisor_host_config( - supervisor_mounts, - &supervisor_endpoint, - network_mode, - config.host_gateway_ip, - )), - ..Default::default() - }; - let created = docker - .create_container( - Some( - CreateContainerOptionsBuilder::default() - .name(supervisor_name.as_str()) - .build(), - ), - create, - ) - .await - .map_err(|error| { - Status::internal(format!("create Docker supervisor container: {error}")) - })?; - if let Err(error) = docker.start_container(&created.id, None).await { - let _ = docker - .remove_container( - &created.id, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - return Err(Status::internal(format!( - "start Docker supervisor container: {error}" - ))); - } - let sandbox_id = sandbox.id.clone(); - let (shutdown, mut shutdown_requested) = oneshot::channel(); - let intentional_shutdown = Arc::new(AtomicBool::new(false)); - let monitored_shutdown = intentional_shutdown.clone(); - let supervisor_id = created.id; - let monitored_supervisor_id = supervisor_id.clone(); - let monitored_docker = failure_context.docker.clone(); - let readiness_container_id = failure_context.container_id.clone(); - let readiness_sandbox_id = sandbox_id.clone(); - let readiness_failures = failure_context.failures.clone(); - let task = tokio::spawn(async move { - let remove_supervisor = || { - monitored_docker.remove_container( - &monitored_supervisor_id, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - }; - let wait = async { - let mut stream = monitored_docker.wait_container( - &monitored_supervisor_id, - None::, - ); - stream.next().await - }; - tokio::select! { - biased; - _ = &mut shutdown_requested => { - let _ = monitored_docker.stop_container( - &monitored_supervisor_id, - Some(StopContainerOptionsBuilder::default().t(SUPERVISOR_STOP_TIMEOUT_SECS).build()), - ).await; - let _ = remove_supervisor().await; - } - result = wait => { - if monitored_shutdown.load(Ordering::Acquire) { - let _ = remove_supervisor().await; - return; - } - if matches!( - tokio::time::timeout( - SUPERVISOR_INTENTIONAL_SHUTDOWN_GRACE, - &mut shutdown_requested, - ) - .await, - Ok(Ok(())), - ) || monitored_shutdown.load(Ordering::Acquire) - { - let _ = remove_supervisor().await; - return; - } - let (reason, mut message) = docker_supervisor_wait_failure(result); - warn!(%sandbox_id, %reason, %message, "Docker supervisor container exited unexpectedly"); - let log_tail = - docker_container_log_tail(&monitored_docker, &monitored_supervisor_id).await; - if reason == CONDITION_WORKSPACE_VALIDATION_FAILED { - warn!(%sandbox_id, supervisor_logs = %log_tail, "Docker sandbox rejected the image working directory"); - message = WORKSPACE_VALIDATION_FAILED_MESSAGE.to_string(); - } else if !log_tail.is_empty() { - write!(message, "; log tail: {log_tail}").ok(); - } - // The gateway can close the supervisor session as soon as it - // commits Stopping. Re-check after collecting diagnostics so - // an overlapping driver stop cannot be published as an - // unexpected control failure. - if monitored_shutdown.load(Ordering::Acquire) { - let _ = remove_supervisor().await; - return; - } - handle_docker_runtime_failure(failure_context, reason, message).await; - // Publish the reason before removing the container. Readiness - // may inspect it after cleanup and must still see exit 78. - let _ = remove_supervisor().await; - }, - } - }); - let process = DockerControlProcess { - shutdown: Some(shutdown), - intentional_shutdown, - task, - }; - if let Err(error) = Box::pin(wait_for_docker_supervisor_ready( - docker, - &supervisor_id, - &readiness_container_id, - &readiness_sandbox_id, - &readiness_failures, - )) - .await - { - stop_docker_control_process(process).await; - return Err(error); - } - Ok(process) -} - -async fn wait_for_docker_supervisor_ready( - docker: &Docker, - supervisor_id: &str, - workload_container_id: &str, - sandbox_id: &str, - failures: &Arc>>, -) -> Result<(), Status> { - // The monitor records a workspace rejection before it removes the - // supervisor, so a later failed inspection must still report it. - match poll_docker_supervisor_ready(docker, supervisor_id, workload_container_id, sandbox_id) - .await - { - Ok(()) => Ok(()), - Err(status) => Err(recorded_workspace_validation_failure(failures, sandbox_id) - .await - .unwrap_or(status)), - } -} - -async fn poll_docker_supervisor_ready( - docker: &Docker, - supervisor_id: &str, - workload_container_id: &str, - sandbox_id: &str, -) -> Result<(), Status> { - // Gateway provisioning deadlines own startup expiration, including policy - // repairs that extend the window. Unhealthy means not ready while the - // supervisor is quarantined; only a stopped process is a startup failure. - loop { - let sandbox = docker - .inspect_container(workload_container_id, None) - .await - .map_err(|error| { - Status::internal(format!("inspect Docker sandbox container: {error}")) - })?; - if sandbox.state.unwrap_or_default().running == Some(false) { - return Err(Status::unavailable( - "Docker sandbox exited before supervisor became ready", - )); - } - let inspected = docker - .inspect_container(supervisor_id, None) - .await - .map_err(|error| { - Status::internal(format!("inspect Docker supervisor container: {error}")) - })?; - let state = inspected.state.unwrap_or_default(); - match state.health.and_then(|health| health.status) { - Some(HealthStatusEnum::HEALTHY) => return Ok(()), - _ if state.running == Some(false) - && state.exit_code - == Some(i64::from(SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED)) => - { - let log_tail = docker_container_log_tail(docker, supervisor_id).await; - warn!(sandbox_id, supervisor_id, supervisor_logs = %log_tail, "Docker sandbox rejected the image working directory"); - return Err(workspace_validation_status()); - } - _ if state.running == Some(false) => { - let log_tail = docker_container_log_tail(docker, supervisor_id).await; - warn!(sandbox_id, supervisor_id, supervisor_logs = %log_tail, "Docker supervisor exited before becoming ready"); - return Err(Status::unavailable(format!( - "Docker supervisor exited before becoming ready{}", - format_log_tail(&log_tail) - ))); - } - _ => tokio::time::sleep(Duration::from_millis(100)).await, - } - } -} - -/// Bollard reports nonzero Docker wait statuses as errors, not successful -/// responses. Both forms must preserve the sandbox's workspace failure reason. -fn docker_supervisor_wait_failure( - result: Option>, -) -> (&'static str, String) { - match result { - Some(Ok(status)) => ( - supervisor_exit_reason(status.status_code), - format!( - "Docker supervisor container exited with status {}", - status.status_code - ), - ), - Some(Err(BollardError::DockerContainerWaitError { code, error })) => ( - supervisor_exit_reason(code), - format!("Docker supervisor container exited with status {code}: {error}"), - ), - Some(Err(error)) => ( - "ControlSupervisorExited", - format!("failed to wait for Docker supervisor container: {error}"), - ), - None => ( - "ControlSupervisorExited", - "Docker supervisor wait stream ended unexpectedly".to_string(), - ), - } -} - -async fn recorded_workspace_validation_failure( - failures: &Arc>>, - sandbox_id: &str, -) -> Option { - let failures = failures.lock().await; - failures - .get(sandbox_id) - .filter(|failure| failure.reason == CONDITION_WORKSPACE_VALIDATION_FAILED) - .map(|_| workspace_validation_status()) -} - -/// Startup failure for a supervisor that exited because the sandbox rejected -/// the image working directory. The message is fixed text, because supervisor -/// output may contain secrets, and identifies the failure for -/// [`supervisor_start_failure_reason`]. -fn workspace_validation_status() -> Status { - Status::failed_precondition(WORKSPACE_VALIDATION_FAILED_MESSAGE) -} - -/// Condition reason for a supervisor that failed before becoming ready. -fn supervisor_start_failure_reason(status: &Status, default: &'static str) -> &'static str { - if status.code() == tonic::Code::FailedPrecondition - && status.message() == WORKSPACE_VALIDATION_FAILED_MESSAGE - { - CONDITION_WORKSPACE_VALIDATION_FAILED - } else { - default - } -} - -/// Condition reason for a supervisor that exited with `status_code`. -fn supervisor_exit_reason(status_code: i64) -> &'static str { - if status_code == i64::from(SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED) { - CONDITION_WORKSPACE_VALIDATION_FAILED - } else { - "ControlSupervisorExited" - } -} - -fn format_log_tail(log_tail: &str) -> String { - // gRPC status messages travel in HTTP/2 headers. A full 16 KiB container - // tail can exceed the client's 16 KiB header budget and hide the real - // error behind PROTOCOL_ERROR. Allow for up to 3x percent-encoding expansion. - const MAX_STATUS_LOG_TAIL_BYTES: usize = 1024; - if log_tail.is_empty() { - String::new() - } else if log_tail.len() > MAX_STATUS_LOG_TAIL_BYTES { - let mut start = log_tail.len() - MAX_STATUS_LOG_TAIL_BYTES; - while !log_tail.is_char_boundary(start) { - start += 1; - } - format!("; log tail: [truncated] {}", &log_tail[start..]) - } else { - format!("; log tail: {log_tail}") - } -} - -async fn docker_container_log_tail(docker: &Docker, container_id: &str) -> String { - const MAX_LOG_TAIL_BYTES: usize = 16 * 1024; - let options = LogsOptionsBuilder::default() - .stdout(true) - .stderr(true) - .tail("80") - .build(); - let mut stream = docker.logs(container_id, Some(options)); - let mut output = Vec::new(); - while let Some(result) = stream.next().await { - let Ok(chunk) = result else { - break; - }; - output.extend_from_slice(chunk.as_ref()); - if output.len() > MAX_LOG_TAIL_BYTES { - output.drain(..output.len() - MAX_LOG_TAIL_BYTES); - } - } - String::from_utf8_lossy(&output).trim().to_string() -} - -async fn handle_docker_runtime_failure( - context: DockerRuntimeFailureContext, - reason: &'static str, - message: String, -) { - context.failures.lock().await.insert( - context.sandbox.id.clone(), - DockerRuntimeFailure { - reason, - message: message.clone(), - }, - ); - - let mut snapshot = pending_sandbox_snapshot( - &context.sandbox, - &context.sandbox_namespace, - error_condition(reason, &message), - false, - ); - if let Some(status) = snapshot.status.as_mut() { - status.instance_id.clone_from(&context.container_id); - } - let _ = context.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Sandbox( - WatchSandboxesSandboxEvent { - sandbox: Some(snapshot), - }, - )), - }); - let _ = context.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::PlatformEvent( - WatchSandboxesPlatformEvent { - sandbox_id: context.sandbox.id.clone(), - event: Some(platform_event( - "docker", - "Warning", - reason, - format!("{message}; stopping the isolated workload container"), - )), - }, - )), - }); - - match context - .docker - .stop_container( - &context.container_id, - Some( - StopContainerOptionsBuilder::default() - .t(docker_stop_timeout_secs(context.stop_timeout_secs)) - .build(), - ), - ) - .await - { - Ok(()) => info!( - sandbox_id = %context.sandbox.id, - container_id = %context.container_id, - "Stopped Docker sandbox after control supervisor failure" - ), - Err(error) if is_not_found_error(&error) || is_not_modified_error(&error) => {} - Err(error) => warn!( - sandbox_id = %context.sandbox.id, - container_id = %context.container_id, - %error, - "Failed to stop Docker sandbox after control supervisor failure" - ), - } -} - -async fn stop_docker_control_process(mut process: DockerControlProcess) { - process.intentional_shutdown.store(true, Ordering::Release); - if let Some(shutdown) = process.shutdown.take() { - let _ = shutdown.send(()); - } - let _ = process.task.await; -} - -// Failed or interrupted creation can leave a retained workspace. Keep its -// independent ownership record until explicit deletion removes that volume. -fn cleanup_failed_docker_boundary_state( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) { - let Ok(path) = workspace::record_path(&sandbox.id, config) else { - return; - }; - match std::fs::symlink_metadata(path) { - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - cleanup_docker_boundary_state(sandbox, config); - } - _ => {} // Preserve unreadable/invalid records too; recovery fails closed. - } -} - -fn cleanup_docker_boundary_state(sandbox: &DriverSandbox, config: &DockerDriverRuntimeConfig) { - cleanup_docker_boundary_state_by_id(&sandbox.id, config); -} - -fn cleanup_docker_boundary_state_by_id(sandbox_id: &str, config: &DockerDriverRuntimeConfig) { - let Ok(directory) = docker_boundary_state_dir_by_id(sandbox_id, config) else { - return; - }; - if let Err(error) = std::fs::remove_dir_all(&directory) - && error.kind() != std::io::ErrorKind::NotFound - { - warn!( - %sandbox_id, - path = %directory.display(), - %error, - "Failed to remove Docker boundary state directory" - ); - } -} - -fn docker_child_environment(sandbox: &DriverSandbox) -> HashMap { - let mut environment = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - .map_or_else(HashMap::new, |template| template.environment.clone()); - if let Some(spec) = sandbox.spec.as_ref() { - environment.extend(spec.environment.clone()); - } - for protected in [ - openshell_core::sandbox_env::ENDPOINT, - openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME, - openshell_core::sandbox_env::MAIN_PROCESS_SPEC, - openshell_core::sandbox_env::NETWORK_RUNTIME_CAPABILITIES, - openshell_core::sandbox_env::OCI_IMAGE_USER, - openshell_core::sandbox_env::SANDBOX, - openshell_core::sandbox_env::SANDBOX_GID, - openshell_core::sandbox_env::SANDBOX_ID, - openshell_core::sandbox_env::SANDBOX_TOKEN, - openshell_core::sandbox_env::SANDBOX_TOKEN_FILE, - openshell_core::sandbox_env::SANDBOX_UID, - openshell_core::sandbox_env::SSH_SOCKET_PATH, - openshell_core::sandbox_env::TLS_CA, - openshell_core::sandbox_env::TLS_CERT, - openshell_core::sandbox_env::TLS_KEY, - openshell_core::sandbox_env::USER_ENVIRONMENT, - ] { - environment.remove(protected); - } - environment -} - -/// Environment that lets the supervisor export spans, joining the current -/// trace, OCSF events, and relayed workload traces, identifying the gateway -/// that launched it. -fn supervisor_otlp_environment(config: &DockerDriverRuntimeConfig) -> Vec { - let exports = config.supervisor_otlp.environment(); - let trace_context = config - .supervisor_otlp - .traces - .iter() - .flat_map(|_| openshell_otel::current_trace_context_environment()); - let gateway_name = config - .supervisor_gateway_name - .iter() - .map(|name| (openshell_core::sandbox_env::GATEWAY_NAME, name.clone())); - exports - .into_iter() - .chain(trace_context) - .chain(gateway_name) - .map(|(name, value)| format!("{name}={value}")) - .collect() -} - -fn build_boundary_environment( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> Vec { - vec![ - format!( - "{}={}", - openshell_core::sandbox_env::LOG_LEVEL, - openshell_core::driver_utils::sandbox_log_level(sandbox, &config.log_level) - ), - format!( - "{}={}", - openshell_core::sandbox_env::TELEMETRY_ENABLED, - openshell_core::telemetry::enabled_env_value() - ), - ] -} - -fn docker_cdi_gpu_inventory(info: &SystemInfo) -> CdiGpuInventory { - CdiGpuInventory::new( - info.discovered_devices - .as_deref() - .unwrap_or_default() - .iter() - .filter(|device| device.source.as_deref() == Some("cdi")) - .filter_map(|device| device.id.as_deref()), - ) -} - -/// Oldest Docker Engine major version the driver is supported on. -const MIN_DOCKER_ENGINE_MAJOR: u64 = 28; - -/// Warn text when the daemon is a Docker Engine older than the supported -/// minimum. Older engines fail sandbox bundle staging with opaque errors. -fn unsupported_docker_engine_warning(version: &SystemVersion) -> Option { - let engine = version - .components - .iter() - .flatten() - .find(|component| component.name == "Engine")?; - let major: u64 = engine - .version - .split(|c: char| !c.is_ascii_digit()) - .next()? - .parse() - .ok()?; - (major < MIN_DOCKER_ENGINE_MAJOR).then(|| { - format!( - "Docker Engine {} is older than the supported minimum {MIN_DOCKER_ENGINE_MAJOR}.0; sandbox creation may fail. See the support matrix in the OpenShell docs.", - engine.version - ) - }) -} - -fn docker_info_reports_wsl2(info: &SystemInfo) -> bool { - [ - info.kernel_version.as_deref(), - info.operating_system.as_deref(), - ] - .into_iter() - .flatten() - .any(os_or_kernel_reports_wsl2) -} - -fn os_or_kernel_reports_wsl2(value: &str) -> bool { - let value = value.to_ascii_lowercase(); - value.contains("wsl2") || value.contains("microsoft-standard") -} - -fn docker_gpu_selection_status(err: CdiGpuSelectionError) -> Status { - Status::failed_precondition(err.to_string()) -} - -#[cfg(test)] -fn build_container_create_body( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, -) -> Result { - let template = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - .ok_or_else(|| Status::invalid_argument("sandbox.spec.template is required"))?; - let driver_config = docker_driver_config(template, config.enable_bind_mounts)?; - let gpu_requirements = sandbox - .spec - .as_ref() - .and_then(|spec| driver_gpu_requirements(spec.resource_requirements.as_ref())); - let cdi_devices = if let Some(cdi_devices) = driver_config.cdi_devices.as_ref() { - validate_cdi_gpu_device_request(gpu_requirements, cdi_devices, "driver_config.cdi_devices") - .map_err(Status::invalid_argument)?; - Some(cdi_devices.as_slice()) - } else { - None - }; - build_container_create_body_with_gpu_devices(sandbox, config, &driver_config, cdi_devices) -} - -#[cfg(test)] -fn build_container_create_body_with_gpu_devices( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - driver_config: &DockerSandboxDriverConfig, - gpu_device_ids: Option<&[String]>, -) -> Result { - let template = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - .ok_or_else(|| Status::invalid_argument("sandbox.spec.template is required"))?; - let workload_identity = ResolvedWorkloadIdentity::new( - 1000, - 1000, - Vec::new(), - "test".to_string(), - template.image.clone(), - ) - .map_err(|error| Status::internal(error.to_string()))?; - build_container_create_body_for_image( - sandbox, - config, - driver_config, - gpu_device_ids, - &DockerImageMetadata { - id: template.image.clone(), - user: String::new(), - working_dir: String::new(), - volumes: Vec::new(), - }, - &workload_identity, - ) -} - -fn build_container_create_body_for_image( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - driver_config: &DockerSandboxDriverConfig, - gpu_device_ids: Option<&[String]>, - image: &DockerImageMetadata, - workload_identity: &ResolvedWorkloadIdentity, -) -> Result { - if let Some(device_ids) = gpu_device_ids { - validate_cdi_device_names(device_ids, "driver_config.cdi_devices") - .map_err(Status::invalid_argument)?; - } - let spec = sandbox - .spec - .as_ref() - .ok_or_else(|| Status::invalid_argument("sandbox.spec is required"))?; - let template = spec - .template - .as_ref() - .ok_or_else(|| Status::invalid_argument("sandbox.spec.template is required"))?; - let resource_limits = docker_resource_limits(template)?; - let workspace_root = driver_mounts::resolve_oci_workspace_root(&image.working_dir) - .map_err(Status::failed_precondition)?; - driver_mounts::validate_workspace_control_path(&workspace_root, BOUNDARY_MOUNT_PATH) - .map_err(Status::failed_precondition)?; - for volume in &image.volumes { - driver_mounts::validate_container_mount_target(volume).map_err(|error| { - Status::failed_precondition(format!( - "invalid image-declared volume '{volume}': {error}" - )) - })?; - driver_mounts::validate_workspace_mount_target(volume, &workspace_root).map_err(|_| { - Status::failed_precondition(format!( - "image-declared volume '{volume}' masks OCI WorkingDir '{workspace_root}' before workspace validation" - )) - })?; - driver_mounts::validate_mount_control_path(volume, BOUNDARY_MOUNT_PATH) - .map_err(Status::failed_precondition)?; - } - let mount_targets = driver_config.mounts.iter().map(|mount| { - match mount { - DockerDriverMountConfig::Bind { target, .. } - | DockerDriverMountConfig::Volume { target, .. } - | DockerDriverMountConfig::Tmpfs { target, .. } - | DockerDriverMountConfig::Image { target, .. } => target, - } - .as_str() - }); - driver_mounts::validate_workspace_mount_targets( - mount_targets, - &workspace_root, - &[BOUNDARY_MOUNT_PATH], - ) - .map_err(Status::failed_precondition)?; - let mut user_mounts = docker_driver_mounts(driver_config)?; - if let Some(mount) = workspace::mount(sandbox, config, image)? { - user_mounts.push(mount); - } - user_mounts.push(Mount { - target: Some(BOUNDARY_MOUNT_PATH.to_string()), - source: Some(docker_channel_volume_name(sandbox, config)), - typ: Some(MountTypeEnum::VOLUME), - read_only: Some(false), - volume_options: Some(MountVolumeOptions { - no_copy: Some(true), - ..Default::default() - }), - ..Default::default() - }); - // The runtime only dials the supervisor-owned socket; it never writes here. - user_mounts.push(Mount { - target: Some(BOUNDARY_CONTROL_MOUNT_PATH.to_string()), - source: Some(docker_control_volume_name_by_id(&sandbox.id, config)), - typ: Some(MountTypeEnum::VOLUME), - read_only: Some(true), - volume_options: Some(MountVolumeOptions { - no_copy: Some(true), - ..Default::default() - }), - ..Default::default() - }); - - let user_bind_strings = docker_driver_bind_strings(driver_config)?; - let device_requests = gpu_device_ids.map(|device_ids| { - vec![DeviceRequest { - driver: Some("cdi".to_string()), - device_ids: Some(device_ids.to_vec()), - ..Default::default() - }] - }); - let mut labels = template.labels.clone(); - // Persistence is recorded in protected driver state, never inferred from - // or published over caller-owned template labels. - labels.insert( - "openshell.ai/private-image-volume-targets".into(), - serde_json::to_string(&image.volumes) - .map_err(|error| Status::internal(error.to_string()))?, - ); - labels.insert( - openshell_core::resource_admission::CONFIG_USED_LABEL.into(), - template - .driver_config - .as_ref() - .is_some_and(|config| !config.fields.is_empty()) - .to_string(), - ); - labels.insert( - LABEL_MANAGED_BY.to_string(), - LABEL_MANAGED_BY_VALUE.to_string(), - ); - labels.insert(LABEL_SANDBOX_ID.to_string(), sandbox.id.clone()); - labels.insert(LABEL_SANDBOX_NAME.to_string(), sandbox.name.clone()); - labels.insert( - LABEL_SANDBOX_WORKSPACE.to_string(), - sandbox.workspace.clone(), - ); - // The list/get/find paths filter by `config.sandbox_namespace`, so use - // the same value here. `DriverSandbox.namespace` is unset on the request - // path (the gateway elides it), and using it would produce containers - // that the driver itself cannot find afterwards. - labels.insert( - LABEL_SANDBOX_NAMESPACE.to_string(), - config.sandbox_namespace.clone(), - ); - labels.insert( - LABEL_ISOLATION_BACKEND.to_string(), - LABEL_ISOLATION_BACKEND_OPEN_SHELL.to_string(), - ); - labels.insert( - LABEL_ISOLATION_ROLE.to_string(), - LABEL_ISOLATION_ROLE_SANDBOX.to_string(), - ); - - Ok(ContainerCreateBody { - image: Some(image.id.clone()), - user: Some(format!( - "{}:{}", - workload_identity.uid, workload_identity.gid - )), - // The image workspace may need to be created or rejected by the - // supervisor, so do not let the OCI runtime chdir there first. - working_dir: Some("/".to_string()), - env: Some(build_boundary_environment(sandbox, config)), - entrypoint: Some(vec![SANDBOX_BINARY_PATH.to_string()]), - // The image cannot append inherited arguments or select either role. - cmd: Some(vec![ - "--bootstrap".to_string(), - BOUNDARY_CONFIG_MOUNT_PATH.to_string(), - ]), - labels: Some(labels), - host_config: Some(HostConfig { - nano_cpus: resource_limits.nano_cpus, - memory: resource_limits.memory_bytes, - pids_limit: docker_pids_limit(config.sandbox_pids_limit)?, - device_requests, - binds: { - let mut binds = build_binds(sandbox, config); - binds.extend(user_bind_strings); - Some(binds) - }, - mounts: Some(user_mounts), - // Canonical main-process exit is terminal. Runtime restart would - // silently create a new process generation behind the gateway. - restart_policy: None, - group_add: Some( - workload_identity - .supplementary_gids - .iter() - .map(u32::to_string) - .collect(), - ), - cap_drop: Some(vec!["ALL".to_string()]), - cap_add: None, - security_opt: Some({ - let mut options = vec!["no-new-privileges:true".to_string()]; - if let Some(option) = config - .app_armor_profile - .as_ref() - .and_then(AppArmorProfile::oci_security_opt) - { - options.push(option); - } - options - }), - network_mode: Some("none".to_string()), - dns: Some(vec!["127.0.0.53".to_string()]), - // Docker otherwise copies the host's search domains. Like the - // Podman, Kubernetes, and VM resolvers, send names to policy DNS - // exactly as written so short names never expand to host domains. - dns_search: Some(vec![".".to_string()]), - tmpfs: Some(HashMap::from([( - openshell_sandbox_backend::SUPERVISOR_CA_RUNTIME_DIR.to_string(), - format!( - "rw,noexec,nosuid,nodev,size=1m,uid={},gid={},mode=0755", - workload_identity.uid, workload_identity.gid - ), - )])), - sysctls: Some(HashMap::from([( - "net.ipv4.ip_unprivileged_port_start".to_string(), - "0".to_string(), - )])), - extra_hosts: None, - ..Default::default() - }), - networking_config: None, - ..Default::default() - }) -} - -/// Reject driver requests that arrive with neither a sandbox id nor a -/// sandbox name. Without this guard, downstream label filters degenerate -/// to "match every managed container in the namespace", which would let -/// `delete_sandbox`/`stop_sandbox`/`get_sandbox` pick an arbitrary -/// sandbox out of the set the driver manages. -fn require_sandbox_identifier(sandbox_id: &str, sandbox_name: &str) -> Result<(), Status> { - if sandbox_id.is_empty() && sandbox_name.is_empty() { - return Err(Status::invalid_argument( - "sandbox_id or sandbox_name is required", - )); - } - Ok(()) -} - -fn docker_resource_limits( - template: &DriverSandboxTemplate, -) -> Result { - let Some(resources) = template.resources.as_ref() else { - return Ok(DockerResourceLimits::default()); - }; - - if !resources.cpu_request.trim().is_empty() { - return Err(Status::failed_precondition( - "docker compute driver does not support resources.requests.cpu", - )); - } - if !resources.memory_request.trim().is_empty() { - return Err(Status::failed_precondition( - "docker compute driver does not support resources.requests.memory", - )); - } - - Ok(DockerResourceLimits { - nano_cpus: parse_cpu_limit(&resources.cpu_limit)?, - memory_bytes: parse_memory_limit(&resources.memory_limit)?, - }) -} - -fn validate_docker_proxy_auth_file(config: &UpstreamProxyConfig) -> CoreResult<()> { - let Some(path) = config.proxy_auth_file.as_ref() else { - return Ok(()); - }; - let raw = openshell_core::driver_utils::read_upstream_proxy_credential_file( - path.to_str() - .ok_or_else(|| Error::config("proxy_auth_file must be valid UTF-8"))?, - ) - .map_err(Error::config)?; - openshell_core::driver_utils::parse_upstream_proxy_credential(&raw) - .map_err(|error| Error::config(format!("proxy_auth_file is invalid: {error}")))?; - Ok(()) -} - -fn validate_docker_proxy_ca_bundle(config: &DockerComputeConfig) -> CoreResult<()> { - let Some(path) = config.proxy_ca_bundle.as_ref() else { - return Ok(()); - }; - if path.as_os_str().is_empty() { - return Err(Error::config("proxy_ca_bundle must not be empty when set")); - } - if config.upstream_proxy.https_proxy.is_none() { - return Err(Error::config( - "proxy_ca_bundle is set but no https_proxy is configured", - )); - } - let path = path - .to_str() - .ok_or_else(|| Error::config("proxy_ca_bundle must be valid UTF-8"))?; - openshell_core::driver_utils::read_upstream_proxy_ca_bundle_file(path, "proxy_ca_bundle") - .map_err(Error::config)?; - Ok(()) -} - -fn docker_upstream_proxy_cli_args( - config: &UpstreamProxyConfig, - proxy_ca_bundle_configured: bool, -) -> Vec { - let mut args = Vec::new(); - if let Some(url) = config.https_proxy.as_ref() { - args.extend(["--upstream-proxy".to_string(), url.clone()]); - } - if let Some(no_proxy) = config.no_proxy.as_ref() { - args.extend(["--upstream-no-proxy".to_string(), no_proxy.clone()]); - } - if config.proxy_auth_file.is_some() { - args.extend([ - "--upstream-proxy-auth-file".to_string(), - SUPERVISOR_PROXY_AUTH_MOUNT_PATH.to_string(), - ]); - } - if config.proxy_auth_allow_insecure == Some(true) { - args.push("--upstream-proxy-auth-allow-insecure".to_string()); - } - if config.proxy_connect_by_hostname == Some(true) { - args.push("--upstream-proxy-connect-by-hostname".to_string()); - } - if proxy_ca_bundle_configured { - args.extend([ - "--upstream-proxy-ca-bundle".to_string(), - SUPERVISOR_PROXY_CA_BUNDLE_MOUNT_PATH.to_string(), - ]); - } - args -} - -fn validate_sandbox_pids_limit(value: Option) -> CoreResult<()> { - if value.is_some_and(|value| value.get() <= 0) { - return Err(Error::config( - "docker sandbox_pids_limit must be positive when set", - )); - } - Ok(()) -} - -fn validate_image_pull_policy(policy: ImagePullPolicy) -> CoreResult<()> { - if policy == ImagePullPolicy::Newer { - return Err(Error::config( - "docker image_pull_policy = \"newer\" is supported only by the Podman compute driver", - )); - } - Ok(()) -} - -fn validate_docker_app_armor_profile( - profile: Option<&AppArmorProfile>, - info: &SystemInfo, -) -> CoreResult<()> { - let requires_apparmor = matches!( - profile, - Some(AppArmorProfile::RuntimeDefault | AppArmorProfile::Localhost(_)) - ); - if !requires_apparmor { - return Ok(()); - } - let available = info.security_options.as_ref().is_some_and(|options| { - options - .iter() - .any(|option| option.to_ascii_lowercase().contains("apparmor")) - }); - if !available { - return Err(Error::config( - "app_armor_profile requires AppArmor, but Docker reports it is unavailable; enable AppArmor on the daemon host or set app_armor_profile = \"Unconfined\" explicitly", - )); - } - Ok(()) -} - -fn docker_pids_limit(value: Option) -> Result, Status> { - if value.is_some_and(|value| value.get() < 0) { - return Err(Status::failed_precondition( - "docker sandbox_pids_limit must be positive when set", - )); - } - Ok(value.map(std::num::NonZeroI64::get)) -} - -#[allow(clippy::cast_possible_truncation)] -fn parse_cpu_limit(value: &str) -> Result, Status> { - let value = value.trim(); - if value.is_empty() { - return Ok(None); - } - if let Some(millicores) = value.strip_suffix('m') { - let millicores = millicores.parse::().map_err(|_| { - Status::failed_precondition(format!( - "invalid docker cpu_limit '{value}'; expected an integer or millicore quantity", - )) - })?; - if millicores <= 0 { - return Err(Status::failed_precondition( - "docker cpu_limit must be greater than zero", - )); - } - return Ok(Some(millicores.saturating_mul(1_000_000))); - } - - let cores = value.parse::().map_err(|_| { - Status::failed_precondition(format!( - "invalid docker cpu_limit '{value}'; expected an integer or millicore quantity", - )) - })?; - if !cores.is_finite() || cores <= 0.0 { - return Err(Status::failed_precondition( - "docker cpu_limit must be greater than zero", - )); - } - - Ok(Some((cores * 1_000_000_000.0).round() as i64)) -} - -#[allow(clippy::cast_possible_truncation)] -fn parse_memory_limit(value: &str) -> Result, Status> { - let value = value.trim(); - if value.is_empty() { - return Ok(None); - } - - let number_end = value - .find(|ch: char| !(ch.is_ascii_digit() || ch == '.')) - .unwrap_or(value.len()); - let (number, suffix) = value.split_at(number_end); - let amount = number.parse::().map_err(|_| { - Status::failed_precondition(format!( - "invalid docker memory_limit '{value}'; expected a Kubernetes-style quantity", - )) - })?; - if !amount.is_finite() || amount <= 0.0 { - return Err(Status::failed_precondition( - "docker memory_limit must be greater than zero", - )); - } - - let multiplier = match suffix { - "" => 1_f64, - "Ki" => 1024_f64, - "Mi" => 1024_f64.powi(2), - "Gi" => 1024_f64.powi(3), - "Ti" => 1024_f64.powi(4), - "Pi" => 1024_f64.powi(5), - "Ei" => 1024_f64.powi(6), - "K" => 1000_f64, - "M" => 1000_f64.powi(2), - "G" => 1000_f64.powi(3), - "T" => 1000_f64.powi(4), - "P" => 1000_f64.powi(5), - "E" => 1000_f64.powi(6), - _ => { - return Err(Status::failed_precondition(format!( - "invalid docker memory_limit suffix '{suffix}'", - ))); - } - }; - - Ok(Some((amount * multiplier).round() as i64)) -} - -fn sandbox_from_container_summary(summary: &ContainerSummary) -> Option { - let labels = summary.labels.as_ref()?; - let id = labels.get(LABEL_SANDBOX_ID)?.clone(); - let name = labels.get(LABEL_SANDBOX_NAME)?.clone(); - let namespace = labels - .get(LABEL_SANDBOX_NAMESPACE) - .cloned() - .unwrap_or_default(); - let workspace = labels - .get(LABEL_SANDBOX_WORKSPACE) - .cloned() - .unwrap_or_default(); - - Some(DriverSandbox { - id, - name: name.clone(), - namespace, - spec: None, - status: Some(driver_status_from_summary(summary, &name)), - workspace, - }) -} - -fn driver_status_from_summary( - summary: &ContainerSummary, - sandbox_name: &str, -) -> DriverSandboxStatus { - let state = summary.state.unwrap_or(ContainerSummaryStateEnum::EMPTY); - let (ready, reason, message, deleting) = container_ready_condition(state); - - DriverSandboxStatus { - name: summary_container_name(summary).unwrap_or_else(|| sandbox_name.to_string()), - instance_id: summary.id.clone().unwrap_or_default(), - agent_fd: String::new(), - sandbox_fd: String::new(), - conditions: vec![DriverCondition { - r#type: "Ready".to_string(), - status: ready.to_string(), - reason: reason.to_string(), - message: message.to_string(), - transition_time: None, - }], - deleting, - ..Default::default() - } -} - -/// Refine an exited Docker sandbox's `Ready` condition from inspected state. -/// -/// A signal kill (exit 137/143 = SIGKILL/SIGTERM, not OOM) is the signature of -/// a machine/daemon restart terminating a running container. Reclassify it from -/// the generic terminal `ContainerExited` to the recoverable -/// `ContainerRuntimeRestart` so gateway startup can revive it. OOM kills and -/// ordinary application exits stay `ContainerExited` and terminal. -fn apply_docker_exit_classification(sandbox: &mut DriverSandbox, state: &ContainerState) { - if state.oom_killed == Some(true) { - return; - } - let Some(code) = state.exit_code.filter(|&code| matches!(code, 137 | 143)) else { - return; - }; - let Some(condition) = sandbox - .status - .as_mut() - .and_then(|status| status.conditions.iter_mut().find(|c| c.r#type == "Ready")) - else { - return; - }; - if condition.reason != CONDITION_EXITED { - return; - } - condition.reason = CONDITION_RUNTIME_RESTART.to_string(); - condition.message = format!("Container terminated by signal (exit code {code})"); -} - -fn container_ready_condition( - state: ContainerSummaryStateEnum, -) -> (&'static str, &'static str, &'static str, bool) { - match state { - ContainerSummaryStateEnum::RUNNING => { - ("True", "BackendReady", "Container is running", false) - } - ContainerSummaryStateEnum::CREATED => ("False", "Starting", "Container created", false), - ContainerSummaryStateEnum::RESTARTING => ( - "False", - "ContainerRestarting", - "Container is restarting after a failure", - false, - ), - ContainerSummaryStateEnum::EMPTY => { - ("False", "Starting", "Container state is unknown", false) - } - ContainerSummaryStateEnum::REMOVING => { - ("False", "Deleting", "Container is being removed", true) - } - ContainerSummaryStateEnum::PAUSED => { - ("False", "ContainerPaused", "Container is paused", false) - } - ContainerSummaryStateEnum::EXITED => ("False", CONDITION_EXITED, "Container exited", false), - ContainerSummaryStateEnum::DEAD => ("False", "ContainerDead", "Container is dead", false), - } -} - -fn summary_container_name(summary: &ContainerSummary) -> Option { - summary - .names - .as_ref() - .and_then(|names| names.first()) - .map(|name| name.trim_start_matches('/').to_string()) - .filter(|name| !name.is_empty()) -} - -fn summary_container_target(summary: &ContainerSummary) -> Option { - // Prefer the container ID: it's stable while the container exists and is - // accepted by Docker APIs just like a name. Fall back to the parsed name - // for transient summaries that do not include an ID. - summary - .id - .as_deref() - .filter(|id| !id.is_empty()) - .map(str::to_string) - .or_else(|| summary_container_name(summary)) -} - -/// States from which a managed container can be brought back to running by -/// `start_container`. Skip `Restarting` (already coming up), `Removing`, -/// `Dead` (terminal), `Paused` (needs `unpause`, not `start`), and -/// `Running` (nothing to do). -fn container_state_needs_start(state: ContainerSummaryStateEnum) -> bool { - matches!( - state, - ContainerSummaryStateEnum::EXITED | ContainerSummaryStateEnum::CREATED - ) -} - -fn docker_stop_timeout_secs(timeout_secs: u32) -> i32 { - i32::try_from(timeout_secs).unwrap_or(i32::MAX) -} - -fn driver_sandbox_reports_container_exit(sandbox: &DriverSandbox) -> bool { - sandbox.status.as_ref().is_some_and(|status| { - status.conditions.iter().any(|condition| { - condition.r#type == "Ready" - && condition.status.eq_ignore_ascii_case("false") - && condition.reason == "ContainerExited" - }) - }) -} - -fn docker_polled_exit_is_stale( - previous_finished_at: &str, - current_state: Option<&ContainerState>, -) -> bool { - let Some(current_state) = current_state else { - return false; - }; - - if current_state.status != Some(ContainerStateStatusEnum::EXITED) { - // The list response said Exited, but inspect has already observed a - // newer state. Publishing the older list result would regress it. - return true; - } - - current_state.finished_at.as_deref() == Some(previous_finished_at) -} - -fn label_filters(values: impl IntoIterator) -> HashMap> { - HashMap::from([("label".to_string(), values.into_iter().collect())]) -} - -fn managed_container_label_filters( - sandbox_namespace: &str, - extra_values: impl IntoIterator, -) -> HashMap> { - let mut values = vec![format!( - "{LABEL_ISOLATION_ROLE}={LABEL_ISOLATION_ROLE_SANDBOX}" - )]; - values.extend(extra_values); - managed_resource_label_filters(sandbox_namespace, values) -} - -fn managed_resource_label_filters( - sandbox_namespace: &str, - extra_values: impl IntoIterator, -) -> HashMap> { - let mut values = vec![ - format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE}"), - format!("{LABEL_SANDBOX_NAMESPACE}={sandbox_namespace}"), - ]; - values.extend(extra_values); - label_filters(values) -} - -/// Maximum Docker container name length. Docker's own limit is 253 bytes, but -/// we cap at a conservative 200 to leave headroom for tooling that truncates -/// names further. -const MAX_CONTAINER_NAME_LEN: usize = 200; -const CONTAINER_NAME_PREFIX: &str = "openshell-"; - -fn container_name_for_sandbox(sandbox: &DriverSandbox) -> String { - let id_suffix = sanitize_docker_name(&sandbox.id); - let workspace = sanitize_docker_name(&sandbox.workspace); - let name = sanitize_docker_name(&sandbox.name); - - // Format: openshell-{workspace}--{name}-{id} - // The workspace and id are never truncated — they ensure uniqueness. - // Only the sandbox name portion is truncated when the total exceeds - // MAX_CONTAINER_NAME_LEN. - - if name.is_empty() { - let mut base = format!("{CONTAINER_NAME_PREFIX}{workspace}---{id_suffix}"); - if base.len() > MAX_CONTAINER_NAME_LEN { - base.truncate(MAX_CONTAINER_NAME_LEN); - } - return trim_container_name_tail(base); - } - - // Reserve space for fixed parts: prefix + workspace + "--" + "-" + id - let reserved = CONTAINER_NAME_PREFIX.len() + workspace.len() + 2 + 1 + id_suffix.len(); - if reserved >= MAX_CONTAINER_NAME_LEN { - let mut base = format!("{CONTAINER_NAME_PREFIX}{workspace}---{id_suffix}"); - base.truncate(MAX_CONTAINER_NAME_LEN); - return trim_container_name_tail(base); - } - - let name_budget = MAX_CONTAINER_NAME_LEN - reserved; - let truncated_name = if name.len() > name_budget { - trim_container_name_tail(name[..name_budget].to_string()) - } else { - name - }; - format!("{CONTAINER_NAME_PREFIX}{workspace}--{truncated_name}-{id_suffix}") -} - -/// Normalize an image reference for a pull request by appending `:latest` -/// when it carries neither an explicit tag nor a digest. -/// -/// The Docker daemon's `create_image` endpoint interprets a `fromImage` with -/// no tag as "every tag in the repository" and pulls them all, so a bare -/// `--from` reference such as `nicolaka/netshoot` must be resolved to a single -/// tag the way `docker pull` (and the Podman driver) do. -/// -/// Parsing mirrors [`openshell_core::driver_utils::supervisor_image_tag`]: only -/// the final path component may carry a tag, so a registry port such as the -/// `:5000` in `registry:5000/team/app` is not mistaken for one, and a -/// digest-pinned reference (`...@sha256:...`) already names an exact image and -/// is left untouched. A separate helper is needed because `supervisor_image_tag` -/// resolves a bare reference to an implied `latest` and so cannot distinguish a -/// reference that still needs a tag appended. -/// -/// Examples: -/// - `"nicolaka/netshoot"` → `"nicolaka/netshoot:latest"` -/// - `"foo:1.2"` → `"foo:1.2"` (already tagged) -/// - `"foo@sha256:abc"` → `"foo@sha256:abc"` (digest-pinned) -/// - `"registry:5000/team/app"` → `"registry:5000/team/app:latest"` -/// - `"registry:5000/team/app:v1"` → `"registry:5000/team/app:v1"` -fn normalize_pull_reference(image: &str) -> Cow<'_, str> { - // A digest-pinned reference already identifies an exact image. - if image.contains('@') { - return Cow::Borrowed(image); - } - // A `:` only denotes a tag in the final path component; earlier ones are - // registry ports (e.g. `registry:5000/team/app`). - let last_component = image.rsplit('/').next().unwrap_or(image); - if last_component.contains(':') { - Cow::Borrowed(image) - } else { - Cow::Owned(format!("{image}:latest")) - } -} - -/// Docker container names may not end with `-`, `.`, or `_`. Truncation can -/// leave one of those trailing, so strip them before returning. -fn trim_container_name_tail(mut value: String) -> String { - while value - .chars() - .last() - .is_some_and(|ch| matches!(ch, '-' | '.' | '_')) - { - value.pop(); - } - value -} - -fn sanitize_docker_name(value: &str) -> String { - value - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-') { - ch.to_ascii_lowercase() - } else { - '-' - } - }) - .collect::() - .trim_matches('-') - .to_string() -} - -async fn pull_runtime_image(docker: &Docker, image: &str, role: &str) -> CoreResult<()> { - let mut stream = docker.create_image( - Some(CreateImageOptions { - from_image: Some(normalize_pull_reference(image).into_owned()), - ..Default::default() - }), - None, - None, - ); - while let Some(result) = stream.next().await { - result.map_err(|err| { - Error::config(format!( - "failed to pull Docker {role} image '{image}': {err}", - )) - })?; - } - Ok(()) -} - -async fn ensure_runtime_image(docker: &Docker, image: &str, role: &str) -> CoreResult { - let local_image_present = docker.inspect_image(image).await.is_ok(); - if supervisor_image_should_refresh(image) { - info!( - image = image, - role, "Refreshing mutable Docker runtime image" - ); - if let Err(error) = pull_runtime_image(docker, image, role).await { - if !local_image_present { - return Err(error); - } - warn!( - image = image, - error = %error, - "failed to refresh mutable Docker runtime image; using the local image", - ); - } - } else if !local_image_present { - pull_runtime_image(docker, image, role).await?; - } - let inspect = docker.inspect_image(image).await.map_err(|error| { - Error::config(format!( - "failed to inspect Docker {role} image '{image}': {error}" - )) - })?; - inspect.id.filter(|id| !id.is_empty()).ok_or_else(|| { - Error::config(format!( - "Docker {role} image '{image}' has no immutable image ID" - )) - }) -} - -/// Create a short-lived container from `image`, stream out the sandbox -/// binary as a tar archive, and return the untarred file bytes. The -/// container is always removed, even on error paths. -async fn extract_sandbox_binary_bytes(docker: &Docker, image: &str) -> CoreResult> { - let bytes = - extract_runtime_path_archive(docker, image, SANDBOX_RUNTIME_IMAGE_BINARY_PATH, true) - .await?; - if !bytes.starts_with(b"\x7fELF") { - return Err(Error::config(format!( - "Docker sandbox runtime image '{image}' contains an invalid sandbox binary" - ))); - } - Ok(bytes) -} - -async fn extract_runtime_path_archive( - docker: &Docker, - image: &str, - path: &str, - extract_single_file: bool, -) -> CoreResult> { - let container_name = temp_extract_container_name(); - docker - .create_container( - Some( - CreateContainerOptionsBuilder::default() - .name(container_name.as_str()) - .build(), - ), - ContainerCreateBody { - image: Some(image.to_string()), - entrypoint: Some(vec![path.to_string()]), - cmd: Some(Vec::new()), - ..Default::default() - }, - ) - .await - .map_err(|err| { - Error::config(format!( - "failed to create extractor container from '{image}': {err}", - )) - })?; - - // Always tear down the extractor container, even if extraction fails. - let result = - download_path_from_container(docker, &container_name, path, extract_single_file).await; - if let Err(remove_err) = docker - .remove_container( - &container_name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await - { - warn!( - container = container_name, - error = %remove_err, - "Failed to remove runtime image extractor container", - ); - } - result -} - -async fn download_path_from_container( - docker: &Docker, - container_name: &str, - path: &str, - extract_single_file: bool, -) -> CoreResult> { - let options = DownloadFromContainerOptionsBuilder::default() - .path(path) - .build(); - let mut stream = docker.download_from_container(container_name, Some(options)); - - let mut tar_bytes = Vec::new(); - while let Some(chunk) = stream.next().await { - let chunk: Bytes = chunk.map_err(|err| { - Error::config(format!( - "failed to read supervisor binary stream from '{container_name}': {err}", - )) - })?; - tar_bytes.extend_from_slice(&chunk); - } - - if extract_single_file { - extract_first_tar_entry(&tar_bytes).map_err(|err| { - Error::config(format!( - "failed to extract supervisor binary from tar archive returned by '{container_name}': {err}", - )) - }) - } else { - Ok(tar_bytes) - } -} - -fn canonicalize_existing_file(path: &Path, description: &str) -> CoreResult { - if !path.is_file() { - return Err(Error::config(format!( - "{description} '{}' does not exist or is not a file", - path.display() - ))); - } - std::fs::canonicalize(path).map_err(|err| { - Error::config(format!( - "failed to resolve {description} '{}': {err}", - path.display() - )) - }) -} - -fn docker_guest_tls_configured(docker_config: &DockerComputeConfig) -> bool { - docker_config.guest_tls_ca.is_some() -} - -fn default_docker_supervisor_grpc_endpoint(gateway_port: u16, tls: bool) -> String { - let scheme = if tls { "https" } else { "http" }; - format!("{scheme}://127.0.0.1:{gateway_port}") -} - -fn default_docker_bridge_endpoint( - gateway_bind_address: SocketAddr, - tls: bool, - desktop: bool, -) -> Option { - let scheme = if tls { "https" } else { "http" }; - if desktop || gateway_bind_address.ip().is_unspecified() { - Some(format!( - "{scheme}://{HOST_DOCKER_INTERNAL}:{}", - gateway_bind_address.port() - )) - } else if !gateway_bind_address.ip().is_loopback() { - Some(format!("{scheme}://{gateway_bind_address}")) - } else { - None - } -} - -fn validate_docker_host_gateway_ip( - ip: IpAddr, - mode: DockerSupervisorNetworkMode, -) -> CoreResult { - let normalized = match ip { - IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or(IpAddr::V6(ip), IpAddr::V4), - ip @ IpAddr::V4(_) => ip, - }; - if normalized.is_unspecified() - || normalized.is_multicast() - || (mode == DockerSupervisorNetworkMode::Bridge && normalized.is_loopback()) - || matches!(normalized, IpAddr::V4(ip) if ip.is_link_local() || ip.is_broadcast()) - || matches!(normalized, IpAddr::V6(ip) if ip.is_unicast_link_local()) - { - return Err(Error::config(format!( - "invalid Docker host_gateway_ip '{ip}' for {mode:?} networking" - ))); - } - Ok(normalized) -} - -fn docker_host_gateway_resolver_body(image: &str, namespace: &str) -> ContainerCreateBody { - ContainerCreateBody { - image: Some(image.to_string()), - user: Some(format!("{SUPERVISOR_UID}:{SUPERVISOR_GID}")), - entrypoint: Some(vec![SUPERVISOR_IMAGE_CONTROL_BINARY_PATH.to_string()]), - cmd: Some(vec!["--help".to_string()]), - labels: Some(HashMap::from([ - ( - LABEL_MANAGED_BY.to_string(), - LABEL_MANAGED_BY_VALUE.to_string(), - ), - (LABEL_SANDBOX_NAMESPACE.to_string(), namespace.to_string()), - ( - LABEL_ISOLATION_ROLE.to_string(), - LABEL_ISOLATION_ROLE_STAGING.to_string(), - ), - ])), - host_config: Some(HostConfig { - network_mode: Some("none".to_string()), - extra_hosts: Some(vec![format!("{HOST_OPEN_SHELL_INTERNAL}:host-gateway")]), - cap_drop: Some(vec!["ALL".to_string()]), - security_opt: Some(vec!["no-new-privileges:true".to_string()]), - readonly_rootfs: Some(true), - ..Default::default() - }), - ..Default::default() - } -} - -fn parse_docker_host_gateway_hosts(contents: &[u8]) -> CoreResult { - let hosts = std::str::from_utf8(contents).map_err(|error| { - Error::config(format!( - "Docker host-gateway hosts file is not UTF-8: {error}" - )) - })?; - let mut addresses = std::collections::BTreeSet::new(); - for line in hosts.lines() { - let mut fields = line.split('#').next().unwrap_or("").split_whitespace(); - let Some(address) = fields.next() else { - continue; - }; - if fields.any(|host| host.eq_ignore_ascii_case(HOST_OPEN_SHELL_INTERNAL)) { - addresses.insert(address.parse::().map_err(|error| { - Error::config(format!("invalid Docker host-gateway hosts entry: {error}")) - })?); - } - } - let ipv4 = addresses - .iter() - .copied() - .filter(IpAddr::is_ipv4) - .collect::>(); - let candidates = if ipv4.is_empty() { - addresses.into_iter().collect::>() - } else { - ipv4 - }; - let [ip] = candidates.as_slice() else { - return Err(Error::config( - "Docker host-gateway resolver did not return one unique address per family", - )); - }; - validate_docker_host_gateway_ip(*ip, DockerSupervisorNetworkMode::Bridge) -} - -/// Resolve once at driver construction; all sandbox launches reuse the cached pin. -async fn resolve_docker_host_gateway( - docker: &Docker, - image: &str, - namespace: &str, -) -> CoreResult { - let name = format!("{}-host-gateway", temp_extract_container_name()); - let result = tokio::time::timeout(HOST_GATEWAY_RESOLUTION_TIMEOUT, async { - docker - .create_container( - Some( - CreateContainerOptionsBuilder::default() - .name(name.as_str()) - .build(), - ), - docker_host_gateway_resolver_body(image, namespace), - ) - .await - .map_err(|error| { - Error::config(format!("create Docker host-gateway resolver: {error}")) - })?; - docker.start_container(&name, None).await.map_err(|error| { - Error::config(format!("start Docker host-gateway resolver: {error}")) - })?; - let mut wait = docker.wait_container( - &name, - None::, - ); - let status = wait - .next() - .await - .ok_or_else(|| Error::config("Docker host-gateway resolver wait ended"))? - .map_err(|error| { - Error::config(format!("wait for Docker host-gateway resolver: {error}")) - })?; - if status.status_code != 0 { - return Err(Error::config(format!( - "Docker host-gateway resolver exited with status {}", - status.status_code - ))); - } - let hosts = download_path_from_container(docker, &name, "/etc/hosts", true).await?; - parse_docker_host_gateway_hosts(&hosts) - }) - .await - .map_err(|_| Error::config("Docker host-gateway resolution timed out")) - .and_then(std::convert::identity); - - // Remove by the unique name even after a timed-out create request. - let cleanup = tokio::time::timeout( - HOST_GATEWAY_CLEANUP_TIMEOUT, - docker.remove_container( - &name, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ), - ) - .await - .map_err(|_| { - Error::config(format!( - "cleanup Docker host-gateway resolver '{name}' timed out" - )) - }) - .and_then(|removed| match removed { - Ok(()) - | Err(BollardError::DockerResponseServerError { - status_code: 404, .. - }) => Ok(()), - Err(error) => Err(Error::config(format!( - "remove Docker host-gateway resolver '{name}': {error}" - ))), - }); - if let Err(error) = &cleanup { - warn!(container = %name, %error, "Failed to clean up Docker host-gateway resolver"); - } - let ip = result?; - cleanup?; - Ok(ip) -} - -fn docker_supervisor_networking( - config: &DockerDriverRuntimeConfig, -) -> Result<(DockerSupervisorNetworkMode, String), Status> { - let mode = match config.supervisor_network_mode { - DockerSupervisorNetworkMode::Auto => DockerSupervisorNetworkMode::Host, - mode => mode, - }; - let endpoint = if mode == DockerSupervisorNetworkMode::Bridge - && !config.supervisor_endpoint_explicit - { - config.bridge_default_endpoint.clone().ok_or_else(|| Status::failed_precondition( - "Docker bridge supervisor cannot reach a Linux gateway bound only to loopback; configure a bridge-reachable gateway bind_address and grpc_endpoint, or use supervisor_network_mode = 'host' when the runtime permits host networking", - ))? - } else { - config.supervisor_grpc_endpoint.clone() - }; - if mode == DockerSupervisorNetworkMode::Bridge { - let url = Url::parse(&endpoint).map_err(|error| { - Status::failed_precondition(format!("invalid Docker supervisor endpoint: {error}")) - })?; - if matches!(url.host(), Some(url::Host::Domain(host)) if host.eq_ignore_ascii_case("localhost")) - || matches!(url.host(), Some(url::Host::Ipv4(ip)) if ip.is_loopback() || ip.is_unspecified()) - || matches!(url.host(), Some(url::Host::Ipv6(ip)) if ip.is_loopback() || ip.is_unspecified()) - { - return Err(Status::failed_precondition( - "Docker bridge supervisor grpc_endpoint must be reachable outside the gateway's loopback namespace; use host.docker.internal or a reachable gateway address", - )); - } - } - Ok((mode, endpoint)) -} - -pub(crate) fn docker_guest_tls_paths( - docker_config: &DockerComputeConfig, -) -> CoreResult> { - let tls_flags_provided = docker_config.guest_tls_ca.is_some() - || docker_config.guest_tls_cert.is_some() - || docker_config.guest_tls_key.is_some(); - - if docker_config.guest_tls_cert.is_some() || docker_config.guest_tls_key.is_some() { - return Err(Error::config( - "guest_tls_cert and guest_tls_key are no longer supported; sandboxes authenticate to the gateway with bearer tokens", - )); - } - - if !docker_config.grpc_endpoint.starts_with("https://") { - if tls_flags_provided { - return Err(Error::config(format!( - "guest_tls_ca was provided but grpc_endpoint is '{}'; TLS materials require an https:// endpoint", - docker_config.grpc_endpoint, - ))); - } - return Ok(None); - } - - if docker_config.guest_tls_ca.is_none() { - return Err(Error::config( - "docker compute driver requires guest_tls_ca when grpc_endpoint uses https://", - )); - } - - let Some(ca) = docker_config.guest_tls_ca.clone() else { - return Err(Error::config( - "guest_tls_ca is required when Docker sandbox TLS materials are configured", - )); - }; - Ok(Some(DockerGuestTlsPaths { - ca: canonicalize_existing_file(&ca, "docker TLS CA certificate")?, - })) -} - -fn is_not_found_error(err: &BollardError) -> bool { - matches!( - err, - BollardError::DockerResponseServerError { - status_code: 404, - .. - } - ) -} - -fn is_removal_in_progress_error(err: &BollardError) -> bool { - matches!( - err, - BollardError::DockerResponseServerError { - status_code: 409, - message, - } if message.contains("removal of container") && message.contains("is already in progress") - ) -} - -fn is_not_modified_error(err: &BollardError) -> bool { - matches!( - err, - BollardError::DockerResponseServerError { - status_code: 304, - .. - } - ) -} - -fn create_status_from_docker_error(operation: &str, err: BollardError) -> Status { - if matches!( - err, - BollardError::DockerResponseServerError { - status_code: 409, - .. - } - ) { - Status::already_exists("sandbox already exists") - } else { - internal_status(operation, err) - } -} - -fn internal_status(operation: &str, err: BollardError) -> Status { - Status::internal(format!("{operation} failed: {err}")) -} - -#[cfg(test)] -mod tests; diff --git a/crates/openshell-driver-docker/src/main.rs b/crates/openshell-driver-docker/src/main.rs deleted file mode 100644 index 3f94fd0855..0000000000 --- a/crates/openshell-driver-docker/src/main.rs +++ /dev/null @@ -1,132 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use std::net::SocketAddr; -use std::path::PathBuf; - -use clap::Parser; -use miette::{IntoDiagnostic, Result}; -use openshell_core::VERSION; -use openshell_core::proto::compute::v1::compute_driver_configuration_updates_server::ComputeDriverConfigurationUpdatesServer; -use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; -use openshell_core::sandbox_env::SupervisorOtlpArgs; -use openshell_driver_docker::{ComputeDriverService, DockerComputeConfig, DockerComputeDriver}; -use tracing::info; - -mod serve; - -#[derive(Debug, Parser)] -#[command(name = "openshell-driver-docker", version = VERSION)] -struct Args { - /// Override the operator admission policy in the driver TOML file. - #[arg(long, env = "OPENSHELL_DRIVER_ADMISSION_CONFIG_JSON")] - admission_config_json: Option, - /// Public compute-driver Unix socket used by the gateway. - #[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_SOCKET")] - bind_socket: PathBuf, - - /// TOML file containing a serialized `DockerComputeConfig` table. - #[arg(long, env = "OPENSHELL_DOCKER_DRIVER_CONFIG")] - config: PathBuf, - - /// OCI image containing the `openshell-sandbox` runtime binary. - #[arg(long, env = openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV)] - sandbox_runtime_image: Option, - - /// OCI image containing the `openshell-supervisor` control binary. - #[arg(long, env = openshell_core::config::SUPERVISOR_IMAGE_ENV)] - supervisor_image: Option, - - /// Gateway listener address used to derive the supervisor endpoint. - #[arg( - long, - env = "OPENSHELL_GATEWAY_BIND", - default_value = "127.0.0.1:50051" - )] - gateway_bind: SocketAddr, - - #[arg(long, env = "OPENSHELL_LOG_LEVEL", default_value = "info")] - log_level: String, - - #[command(flatten)] - otlp: SupervisorOtlpArgs, - - #[arg(long, env = "OPENSHELL_GATEWAY_NAME")] - gateway_name: Option, -} - -#[tokio::main] -async fn main() -> Result<()> { - if let Some(code) = serve::dispatch().await { - std::process::exit(code); - } - let args = Args::parse(); - let _tracing = openshell_otel::install_driver_tracing( - openshell_driver_docker::otel_tracing::TRACING, - openshell_otel::DriverTracingConfig { - endpoint: args.otlp.endpoint.as_deref(), - protocol: args.otlp.protocol.into(), - ca_file: args.otlp.ca_file.as_deref(), - cert_file: args.otlp.cert_file.as_deref(), - key_file: args.otlp.key_file.as_deref(), - gateway_name: args.gateway_name.as_deref(), - service_version: VERSION, - log_level: &args.log_level, - ansi: openshell_core::color::stdout_ansi(), - }, - ); - args.otlp.warn_deprecated(); - - let supervisor_otlp = args.otlp.supervisor_otlp(); - let config_source = std::fs::read_to_string(&args.config).into_diagnostic()?; - let mut docker_config: DockerComputeConfig = - toml::from_str(&config_source).into_diagnostic()?; - if let Some(policy) = args.admission_config_json { - docker_config.allow_driver_config = policy.allow_driver_config; - docker_config.resource_admission = policy.resource_admission; - } - if let Some(image) = args.sandbox_runtime_image { - docker_config.sandbox_runtime_image = Some(image); - } - if let Some(image) = args.supervisor_image { - docker_config.supervisor_image = Some(image); - } - docker_config.supervisor_otlp = supervisor_otlp; - docker_config.supervisor_gateway_name = args.gateway_name.clone(); - let driver = DockerComputeDriver::new(args.gateway_bind, &args.log_level, &docker_config, None) - .await - .into_diagnostic()?; - - let listener = openshell_core::external_driver_socket::bind_private(&args.bind_socket) - .map_err(|err| miette::miette!("{err}"))?; - let _cleanup = - openshell_core::external_driver_socket::SocketCleanup::new(args.bind_socket.clone()); - info!(socket = %args.bind_socket.display(), "Starting Docker compute driver"); - let service = ComputeDriverService::new(driver); - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(ComputeDriverServer::new(service.clone())) - .add_service(ComputeDriverConfigurationUpdatesServer::new(service)) - .serve_with_incoming_shutdown( - openshell_core::external_driver_socket::SameUidUnixIncoming::new(listener), - shutdown_signal(), - ) - .await - .into_diagnostic() -} - -async fn shutdown_signal() { - let terminate = async { - match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { - Ok(mut signal) => { - signal.recv().await; - } - Err(_) => std::future::pending::<()>().await, - } - }; - tokio::select! { - _ = tokio::signal::ctrl_c() => {} - () = terminate => {} - } - info!("Received shutdown signal, draining in-flight requests"); -} diff --git a/crates/openshell-driver-docker/src/otel_tracing.rs b/crates/openshell-driver-docker/src/otel_tracing.rs deleted file mode 100644 index 03090c2eda..0000000000 --- a/crates/openshell-driver-docker/src/otel_tracing.rs +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! OpenTelemetry tracing identity for the Docker compute driver. - -pub const TRACING: openshell_otel::ComputeDriverTracing = openshell_otel::compute_driver_tracing!(); - -#[cfg(test)] -mod tests { - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn driver_spans_reach_otlp_collector_with_resource_identity() { - openshell_otel_test_support::assert_compute_driver_tracing( - super::TRACING, - openshell_core::VERSION, - "docker.schedule_sandbox", - ) - .await; - } -} diff --git a/crates/openshell-driver-docker/src/serve.rs b/crates/openshell-driver-docker/src/serve.rs deleted file mode 100644 index b2901a007b..0000000000 --- a/crates/openshell-driver-docker/src/serve.rs +++ /dev/null @@ -1,315 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! The launched-driver commands: `serve` and `preflight`. -//! -//! The gateway starts `serve` with bootstrap arguments only and the operator's -//! `[openshell.drivers.docker]` table on stdin, then delivers gateway-owned -//! metadata with the `Configure` RPC. Until `Configure` succeeds the driver -//! creates no Docker volumes, networks or containers, and both of its gRPC -//! services answer `UNAVAILABLE`. - -use std::path::PathBuf; - -use clap::Parser; -use openshell_core::VERSION; -use openshell_core::proto::compute::v1::compute_driver_configuration_updates_server::ComputeDriverConfigurationUpdatesServer; -use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; -use openshell_driver_docker::launch::{check_backend, settings_from_table}; -use openshell_driver_docker::{ComputeDriverService, DockerComputeConfig, DockerComputeDriver}; -use openshell_driver_sdk::launch::{ConfigureRequest, Deferred, Launch, LaunchInfo}; -use openshell_driver_sdk::{GatewayContext, StartResult}; -use tonic::Status; -use tracing::info; - -/// Bootstrap arguments the gateway passes to `serve`. They are frozen for -/// protocol version 1. -#[derive(Parser, Debug)] -#[command(name = "openshell-driver-docker serve")] -struct ServeArgs { - #[arg(long)] - bind_socket: PathBuf, - - #[arg(long)] - expected_peer_pid: u32, - - #[arg(long, default_value = "info")] - log_level: String, -} - -/// Run `serve` or `preflight` when that is the first argument and return the -/// process exit code. Any other invocation returns `None` and takes the -/// standalone path. -pub async fn dispatch() -> Option { - let args: Vec = std::env::args().collect(); - match args.get(1)?.as_str() { - "serve" => { - let parsed = ServeArgs::parse_from( - std::iter::once("openshell-driver-docker serve".to_string()) - .chain(args.into_iter().skip(2)), - ); - Some(serve(parsed).await) - } - "preflight" => Some(preflight()), - _ => None, - } -} - -fn read_settings() -> Result { - let table = openshell_driver_sdk::read_stdin_table() - .map_err(|error| StartResult::invalid_config(format!("read driver table: {error}")))?; - settings_from_table(&table).map_err(StartResult::invalid_config) -} - -fn preflight() -> i32 { - match read_settings() { - Ok(_) => 0, - Err(result) => result.report(), - } -} - -async fn serve(args: ServeArgs) -> i32 { - let tracing = openshell_otel::install_deferred_driver_tracing( - openshell_driver_docker::otel_tracing::TRACING, - &args.log_level, - openshell_core::color::stdout_ansi(), - ); - match run(args, tracing).await { - Ok(()) => 0, - Err(result) => result.report(), - } -} - -async fn run( - args: ServeArgs, - tracing: openshell_otel::DeferredDriverTracing, -) -> Result<(), StartResult> { - let settings = read_settings()?; - openshell_driver_sdk::check_backend_within("Docker", check_backend(&settings)).await?; - - let listener = openshell_core::external_driver_socket::bind_private(&args.bind_socket) - .map_err(StartResult::error)?; - let _cleanup = - openshell_core::external_driver_socket::SocketCleanup::new(args.bind_socket.clone()); - - let log_level = args.log_level.clone(); - let launch = Launch::new( - LaunchInfo { - driver_name: "docker".to_string(), - driver_version: VERSION.to_string(), - features: Vec::new(), - }, - move |request| { - let settings = settings.clone(); - let tracing = tracing.clone(); - let log_level = log_level.clone(); - async move { apply_configure(settings, &log_level, &tracing, request).await } - }, - ); - let shutdown = launch.shutdown(); - #[cfg(unix)] - openshell_driver_sdk::watch_parent(args.expected_peer_pid, shutdown.clone()); - // One configured service backs both gRPC services. - let compute = Deferred::new(launch.configured(), |service: &ComputeDriverService| { - ComputeDriverServer::new(service.clone()) - }); - let configuration_updates = - Deferred::new(launch.configured(), |service: &ComputeDriverService| { - ComputeDriverConfigurationUpdatesServer::new(service.clone()) - }); - - info!(socket = %args.bind_socket.display(), "Starting Docker compute driver"); - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(launch.into_server()) - .add_service(compute) - .add_service(configuration_updates) - .serve_with_incoming_shutdown( - openshell_core::external_driver_socket::SameUidUnixIncoming::new(listener) - .expecting_peer_pid(args.expected_peer_pid), - openshell_driver_sdk::stop_when_released( - shutdown, - crate::shutdown_signal(), - openshell_driver_sdk::EXTERNAL_STOP_GRACE, - ), - ) - .await - .map_err(|error| StartResult::error(format!("serve: {error}"))) -} - -/// Build the driver from the operator's settings and the gateway's metadata. -async fn apply_configure( - settings: DockerComputeConfig, - log_level: &str, - tracing: &openshell_otel::DeferredDriverTracing, - request: ConfigureRequest, -) -> Result { - let gateway = GatewayContext::try_from(&request.gateway.clone().unwrap_or_default())?; - if let Some(export) = openshell_driver_sdk::deferred_export_config( - request.telemetry.as_ref(), - gateway.gateway_name.as_deref(), - VERSION, - )? && let Err(error) = tracing.enable_export(export) - { - tracing::error!(%error, "OTLP exporting could not be started"); - } - let supervisor_otlp = openshell_driver_sdk::supervisor_otlp(request.telemetry.as_ref())?; - let network_trust = openshell_driver_sdk::load_network_trust(request.network_trust.as_ref())?; - let admission = - openshell_driver_sdk::admission_from_json(&request.resource_admission_policy_json)?; - let (config, bind_address) = driver_config( - settings, - &gateway, - request.image_overrides.as_ref(), - supervisor_otlp, - &admission, - )?; - let driver = DockerComputeDriver::new(bind_address, log_level, &config, network_trust) - .await - .map_err(|error| Status::internal(error.to_string()))?; - Ok(ComputeDriverService::new(driver)) -} - -/// The driver configuration for `settings` and the gateway's metadata, and -/// the gateway's listener. The gateway supplies the CA and the admission -/// policy, which the table cannot set. Image overrides win over the table, as -/// the environment did when the gateway built the configuration itself. -fn driver_config( - mut settings: DockerComputeConfig, - gateway: &GatewayContext, - images: Option<&openshell_driver_sdk::launch::ImageOverrides>, - supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, - admission: &openshell_core::resource_admission::DriverAdmissionConfig, -) -> Result<(DockerComputeConfig, std::net::SocketAddr), Status> { - let bind_address = gateway - .bind_address - .ok_or_else(|| Status::invalid_argument("the gateway did not send its bind address"))?; - settings.guest_tls_ca.clone_from(&gateway.tls_ca_path); - if openshell_driver_sdk::endpoint_uses_tls(&settings.grpc_endpoint) - && settings.guest_tls_ca.is_none() - { - return Err(Status::invalid_argument( - "grpc_endpoint uses https:// but the gateway supplied no CA path", - )); - } - settings.allow_driver_config = admission.allow_driver_config; - settings.resource_admission = admission.resource_admission.clone(); - if let Some(images) = images { - if let Some(image) = &images.sandbox_runtime_image { - settings.sandbox_runtime_image = Some(image.clone()); - } - if let Some(image) = &images.supervisor_image { - settings.supervisor_image = Some(image.clone()); - } - } - settings.supervisor_otlp = supervisor_otlp; - settings - .supervisor_gateway_name - .clone_from(&gateway.gateway_name); - Ok((settings, bind_address)) -} - -#[cfg(test)] -mod tests { - use openshell_core::resource_admission::DriverAdmissionConfig; - use openshell_driver_sdk::launch::ImageOverrides; - - use super::*; - - fn gateway(bind: Option<&str>, ca: Option<&str>) -> GatewayContext { - GatewayContext { - gateway_port: Some(8080), - tls_ca_path: ca.map(PathBuf::from), - gateway_name: Some("gw".to_string()), - bind_address: bind.map(|address| address.parse().unwrap()), - } - } - - fn build( - settings: DockerComputeConfig, - gateway: &GatewayContext, - images: Option<&ImageOverrides>, - admission: &DriverAdmissionConfig, - ) -> Result<(DockerComputeConfig, std::net::SocketAddr), Status> { - driver_config( - settings, - gateway, - images, - openshell_core::sandbox_env::SupervisorOtlp::default(), - admission, - ) - } - - #[test] - fn the_gateway_supplies_the_listener_name_ca_and_admission() { - let admission = DriverAdmissionConfig { - allow_driver_config: true, - ..DriverAdmissionConfig::default() - }; - let (config, bind) = build( - DockerComputeConfig::default(), - &gateway(Some("127.0.0.1:8080"), Some("/ca.pem")), - None, - &admission, - ) - .unwrap(); - assert_eq!(bind, "127.0.0.1:8080".parse().unwrap()); - assert_eq!(config.guest_tls_ca, Some("/ca.pem".into())); - assert_eq!(config.supervisor_gateway_name.as_deref(), Some("gw")); - assert!(config.allow_driver_config); - } - - #[test] - fn the_bind_address_is_required() { - let status = build( - DockerComputeConfig::default(), - &gateway(None, None), - None, - &DriverAdmissionConfig::default(), - ) - .unwrap_err(); - assert_eq!(status.code(), tonic::Code::InvalidArgument); - } - - #[test] - fn an_https_endpoint_needs_the_gateway_ca() { - let table = settings_from_table("grpc_endpoint = \"https://host.test:9\"").unwrap(); - let admission = DriverAdmissionConfig::default(); - let status = build( - table.clone(), - &gateway(Some("127.0.0.1:8080"), None), - None, - &admission, - ) - .unwrap_err(); - assert_eq!(status.code(), tonic::Code::InvalidArgument); - build( - table, - &gateway(Some("127.0.0.1:8080"), Some("/ca.pem")), - None, - &admission, - ) - .unwrap(); - } - - #[test] - fn image_overrides_win_over_the_table_as_the_environment_did() { - let table = settings_from_table( - "sandbox_runtime_image = \"table-runtime\"\nsupervisor_image = \"table-supervisor\"", - ) - .unwrap(); - let overrides = ImageOverrides { - sandbox_runtime_image: Some("env-runtime".to_string()), - supervisor_image: None, - }; - let (config, _) = build( - table, - &gateway(Some("127.0.0.1:8080"), None), - Some(&overrides), - &DriverAdmissionConfig::default(), - ) - .unwrap(); - assert_eq!(config.sandbox_runtime_image.as_deref(), Some("env-runtime")); - assert_eq!(config.supervisor_image.as_deref(), Some("table-supervisor")); - } -} diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs deleted file mode 100644 index c86e2d068b..0000000000 --- a/crates/openshell-driver-docker/src/tests.rs +++ /dev/null @@ -1,4718 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use super::*; -use openshell_core::driver_utils::{ - LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, - LABEL_SANDBOX_NAMESPACE, -}; -use openshell_core::jwt::{ - CredentialEpoch, SandboxLaunchAuthentication, SecretJwt, SessionVerificationKey, - SupervisorAuthBundle, -}; -use openshell_core::progress::{ - PROGRESS_ACTIVE_DETAIL_KEY, PROGRESS_ACTIVE_STEP_KEY, PROGRESS_COMPLETE_LABEL_KEY, - PROGRESS_COMPLETE_STEP_KEY, PROGRESS_STEP_PULLING_IMAGE, PROGRESS_STEP_REQUESTING_SANDBOX, - PROGRESS_STEP_STARTING_SANDBOX, -}; -use openshell_core::proto::compute::v1::{ - DriverResourceRequirements, DriverSandboxSpec, DriverSandboxTemplate, GpuResourceRequirements, - ResourceRequirements, WorkloadIdentityRequest, -}; -use std::fs; -use std::io::Read as _; -use std::sync::Arc; -use tempfile::TempDir; - -#[test] -fn startup_error_log_tails_fit_grpc_header_budget() { - // Multibyte text exercises both the UTF-8 cut and worst-case gRPC message - // percent encoding. Preserve the supervisor's final diagnostic. - let logs = format!("{}\nstartup timed out", "🦀".repeat(8192)); - let message = format!( - "Docker supervisor exited before becoming ready{}", - format_log_tail(&logs), - ); - assert_eq!(message.matches("[truncated]").count(), 1); - assert_eq!(message.matches("startup timed out").count(), 1); - let response = Status::unavailable(message).into_http::<()>(); - let header_bytes: usize = response - .headers() - .iter() - .map(|(name, value)| name.as_str().len() + value.as_bytes().len() + 32) - .sum(); - assert!( - header_bytes < 16 * 1024, - "status headers: {header_bytes} bytes" - ); - assert_eq!(format_log_tail("small error"), "; log tail: small error"); - assert!(format_log_tail("").is_empty()); -} - -pub fn test_launch_authentication() -> Vec { - serde_json::to_vec(&SandboxLaunchAuthentication { - supervisor: SupervisorAuthBundle { - session_id: openshell_core::SandboxSessionId::new(), - runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( - "generation-1", - ) - .unwrap(), - session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), - auth_epoch: CredentialEpoch::new(1).unwrap(), - gateway_token: SecretJwt::parse("gateway.token.value").unwrap(), - gateway_expires_at: i64::MAX, - sandbox_token: SecretJwt::parse("sandbox.token.value").unwrap(), - sandbox_expires_at: i64::MAX, - ssh_host_private_key: None, - traces_otlp_headers: None, - ocsf_otlp_headers: None, - agent_otlp_headers: None, - otlp_tls: Vec::new(), - traces_otlp_tls: None, - ocsf_otlp_tls: None, - agent_otlp_tls: None, - }, - gateway_id: "gateway-test".to_string(), - verification_keys: vec![SessionVerificationKey { - key_id: "test-key".to_string(), - public_key_pem: b"public-key".to_vec(), - }], - }) - .unwrap() -} - -#[tokio::test] -async fn restart_rotates_bootstrap_descriptor_and_provisioning_evidence_together() { - let config = runtime_config(); - let sandbox_id = format!("restart-{}", openshell_core::SandboxSessionId::new()); - let directory = docker_boundary_state_dir_by_id(&sandbox_id, &config).unwrap(); - fs::create_dir_all(&directory).unwrap(); - let mut authentication: SandboxLaunchAuthentication = - serde_json::from_slice(&test_launch_authentication()).unwrap(); - let tls = generate_sandbox_tls_material(authentication.supervisor.session_id).unwrap(); - let provisioned = isolation::DockerBoundarySpec { - boundary_id: sandbox_id.clone(), - generation: authentication.supervisor.runtime_generation.to_string(), - session_id: authentication.supervisor.session_id, - session_rotation: authentication.supervisor.session_rotation, - auth_epoch: authentication.supervisor.auth_epoch, - gateway_id: authentication.gateway_id.clone(), - verification_keys: gateway_verification_keys(&authentication.verification_keys).unwrap(), - container_id: "container-test".into(), - image_identity: "image-test".into(), - gpu_requested: false, - listener_socket: BOUNDARY_SOCKET_MOUNT_PATH.into(), - control_socket: BOUNDARY_SOCKET_MOUNT_PATH.into(), - sandbox_tls: SandboxTlsServerConfig { - certificate_chain_path: BOUNDARY_CERTIFICATE_MOUNT_PATH.into(), - private_key_path: BOUNDARY_PRIVATE_KEY_MOUNT_PATH.into(), - }, - supervisor_tls: SandboxTlsClientConfig { - server_name: tls.server_name, - trust_anchor_pem: tls.trust_anchor_pem, - }, - host_gateway_ip: None, - workload_identity: ResolvedWorkloadIdentity::new( - 1000, - 1000, - vec![], - "image".into(), - "image-test".into(), - ) - .unwrap(), - child_env: HashMap::new(), - } - .provision() - .unwrap(); - fs::write( - directory.join(BOUNDARY_CONFIG_FILE), - provisioned.boundary_config.encode().unwrap(), - ) - .unwrap(); - fs::write( - directory.join(RUNTIME_DESCRIPTOR_FILE), - provisioned - .runtime_descriptor - .backend_descriptor() - .unwrap() - .payload, - ) - .unwrap(); - let previous_evidence = provisioned.boundary_config.provisioning_evidence; - authentication.supervisor.runtime_generation = - openshell_core::sandbox_generation::SandboxGenerationId::parse("generation-2").unwrap(); - authentication.supervisor.session_id = openshell_core::SandboxSessionId::new(); - let encoded = serde_json::to_vec(&authentication).unwrap(); - refresh_docker_boundary_authentication(&sandbox_id, &config, &encoded) - .await - .unwrap(); - - let bootstrap: BoundaryConfig = - serde_json::from_slice(&fs::read(directory.join(BOUNDARY_CONFIG_FILE)).unwrap()).unwrap(); - // A restart keeps the original image identity even if the mutable - // template reference now names another image in the registry. - let sandbox = test_sandbox(); - let image_env = docker_workload_image_environment(&sandbox, &directory) - .await - .unwrap(); - assert!(image_env.contains(&format!( - "{}=image-test", - openshell_core::sandbox_env::CONTAINER_IMAGE_UID - ))); - assert!(image_env.contains(&format!( - "{}={}", - openshell_core::sandbox_env::CONTAINER_IMAGE, - sandbox_image(&sandbox).unwrap() - ))); - let descriptor = read_docker_runtime_descriptor(&sandbox_id, &config) - .await - .unwrap() - .unwrap(); - let supervisor: SupervisorAuthBundle = - serde_json::from_slice(&fs::read(directory.join(SUPERVISOR_AUTH_BUNDLE_FILE)).unwrap()) - .unwrap(); - assert_eq!(bootstrap.generation, "generation-2"); - assert_eq!(descriptor.generation, bootstrap.generation); - assert_eq!(supervisor.runtime_generation.as_str(), bootstrap.generation); - assert_eq!(bootstrap.session_id, descriptor.session_id); - assert_eq!(bootstrap.session_id, supervisor.session_id); - bootstrap - .provisioning_evidence - .validate("generation-2") - .unwrap(); - assert_eq!( - bootstrap.provisioning_evidence, - descriptor.provisioning_evidence - ); - assert_ne!( - bootstrap.provisioning_evidence.evidence_digest, - previous_evidence.evidence_digest - ); - assert_eq!( - bootstrap.resource_claims, - provisioned.runtime_descriptor.resource_claims - ); - // Retrying this launch keeps its generation/evidence binding stable. - refresh_docker_boundary_authentication(&sandbox_id, &config, &encoded) - .await - .unwrap(); - let retried = read_docker_runtime_descriptor(&sandbox_id, &config) - .await - .unwrap() - .unwrap(); - assert_eq!( - retried.provisioning_evidence, - descriptor.provisioning_evidence - ); - fs::remove_dir_all(directory).unwrap(); -} - -pub fn test_sandbox() -> DriverSandbox { - // Mirrors the gateway-supplied request: the public `Sandbox` API no - // longer carries `namespace`, so the gateway elides the field and the - // driver must source it from its own runtime config. - DriverSandbox { - id: "sbx-123".to_string(), - name: "demo".to_string(), - namespace: String::new(), - spec: Some(DriverSandboxSpec { - log_level: "debug".to_string(), - environment: HashMap::from([("SPEC_ENV".to_string(), "spec".to_string())]), - template: Some(DriverSandboxTemplate { - image: "nvcr.io/nvidia/base/ubuntu:24.04".to_string(), - agent_socket_path: String::new(), - labels: HashMap::new(), - environment: HashMap::from([("TEMPLATE_ENV".to_string(), "template".to_string())]), - ..Default::default() - }), - policy: None, - resource_requirements: None, - sandbox_token: String::new(), - command: Vec::new(), - tty: false, - await_main_process_attachment: false, - workload_identity: None, - launch_authentication: test_launch_authentication(), - ..Default::default() - }), - status: None, - workspace: String::new(), - } -} - -#[test] -fn admission_defaults_reject_even_gpu_driver_json_but_not_public_gpu_requests() { - let mut config = runtime_config(); - config.allow_driver_config = false; - config.resource_admission = - openshell_core::resource_admission::ResourceAdmissionConfig::default(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(Some(1))); - assert!(DockerComputeDriver::validate_sandbox(&sandbox, &config).is_ok()); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(cdi_devices_config(&["nvidia.com/gpu=0"])); - let error = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - config.allow_driver_config = true; - assert!(DockerComputeDriver::validate_sandbox(&sandbox, &config).is_ok()); -} - -#[test] -fn admission_blocks_unlabelable_bind_mount_even_when_bind_mounts_enabled() { - let mut config = runtime_config(); - config.enable_bind_mounts = true; - config.resource_admission = - openshell_core::resource_admission::ResourceAdmissionConfig::default(); - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some( - openshell_core::proto_struct::json_object_to_struct( - serde_json::json!({"mounts":[{"type":"bind","source":"/srv/data","target":"/data"}]}) - .as_object() - .unwrap() - .clone(), - ) - .unwrap(), - ); - let error = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - assert!(error.message().contains("no trusted label resolver")); -} - -fn cdi_devices_config(device_ids: &[&str]) -> prost_types::Struct { - list_string_driver_config("cdi_devices", device_ids) -} - -fn cdi_device_typo_config(device_ids: &[&str]) -> prost_types::Struct { - list_string_driver_config("cdi_device", device_ids) -} - -fn list_string_driver_config(field: &str, values: &[&str]) -> prost_types::Struct { - prost_types::Struct { - fields: std::iter::once(( - field.to_string(), - prost_types::Value { - kind: Some(prost_types::value::Kind::ListValue( - prost_types::ListValue { - values: values - .iter() - .map(|device_id| prost_types::Value { - kind: Some(prost_types::value::Kind::StringValue( - (*device_id).to_string(), - )), - }) - .collect(), - }, - )), - }, - )) - .collect(), - } -} - -fn gpu_resources(count: Option) -> ResourceRequirements { - ResourceRequirements { - gpu: Some(GpuResourceRequirements { count }), - } -} - -pub fn runtime_config() -> DockerDriverRuntimeConfig { - DockerDriverRuntimeConfig { - // Existing lifecycle fixtures exercise the explicitly opted-out contract. - allow_driver_config: true, - resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig { - enabled: false, - ..Default::default() - }, - default_image: "image:latest".to_string(), - image_pull_policy: ImagePullPolicy::IfNotPresent, - sandbox_namespace: "default".to_string(), - stop_timeout_secs: DEFAULT_STOP_TIMEOUT_SECS, - log_level: "info".to_string(), - sandbox_binary: Arc::new(b"\x7fELFtest".to_vec()), - supervisor_image_id: "sha256:supervisor-test".to_string(), - supervisor_grpc_endpoint: "https://host.openshell.internal:8443".to_string(), - supervisor_network_mode: DockerSupervisorNetworkMode::Host, - supervisor_endpoint_explicit: true, - bridge_default_endpoint: Some("https://host.docker.internal:8443".to_string()), - host_gateway_ip: None, - supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp::default(), - supervisor_gateway_name: None, - ssh_socket_path: openshell_core::container_paths::SSH_SOCKET_PATH.to_string(), - guest_tls: Some(DockerGuestTlsPaths { - ca: PathBuf::from("/tmp/ca.crt"), - }), - gpu: DockerGpuRuntimeCapabilities { - cdi_supported: false, - wsl_all_gpu_fallback_enabled: false, - }, - sandbox_pids_limit: openshell_core::config::default_sandbox_pids_limit(), - enable_bind_mounts: false, - workspace_storage: workspace::Storage::WritableLayer, - upstream_proxy: UpstreamProxyConfig::default(), - proxy_ca_bundle: None, - ipv6_egress: SupervisorIpv6EgressConfig::default(), - provider_spiffe_workload_api_socket: None, - app_armor_profile: Some(AppArmorProfile::Unconfined), - network_trust: None, - } -} - -fn write_test_proxy_ca_bundle(directory: &TempDir) -> PathBuf { - let tls = generate_sandbox_tls_material(openshell_core::SandboxSessionId::new()) - .expect("generate test proxy CA"); - let path = directory.path().join("proxy-ca.pem"); - fs::write(&path, tls.trust_anchor_pem).expect("write test proxy CA"); - path -} - -#[test] -fn docker_config_parses_operator_proxy_ca_bundle() { - let config: DockerComputeConfig = toml::from_str( - r#" -https_proxy = "https://proxy.corp.example:8443" -proxy_ca_bundle = "/etc/openshell/tls/proxy-ca.pem" -"#, - ) - .expect("parse Docker proxy CA configuration"); - - assert_eq!( - config.proxy_ca_bundle, - Some(PathBuf::from("/etc/openshell/tls/proxy-ca.pem")) - ); -} - -#[test] -fn docker_proxy_ca_bundle_validation_is_fail_closed() { - let directory = TempDir::new().expect("create CA directory"); - let ca_bundle = write_test_proxy_ca_bundle(&directory); - let gateway_bind_address = "127.0.0.1:17670".parse().unwrap(); - - let mut valid = DockerComputeConfig::default(); - valid.upstream_proxy.https_proxy = Some("http://proxy.corp.example:8080".to_string()); - valid.proxy_ca_bundle = Some(ca_bundle); - valid - .validate_configuration(gateway_bind_address) - .expect("a valid CA bundle is accepted with an HTTP interception proxy"); - - let mut without_proxy = valid.clone(); - without_proxy.upstream_proxy.https_proxy = None; - let error = without_proxy - .validate_configuration(gateway_bind_address) - .expect_err("a CA bundle without a proxy must fail"); - assert!(error.to_string().contains("proxy_ca_bundle"), "{error}"); - assert!(error.to_string().contains("https_proxy"), "{error}"); - - let mut empty_path = valid.clone(); - empty_path.proxy_ca_bundle = Some(PathBuf::new()); - let error = empty_path - .validate_configuration(gateway_bind_address) - .expect_err("an empty CA bundle path must fail"); - assert!(error.to_string().contains("must not be empty"), "{error}"); - - let mut missing = valid.clone(); - missing.proxy_ca_bundle = Some(directory.path().join("missing.pem")); - let error = missing - .validate_configuration(gateway_bind_address) - .expect_err("a missing CA bundle must fail"); - assert!(error.to_string().contains("could not be read"), "{error}"); - - let malformed_path = directory.path().join("malformed.pem"); - fs::write(&malformed_path, "not a certificate\n").unwrap(); - let mut malformed = valid; - malformed.proxy_ca_bundle = Some(malformed_path); - let error = malformed - .validate_configuration(gateway_bind_address) - .expect_err("a certificate-free CA bundle must fail"); - assert!(error.to_string().contains("no PEM certificate"), "{error}"); -} - -#[tokio::test] -async fn docker_constructor_rejects_proxy_ca_bundle_without_proxy() { - let directory = TempDir::new().expect("create CA directory"); - let mut config = DockerComputeConfig { - socket_path: Some(directory.path().join("unused-docker.sock")), - proxy_ca_bundle: Some(write_test_proxy_ca_bundle(&directory)), - ..DockerComputeConfig::default() - }; - config.upstream_proxy.https_proxy = None; - - let Err(error) = - DockerComputeDriver::new("127.0.0.1:17670".parse().unwrap(), "info", &config, None).await - else { - panic!("constructor must reject incoherent proxy CA configuration before Docker I/O"); - }; - - assert!(error.to_string().contains("proxy_ca_bundle"), "{error}"); - assert!(error.to_string().contains("https_proxy"), "{error}"); -} - -#[test] -fn docker_proxy_ca_bundle_uses_fixed_supervisor_path() { - let proxy = UpstreamProxyConfig { - https_proxy: Some("https://proxy.corp.example:8443".to_string()), - ..UpstreamProxyConfig::default() - }; - - let args = docker_upstream_proxy_cli_args(&proxy, true); - let option = args - .iter() - .position(|arg| arg == "--upstream-proxy-ca-bundle") - .expect("proxy CA option"); - assert_eq!( - args.get(option + 1).map(String::as_str), - Some(SUPERVISOR_PROXY_CA_BUNDLE_MOUNT_PATH) - ); - assert!( - !args.iter().any(|arg| arg.contains("/etc/openshell/tls")), - "gateway-host paths must not appear in supervisor argv: {args:?}" - ); - - let args = docker_upstream_proxy_cli_args(&proxy, false); - assert!(!args.iter().any(|arg| arg == "--upstream-proxy-ca-bundle")); -} - -#[test] -fn docker_proxy_ca_bundle_is_staged_in_supervisor_archive() { - let directory = TempDir::new().expect("create CA directory"); - let ca_bundle = write_test_proxy_ca_bundle(&directory); - let expected = fs::read_to_string(&ca_bundle).unwrap(); - let mut builder = tar::Builder::new(Vec::new()); - - append_docker_proxy_ca_bundle(&mut builder, Some(&ca_bundle)).expect("append proxy CA bundle"); - let archive = builder.into_inner().expect("finish proxy CA archive"); - let mut archive = tar::Archive::new(archive.as_slice()); - let mut entries = archive.entries().unwrap(); - let mut entry = entries.next().expect("proxy CA entry").unwrap(); - - assert_eq!( - entry.path().unwrap().as_ref(), - Path::new("upstream-proxy-ca-bundle.pem") - ); - assert_eq!(entry.header().uid().unwrap(), u64::from(SUPERVISOR_UID)); - assert_eq!(entry.header().gid().unwrap(), u64::from(SUPERVISOR_GID)); - assert_eq!(entry.header().mode().unwrap(), 0o644); - let mut actual = String::new(); - entry.read_to_string(&mut actual).unwrap(); - assert_eq!(actual, expected); - assert!(entries.next().is_none()); -} - -#[test] -fn sandbox_driver_config_cannot_override_proxy_ca_bundle() { - let config = runtime_config(); - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "proxy_ca_bundle": "/workload/controlled-ca.pem" - }))); - - let error = DockerComputeDriver::validate_sandbox(&sandbox, &config) - .expect_err("sandbox driver config must not accept proxy_ca_bundle"); - assert_eq!(error.code(), tonic::Code::InvalidArgument); - assert!(error.message().contains("unknown field"), "{error}"); - assert!(error.message().contains("proxy_ca_bundle"), "{error}"); -} - -pub fn test_workload_identity() -> ResolvedWorkloadIdentity { - ResolvedWorkloadIdentity::new( - 1234, - 1235, - vec![1236], - "test".to_string(), - "sha256:immutable".to_string(), - ) - .unwrap() -} - -fn json_struct(value: serde_json::Value) -> prost_types::Struct { - let serde_json::Value::Object(object) = value else { - panic!("expected JSON object"); - }; - openshell_core::proto_struct::json_object_to_struct(object) - .expect("test JSON must convert to a protobuf Struct") -} - -fn inspected_volume(driver: &str, options: HashMap) -> bollard::models::Volume { - bollard::models::Volume { - name: "openshell-test-volume".to_string(), - driver: driver.to_string(), - mountpoint: "/var/lib/docker/volumes/openshell-test-volume/_data".to_string(), - created_at: None, - status: None, - labels: HashMap::new(), - scope: None, - cluster_volume: None, - options, - usage_data: None, - } -} - -pub fn test_driver_with_config(config: DockerDriverRuntimeConfig) -> DockerComputeDriver { - let wsl_all_gpu_fallback_enabled = config.gpu.wsl_all_gpu_fallback_enabled; - DockerComputeDriver { - docker: Arc::new( - Docker::connect_with_http("http://127.0.0.1:2375", 1, bollard::API_DEFAULT_VERSION) - .expect("construct test Docker client"), - ), - config, - events: broadcast::channel(WATCH_BUFFER).0, - pending: Arc::new(Mutex::new(HashMap::new())), - gpu_selector: Arc::new(CdiGpuDefaultSelector::new( - CdiGpuInventory::default(), - wsl_all_gpu_fallback_enabled, - )), - lifecycle_event_fences: DockerLifecycleEventFences::default(), - control_processes: Arc::new(Mutex::new(HashMap::new())), - runtime_failures: Arc::new(Mutex::new(HashMap::new())), - image_update_gates: Arc::new(image_update::Gates::default()), - } -} - -#[test] -fn capabilities_report_static_resource_support() { - let mut config = runtime_config(); - let capabilities = test_driver_with_config(config.clone()).capabilities(); - let resources = capabilities.resource_capabilities.unwrap(); - assert!(resources.cpu.unwrap().limit_supported); - assert!(resources.memory.unwrap().limit_supported); - let gpu = resources.gpu.unwrap(); - assert!(!gpu.default_selection_supported); - assert!(!gpu.count_selection_supported); - - config.gpu.cdi_supported = true; - let gpu = test_driver_with_config(config) - .capabilities() - .resource_capabilities - .unwrap() - .gpu - .unwrap(); - assert!(gpu.default_selection_supported); - assert!(gpu.count_selection_supported); -} - -#[tokio::test] -async fn capabilities_reject_missing_gateway_metadata() { - let driver = test_driver_with_config(runtime_config()); - - let error = - ComputeDriver::get_capabilities(&driver, Request::new(GetCapabilitiesRequest::default())) - .await - .unwrap_err(); - - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!( - error - .message() - .contains("gateway did not provide protocol metadata") - ); -} - -#[tokio::test] -#[ignore = "requires a local Docker daemon; creates and removes only isolated test volumes"] -async fn live_docker_resource_admission_checks_native_volume_labels() { - let temporary = TempDir::new().unwrap(); - let suffix = temporary.path().file_name().unwrap().to_str().unwrap(); - let mut config = runtime_config(); - config.resource_admission = - openshell_core::resource_admission::ResourceAdmissionConfig::default(); - let mut driver = test_driver_with_config(config); - driver.docker = Arc::new(Docker::connect_with_local_defaults().unwrap()); - for (index, (workspace, approved)) in [ - (None, false), - (Some("other"), false), - (Some("team-a"), true), - ] - .into_iter() - .enumerate() - { - let name = format!("openshell-admission-{suffix}-{index}"); - assert!(driver.docker.inspect_volume(&name).await.is_err()); - let labels = workspace.map(|workspace| { - HashMap::from([ - ("openshell.ai/sandbox-attachable".into(), "true".into()), - ( - "openshell.ai/sandbox-attachable-workspace".into(), - workspace.into(), - ), - ]) - }); - driver - .docker - .create_volume(VolumeCreateRequest { - name: Some(name.clone()), - labels, - ..Default::default() - }) - .await - .unwrap(); - let mut results = Vec::new(); - for read_only in [true, false] { - let mounts = serde_json::from_value(serde_json::json!({"mounts":[{ - "type":"volume", "source":name, "target":"/external", "read_only":read_only - }]})) - .unwrap(); - let result = driver - .validate_user_volume_mounts_available(&mounts, "team-a") - .await; - if !approved { - assert!( - result - .as_ref() - .unwrap_err() - .message() - .contains(&format!("docker volume '{name}'")) - ); - } - results.push(result.is_ok()); - } - driver - .docker - .remove_volume( - &name, - None::, - ) - .await - .unwrap(); - assert_eq!(results, vec![approved; 2]); - } -} - -type TestDriverClient = - openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient< - tonic::transport::Channel, - >; - -fn request_with_traceparent(message: T) -> Request { - let mut request = Request::new(message); - request.metadata_mut().insert( - "traceparent", - "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" - .parse() - .unwrap(), - ); - request -} - -async fn standalone_traced_client() -> ( - TestDriverClient, - oneshot::Sender<()>, - JoinHandle>, -) { - use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let (shutdown, shutdown_rx) = oneshot::channel(); - let service = ComputeDriverService::new(test_driver_with_config(runtime_config())); - let server = tokio::spawn(async move { - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(ComputeDriverServer::new(service)) - .serve_with_incoming_shutdown( - tokio_stream::wrappers::TcpListenerStream::new(listener), - async { - let _ = shutdown_rx.await; - }, - ) - .await - }); - let client = TestDriverClient::connect(format!("http://{address}")) - .await - .unwrap(); - (client, shutdown, server) -} - -#[tokio::test] -async fn tracing_standalone_rpc_layer_propagates_context_and_records_errors() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let dispatch = tracing::Dispatch::new( - tracing_subscriber::registry().with(otel_tracing::TRACING.layer(&provider)), - ); - let _dispatch = tracing::dispatcher::set_default(&dispatch); - let (mut client, shutdown, server) = standalone_traced_client().await; - - client - .get_capabilities(request_with_traceparent(GetCapabilitiesRequest { - gateway: Some(openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - )), - })) - .await - .expect("capabilities should succeed"); - client - .validate_sandbox_create(request_with_traceparent(ValidateSandboxCreateRequest { - sandbox: None, - })) - .await - .expect_err("missing sandbox should fail"); - drop(client); - shutdown.send(()).unwrap(); - tokio::time::timeout(Duration::from_secs(5), server) - .await - .expect("standalone test server should stop") - .expect("standalone test server should not panic") - .expect("standalone test server should stop cleanly"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let capabilities = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/GetCapabilities") - .expect("capabilities RPC span"); - assert_eq!( - capabilities.span_context.trace_id().to_string(), - "4bf92f3577b34da6a3ce929d0e0e4736" - ); - assert_eq!(capabilities.parent_span_id.to_string(), "00f067aa0ba902b7"); - assert!(capabilities.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.method" - && attribute.value.to_string() == "openshell.compute.v1.ComputeDriver/GetCapabilities" - })); - assert!( - capabilities - .attributes - .iter() - .all(|attribute| attribute.key.as_str() != "rpc.service"), - "the current RPC semantic conventions integrate the service into rpc.method" - ); - let failed = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/ValidateSandboxCreate") - .expect("failed RPC span"); - assert!(matches!( - failed.status, - opentelemetry::trace::Status::Error { .. } - )); - provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn control_failure_overrides_running_container_readiness() { - let driver = test_driver_with_config(runtime_config()); - driver.runtime_failures.lock().await.insert( - "sbx-123".to_string(), - DockerRuntimeFailure { - reason: "ControlSupervisorExited", - message: "control exited unexpectedly".to_string(), - }, - ); - let mut sandbox = pending_sandbox_snapshot( - &test_sandbox(), - "default", - DriverCondition { - r#type: "Ready".to_string(), - status: "True".to_string(), - reason: "BackendReady".to_string(), - message: "Container is running".to_string(), - transition_time: None, - }, - false, - ); - - driver.apply_runtime_failure(&mut sandbox).await; - - let ready = sandbox - .status - .unwrap() - .conditions - .into_iter() - .find(|condition| condition.r#type == "Ready") - .expect("ready condition"); - assert_eq!(ready.status, "False"); - assert_eq!(ready.reason, "ControlSupervisorExited"); - assert!(ready.message.contains("control exited unexpectedly")); -} - -#[tokio::test] -async fn control_failure_does_not_hide_a_terminal_container_exit() { - let driver = test_driver_with_config(runtime_config()); - driver.runtime_failures.lock().await.insert( - "sbx-123".to_string(), - DockerRuntimeFailure { - reason: "ControlSupervisorExited", - message: "control exited unexpectedly".to_string(), - }, - ); - let mut sandbox = pending_sandbox_snapshot( - &test_sandbox(), - "default", - DriverCondition { - r#type: "Ready".to_string(), - status: "False".to_string(), - reason: CONDITION_EXITED.to_string(), - message: "Container exited".to_string(), - transition_time: None, - }, - false, - ); - - driver.apply_runtime_failure(&mut sandbox).await; - - let ready = sandbox - .status - .unwrap() - .conditions - .into_iter() - .find(|condition| condition.r#type == "Ready") - .expect("ready condition"); - assert_eq!(ready.reason, CONDITION_EXITED); -} - -#[tokio::test] -async fn tracing_in_process_service_preserves_the_driver_rpc_server_boundary() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::{Instrument as _, instrument::WithSubscriber as _}; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let gateway_exporter = InMemorySpanExporterBuilder::new().build(); - let gateway_provider = SdkTracerProvider::builder() - .with_simple_exporter(gateway_exporter.clone()) - .build(); - let driver_exporter = InMemorySpanExporterBuilder::new().build(); - let driver_provider = SdkTracerProvider::builder() - .with_simple_exporter(driver_exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry() - .with(openshell_otel::layer_excluding_target_prefixes( - &gateway_provider, - "gateway-test", - otel_tracing::TRACING.in_process_targets(), - )) - .with(otel_tracing::TRACING.in_process_layer(&driver_provider)); - let service = ComputeDriverService::new_in_process(test_driver_with_config(runtime_config())); - - async { - let gateway_span = tracing::info_span!( - target: "openshell_server::compute", - "driver", - otel.name = "openshell.compute.v1.ComputeDriver/GetCapabilities", - otel.kind = "client" - ); - ComputeDriver::get_capabilities( - &service, - Request::new(GetCapabilitiesRequest { - gateway: Some(openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - )), - }), - ) - .instrument(gateway_span) - .await?; - - let unrelated = tracing::info_span!( - target: "openshell_driver_kubernetes::compute", - "kubernetes.operation" - ); - drop(unrelated.enter()); - drop(unrelated); - let selected_backend = tracing::info_span!( - target: "openshell_driver_docker::compute", - "docker.operation" - ); - drop(selected_backend.enter()); - drop(selected_backend); - Ok::<_, Status>(()) - } - .with_subscriber(subscriber) - .await - .expect("capabilities should succeed"); - async { - let gateway_span = tracing::info_span!( - target: "openshell_server::compute", - "driver", - otel.name = "openshell.compute.v1.ComputeDriver/ValidateSandboxCreate", - otel.kind = "client" - ); - ComputeDriver::validate_sandbox_create( - &service, - Request::new(ValidateSandboxCreateRequest { sandbox: None }), - ) - .instrument(gateway_span) - .await - } - .with_subscriber( - tracing_subscriber::registry() - .with(openshell_otel::layer_excluding_target_prefixes( - &gateway_provider, - "gateway-test", - otel_tracing::TRACING.in_process_targets(), - )) - .with(otel_tracing::TRACING.in_process_layer(&driver_provider)), - ) - .await - .expect_err("missing sandbox should fail"); - gateway_provider.force_flush().unwrap(); - driver_provider.force_flush().unwrap(); - - let gateway_spans = gateway_exporter.get_finished_spans().unwrap(); - let driver_spans = driver_exporter.get_finished_spans().unwrap(); - let client = gateway_spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/GetCapabilities") - .unwrap(); - let server = driver_spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/GetCapabilities") - .expect("in-process server span"); - assert_eq!( - server.span_context.trace_id(), - client.span_context.trace_id() - ); - assert_eq!(server.parent_span_id, client.span_context.span_id()); - assert_eq!(server.span_kind, opentelemetry::trace::SpanKind::Server); - assert!(server.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.method" - && attribute.value.to_string() == "openshell.compute.v1.ComputeDriver/GetCapabilities" - })); - assert!( - server - .attributes - .iter() - .all(|attribute| attribute.key.as_str() != "rpc.service"), - "the current RPC semantic conventions integrate the service into rpc.method" - ); - assert!(server.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.response.status_code" && attribute.value.to_string() == "OK" - })); - assert!( - gateway_spans - .iter() - .any(|span| span.name == "kubernetes.operation"), - "unrelated driver targets must remain gateway spans" - ); - assert!( - driver_spans - .iter() - .all(|span| span.name != "kubernetes.operation"), - "the Docker provider must not claim unrelated driver spans" - ); - assert!( - gateway_spans - .iter() - .all(|span| span.name != "docker.operation"), - "the gateway provider must not claim the selected driver's backend spans" - ); - assert!( - driver_spans - .iter() - .any(|span| span.name == "docker.operation"), - "the Docker provider must export backend spans from the selected driver" - ); - let failed = driver_spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/ValidateSandboxCreate") - .expect("failed in-process server span"); - assert!(matches!( - failed.status, - opentelemetry::trace::Status::Error { .. } - )); - assert!(failed.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.response.status_code" - && attribute.value.to_string() == "INVALID_ARGUMENT" - })); - gateway_provider.shutdown().unwrap(); - driver_provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn start_sandbox_span_does_not_capture_launch_authentication() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry().with(otel_tracing::TRACING.layer(&provider)); - - test_driver_with_config(runtime_config()) - .start_sandbox( - "sandbox-1", - "sandbox", - "invalid-generation", - b"secret-launch-authentication", - None, - ) - .with_subscriber(subscriber) - .await - .expect_err("invalid generation must fail before contacting Docker"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "docker.start_sandbox") - .expect("start operation span"); - assert!(span.attributes.iter().all(|attribute| { - !matches!( - attribute.key.as_str(), - "launch_authentication" | "encoded_authentication" - ) - })); - provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn tracing_lifecycle_rpc_failures_export_docker_operation_spans() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry().with(otel_tracing::TRACING.layer(&provider)); - let driver = test_driver_with_config(runtime_config()); - - async { - ComputeDriver::create_sandbox( - &driver, - Request::new(CreateSandboxRequest { sandbox: None }), - ) - .await - .expect_err("missing sandbox should fail"); - ComputeDriver::start_sandbox(&driver, Request::new(StartSandboxRequest::default())) - .await - .expect_err("missing start identifier should fail"); - ComputeDriver::stop_sandbox(&driver, Request::new(StopSandboxRequest::default())) - .await - .expect_err("missing stop identifier should fail"); - ComputeDriver::delete_sandbox(&driver, Request::new(DeleteSandboxRequest::default())) - .await - .expect_err("missing delete identifier should fail"); - } - .with_subscriber(subscriber) - .await; - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - for name in [ - "docker.schedule_sandbox", - "docker.start_sandbox", - "docker.stop_sandbox", - "docker.delete_sandbox", - ] { - let span = spans - .iter() - .find(|span| span.name == name) - .unwrap_or_else(|| panic!("{name} should be exported")); - assert!( - matches!(span.status, opentelemetry::trace::Status::Error { .. }), - "{name} should record the failed operation" - ); - } - provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn tracing_direct_start_exports_a_docker_start_span() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry().with(otel_tracing::TRACING.layer(&provider)); - let driver = test_driver_with_config(runtime_config()); - - Box::pin( - DockerComputeDriver::start_sandbox(&driver, "", "", "", &[], None) - .with_subscriber(subscriber), - ) - .await - .expect_err("missing identifier should fail"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "docker.start_sandbox") - .expect("direct startup operation should export docker.start_sandbox"); - assert!(matches!( - span.status, - opentelemetry::trace::Status::Error { .. } - )); - provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn tracing_image_preparation_failure_exports_nested_failed_spans() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::{Instrument as _, instrument::WithSubscriber as _}; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry().with(otel_tracing::TRACING.layer(&provider)); - let mut config = runtime_config(); - config.image_pull_policy = ImagePullPolicy::Newer; - let driver = test_driver_with_config(config); - - async { - Box::pin( - driver - .provision_sandbox_inner(&test_sandbox()) - .instrument(tracing::info_span!( - "docker.provision", - otel.status_code = tracing::field::Empty - )), - ) - .await - } - .with_subscriber(subscriber) - .await - .expect_err("unsupported image pull policy should fail provisioning"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let provision = spans - .iter() - .find(|span| span.name == "docker.provision") - .expect("provisioning span should be exported"); - assert!(matches!( - provision.status, - opentelemetry::trace::Status::Error { .. } - )); - let prepare_image = spans - .iter() - .find(|span| span.name == "docker.prepare_image") - .expect("image preparation span should be exported"); - assert_eq!( - prepare_image.parent_span_id, - provision.span_context.span_id() - ); - assert!(matches!( - prepare_image.status, - opentelemetry::trace::Status::Error { .. } - )); - provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn background_provisioning_does_not_extend_the_scheduling_span_lifetime() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::Instrument as _; - use tracing_opentelemetry::OpenTelemetrySpanExt as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry().with(otel_tracing::TRACING.layer(&provider)); - let dispatch = tracing::Dispatch::new(subscriber); - let _dispatch = tracing::dispatcher::set_default(&dispatch); - - let scheduling = tracing::info_span!("docker.schedule_sandbox"); - let entered = scheduling.enter(); - let sandbox = test_sandbox(); - let provisioning = provisioning_span(&scheduling.context(), &sandbox, "test-image"); - let task = tokio::spawn(futures::future::pending::<()>().instrument(provisioning)); - drop(entered); - drop(scheduling); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - assert!( - spans - .iter() - .any(|span| span.name == "docker.schedule_sandbox"), - "the scheduling span should finish while background provisioning is pending" - ); - assert!( - spans.iter().all(|span| span.name != "docker.provision"), - "the provisioning span should remain open with the background task" - ); - - task.abort(); - task.await - .expect_err("the pending task should be cancelled"); - provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn tracing_in_process_stream_span_lives_until_stream_failure() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = - tracing_subscriber::registry().with(otel_tracing::TRACING.in_process_layer(&provider)); - - async { - let span = tracing::info_span!( - target: otel_tracing::TRACING.in_process_target(), - "driver_rpc", - otel.name = "openshell.compute.v1.ComputeDriver/WatchSandboxes", - otel.kind = "server", - otel.status_code = tracing::field::Empty, - rpc.response.status_code = tracing::field::Empty, - ); - let inner: WatchStream = Box::pin(futures::stream::iter([Err(Status::internal( - "watch failed", - ))])); - let mut stream = TracedWatchStream::new(inner, span); - - provider.force_flush().unwrap(); - assert!( - exporter.get_finished_spans().unwrap().is_empty(), - "server span must remain open while the response stream is alive" - ); - stream - .next() - .await - .expect("stream item") - .expect_err("stream should fail"); - drop(stream); - } - .with_subscriber(subscriber) - .await; - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/WatchSandboxes") - .expect("watch server span should be exported when the stream ends"); - assert!(matches!( - span.status, - opentelemetry::trace::Status::Error { .. } - )); - provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn tracing_in_process_stream_records_ok_when_stream_completes() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = - tracing_subscriber::registry().with(otel_tracing::TRACING.in_process_layer(&provider)); - - async { - let span = tracing::info_span!( - target: otel_tracing::TRACING.in_process_target(), - "driver_rpc", - otel.name = "openshell.compute.v1.ComputeDriver/WatchSandboxes", - otel.kind = "server", - otel.status_code = tracing::field::Empty, - rpc.response.status_code = tracing::field::Empty, - ); - let inner: WatchStream = Box::pin(futures::stream::empty()); - let mut stream = TracedWatchStream::new(inner, span); - - assert!(stream.next().await.is_none()); - drop(stream); - } - .with_subscriber(subscriber) - .await; - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/WatchSandboxes") - .expect("watch server span should be exported when the stream completes"); - assert!(span.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.response.status_code" && attribute.value.to_string() == "OK" - })); - provider.shutdown().unwrap(); -} - -#[tokio::test] -async fn tracing_in_process_stream_leaves_status_unset_when_dropped() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = - tracing_subscriber::registry().with(otel_tracing::TRACING.in_process_layer(&provider)); - - async { - let span = tracing::info_span!( - target: otel_tracing::TRACING.in_process_target(), - "driver_rpc", - otel.name = "openshell.compute.v1.ComputeDriver/WatchSandboxes", - otel.kind = "server", - otel.status_code = tracing::field::Empty, - rpc.response.status_code = tracing::field::Empty, - ); - let inner: WatchStream = Box::pin(futures::stream::pending()); - let stream = TracedWatchStream::new(inner, span); - - drop(stream); - } - .with_subscriber(subscriber) - .await; - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/WatchSandboxes") - .expect("watch server span should be exported when the stream is dropped"); - assert!(matches!(span.status, opentelemetry::trace::Status::Unset)); - assert!( - span.attributes - .iter() - .all(|attribute| attribute.key.as_str() != "rpc.response.status_code") - ); - provider.shutdown().unwrap(); -} - -#[test] -fn parse_cpu_limit_supports_cores_and_millicores() { - assert_eq!(parse_cpu_limit("250m").unwrap(), Some(250_000_000)); - assert_eq!(parse_cpu_limit("2").unwrap(), Some(2_000_000_000)); - assert!(parse_cpu_limit("0").is_err()); -} - -#[test] -fn parse_memory_limit_supports_binary_quantities() { - assert_eq!(parse_memory_limit("512Mi").unwrap(), Some(536_870_912)); - assert_eq!(parse_memory_limit("1G").unwrap(), Some(1_000_000_000)); - assert!(parse_memory_limit("12XB").is_err()); -} - -#[test] -fn docker_resource_limits_rejects_requests() { - let template = DriverSandboxTemplate { - image: "img".to_string(), - agent_socket_path: String::new(), - labels: HashMap::new(), - environment: HashMap::new(), - resources: Some(DriverResourceRequirements { - cpu_request: "250m".to_string(), - cpu_limit: String::new(), - memory_request: String::new(), - memory_limit: String::new(), - }), - ..Default::default() - }; - - let err = docker_resource_limits(&template).unwrap_err(); - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("resources.requests.cpu")); -} - -#[test] -fn docker_resource_limits_applies_cpu_and_memory_limits() { - let template = DriverSandboxTemplate { - image: "img".to_string(), - agent_socket_path: String::new(), - labels: HashMap::new(), - environment: HashMap::new(), - resources: Some(DriverResourceRequirements { - cpu_limit: "500m".to_string(), - memory_limit: "2Gi".to_string(), - ..Default::default() - }), - ..Default::default() - }; - - let limits = docker_resource_limits(&template).unwrap(); - assert_eq!(limits.nano_cpus, Some(500_000_000)); - assert_eq!(limits.memory_bytes, Some(2_147_483_648)); -} - -#[test] -fn docker_pids_limit_uses_driver_default_and_allows_runtime_inherit() { - let default = openshell_core::config::default_sandbox_pids_limit(); - assert_eq!( - docker_pids_limit(default).unwrap(), - default.map(std::num::NonZeroI64::get) - ); - assert_eq!(docker_pids_limit(None).unwrap(), None); - assert!(docker_pids_limit(std::num::NonZeroI64::new(-1)).is_err()); -} - -#[test] -fn docker_compute_config_disables_bind_mounts_by_default() { - let cfg = DockerComputeConfig::default(); - assert!(!cfg.enable_bind_mounts); -} - -#[test] -fn repository_e2e_docker_configuration_uses_the_supported_schema() { - let source = include_str!("../../../e2e/configs/gateway/docker.toml"); - let (_, docker_table) = source - .split_once("[openshell.drivers.docker]") - .expect("Docker E2E config contains a driver table"); - let config: DockerComputeConfig = - toml::from_str(docker_table).expect("Docker E2E driver config parses"); - - assert_eq!(config.image_pull_policy, ImagePullPolicy::IfNotPresent); - assert_eq!(config.sandbox_label, "openshell-e2e"); -} - -#[test] -fn docker_config_passes_ipv6_egress_settings_to_the_supervisor() { - let config: DockerComputeConfig = toml::from_str( - r#" -https_proxy = "http://proxy.example:3128" -policy_dns_ipv6_egress = "enabled" -nat64_prefixes = ["2001:db8:64::/96"] -"#, - ) - .expect("Docker driver config parses"); - assert_eq!( - config.upstream_proxy.https_proxy.as_deref(), - Some("http://proxy.example:3128") - ); - assert_eq!( - config.ipv6_egress.supervisor_args(), - [ - "--policy-dns-ipv6-egress", - "enabled", - "--nat64-prefix", - "2001:db8:64::/96" - ] - ); - let bind: SocketAddr = "127.0.0.1:8080".parse().unwrap(); - config.validate_configuration(bind).unwrap(); - - let invalid: DockerComputeConfig = - toml::from_str(r#"nat64_prefixes = ["2001:db8::/80"]"#).unwrap(); - assert!(invalid.validate_configuration(bind).is_err()); -} - -#[test] -fn container_create_body_sets_driver_owned_pids_limit() { - let body = build_container_create_body(&test_sandbox(), &runtime_config()).unwrap(); - let host_config = body.host_config.expect("host config"); - assert_eq!( - host_config.pids_limit, - openshell_core::config::default_sandbox_pids_limit().map(std::num::NonZeroI64::get) - ); -} - -#[test] -fn docker_child_environment_strips_supervisor_control_keys() { - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - for key in [ - openshell_core::sandbox_env::ENDPOINT, - openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME, - openshell_core::sandbox_env::NETWORK_RUNTIME_CAPABILITIES, - openshell_core::sandbox_env::OCI_IMAGE_USER, - openshell_core::sandbox_env::SANDBOX_TOKEN, - openshell_core::sandbox_env::SANDBOX_TOKEN_FILE, - ] { - spec.environment - .insert(key.to_string(), "spoofed".to_string()); - } - spec.environment - .insert("PATH".to_string(), "/agent/bin".to_string()); - - let env = docker_child_environment(&sandbox); - - assert_eq!(env.get("PATH").map(String::as_str), Some("/agent/bin")); - assert!(env.contains_key("TEMPLATE_ENV")); - assert!(env.contains_key("SPEC_ENV")); - assert!(!env.values().any(|value| value == "spoofed")); -} - -#[test] -fn supervisor_otlp_environment_carries_only_configured_signals() { - use openshell_core::sandbox_env::{ - GATEWAY_NAME, OTLP_AGENT_ENDPOINT, OTLP_AGENT_PROTOCOL, OTLP_ENDPOINT, OTLP_OCSF_ENDPOINT, - OTLP_OCSF_PROTOCOL, OTLP_PROTOCOL, OtlpExport, OtlpProtocol, - }; - let export = |endpoint: &str, protocol| { - Some(OtlpExport { - endpoint: endpoint.to_string(), - protocol, - }) - }; - - let mut config = runtime_config(); - assert!(supervisor_otlp_environment(&config).is_empty()); - - config.supervisor_otlp.traces = export("http://127.0.0.1:4317", OtlpProtocol::Grpc); - assert_eq!( - supervisor_otlp_environment(&config), - [format!("{OTLP_ENDPOINT}=http://127.0.0.1:4317")] - ); - - config.supervisor_otlp.traces = export("http://127.0.0.1:4318", OtlpProtocol::HttpProtobuf); - assert_eq!( - supervisor_otlp_environment(&config), - [ - format!("{OTLP_ENDPOINT}=http://127.0.0.1:4318"), - format!("{OTLP_PROTOCOL}=http/protobuf"), - ] - ); - - config.supervisor_otlp.traces = None; - config.supervisor_otlp.ocsf = export("http://siem:4317", OtlpProtocol::Grpc); - assert_eq!( - supervisor_otlp_environment(&config), - [format!("{OTLP_OCSF_ENDPOINT}=http://siem:4317")] - ); - - config.supervisor_otlp.ocsf = export("http://siem:4318", OtlpProtocol::HttpProtobuf); - assert_eq!( - supervisor_otlp_environment(&config), - [ - format!("{OTLP_OCSF_ENDPOINT}=http://siem:4318"), - format!("{OTLP_OCSF_PROTOCOL}=http/protobuf"), - ] - ); - - config.supervisor_otlp.ocsf = None; - config.supervisor_otlp.agent = export("http://agents:4317", OtlpProtocol::Grpc); - assert_eq!( - supervisor_otlp_environment(&config), - [format!("{OTLP_AGENT_ENDPOINT}=http://agents:4317")] - ); - - config.supervisor_otlp.agent = export("http://agents:4318", OtlpProtocol::HttpProtobuf); - assert_eq!( - supervisor_otlp_environment(&config), - [ - format!("{OTLP_AGENT_ENDPOINT}=http://agents:4318"), - format!("{OTLP_AGENT_PROTOCOL}=http/protobuf"), - ] - ); - - config.supervisor_gateway_name = Some("prod-west".to_string()); - assert_eq!( - supervisor_otlp_environment(&config).last(), - Some(&format!("{GATEWAY_NAME}=prod-west")) - ); -} - -#[test] -fn boundary_environment_contains_only_driver_owned_values() { - let env = build_boundary_environment(&test_sandbox(), &runtime_config()); - - assert_eq!(env.len(), 2); - assert!( - env.iter() - .any(|entry| entry.starts_with("OPENSHELL_LOG_LEVEL=")) - ); - assert!(env.iter().any(|entry| entry.starts_with(&format!( - "{}=", - openshell_core::sandbox_env::TELEMETRY_ENABLED - )))); -} - -#[test] -fn container_creation_uses_inspected_immutable_image() { - let sandbox = test_sandbox(); - let metadata = DockerImageMetadata { - id: "sha256:immutable".to_string(), - user: "1234:1235".to_string(), - working_dir: "/workspace/project".to_string(), - volumes: Vec::new(), - }; - let body = build_container_create_body_for_image( - &sandbox, - &runtime_config(), - &DockerSandboxDriverConfig::default(), - None, - &metadata, - &test_workload_identity(), - ) - .unwrap(); - - assert_eq!(body.image.as_deref(), Some("sha256:immutable")); - assert_eq!(body.user.as_deref(), Some("1234:1235")); - assert_eq!(body.working_dir.as_deref(), Some("/")); - assert_eq!( - body.labels - .as_ref() - .and_then(|labels| labels.get(LABEL_ISOLATION_BACKEND)) - .map(String::as_str), - Some(LABEL_ISOLATION_BACKEND_OPEN_SHELL) - ); - assert_eq!( - body.labels - .as_ref() - .and_then(|labels| labels.get(LABEL_ISOLATION_ROLE)) - .map(String::as_str), - Some(LABEL_ISOLATION_ROLE_SANDBOX) - ); - assert_eq!( - body.cmd.as_deref(), - Some( - &[ - "--bootstrap".to_string(), - BOUNDARY_CONFIG_MOUNT_PATH.to_string(), - ][..] - ) - ); - assert!(body.env.unwrap().iter().all(|entry| { - !entry.starts_with(&format!("{}=", openshell_core::sandbox_env::OCI_IMAGE_USER)) - })); - let host = body.host_config.unwrap(); - assert_eq!(host.cap_add, None); - assert_eq!(host.cap_drop, Some(vec!["ALL".to_string()])); - assert_eq!(host.group_add, Some(vec!["1236".to_string()])); - assert_eq!( - host.security_opt, - Some(vec![ - "no-new-privileges:true".to_string(), - "apparmor=unconfined".to_string(), - ]) - ); - assert_eq!(host.network_mode.as_deref(), Some("none")); - assert_eq!(host.dns, Some(vec!["127.0.0.53".to_string()])); - assert_eq!(host.dns_search, Some(vec![".".to_string()])); -} - -#[test] -fn docker_outer_fence_accepts_network_none_without_attachments() { - let inspected = bollard::models::ContainerInspectResponse { - host_config: Some(HostConfig { - network_mode: Some("none".to_string()), - ..Default::default() - }), - network_settings: Some(bollard::models::NetworkSettings { - networks: Some(HashMap::from([( - "none".to_string(), - bollard::models::EndpointSettings::default(), - )])), - ..Default::default() - }), - ..Default::default() - }; - - assert!(validate_docker_outer_fence(&inspected).is_ok()); -} - -#[test] -fn docker_outer_fence_rejects_network_mode_or_attached_network_drift() { - let bridge_mode = bollard::models::ContainerInspectResponse { - host_config: Some(HostConfig { - network_mode: Some("bridge".to_string()), - ..Default::default() - }), - ..Default::default() - }; - let attached_network = bollard::models::ContainerInspectResponse { - host_config: Some(HostConfig { - network_mode: Some("none".to_string()), - ..Default::default() - }), - network_settings: Some(bollard::models::NetworkSettings { - networks: Some(HashMap::from([( - "unexpected".to_string(), - bollard::models::EndpointSettings::default(), - )])), - ..Default::default() - }), - ..Default::default() - }; - - assert!(validate_docker_outer_fence(&bridge_mode).is_err()); - assert!(validate_docker_outer_fence(&attached_network).is_err()); -} - -#[test] -fn sandbox_bundle_prepares_only_the_driver_managed_workspace() { - let identity = test_workload_identity(); - let default_archive = docker_sandbox_bundle_archive( - b"sandbox-binary", - b"{}", - DockerSandboxTls { - certificate: b"server-cert", - private_key: b"server-key", - }, - &identity, - driver_mounts::DEFAULT_WORKSPACE_ROOT, - ) - .unwrap(); - let mut archive = tar::Archive::new(default_archive.as_slice()); - let sandbox_entry = archive - .entries() - .unwrap() - .map(Result::unwrap) - .find(|entry| entry.path().unwrap().as_ref() == Path::new("sandbox")) - .expect("managed /sandbox entry"); - assert!(sandbox_entry.header().entry_type().is_dir()); - assert_eq!(sandbox_entry.header().mode().unwrap(), 0o700); - assert_eq!( - sandbox_entry.header().uid().unwrap(), - u64::from(identity.uid) - ); - assert_eq!( - sandbox_entry.header().gid().unwrap(), - u64::from(identity.gid) - ); - - let image_archive = docker_sandbox_bundle_archive( - b"sandbox-binary", - b"{}", - DockerSandboxTls { - certificate: b"server-cert", - private_key: b"server-key", - }, - &identity, - "/workspace/project", - ) - .unwrap(); - let mut archive = tar::Archive::new(image_archive.as_slice()); - assert!( - archive - .entries() - .unwrap() - .map(Result::unwrap) - .all(|entry| { entry.path().unwrap().as_ref() != Path::new("workspace/project") }) - ); -} - -#[test] -fn sandbox_bundle_stages_private_tls_server_material() { - let identity = test_workload_identity(); - let archive = docker_sandbox_bundle_archive( - b"sandbox-binary", - b"{}", - DockerSandboxTls { - certificate: b"server-cert", - private_key: b"server-key", - }, - &identity, - driver_mounts::DEFAULT_WORKSPACE_ROOT, - ) - .unwrap(); - let mut archive = tar::Archive::new(archive.as_slice()); - let entries = archive - .entries() - .unwrap() - .map(Result::unwrap) - .filter_map(|entry| { - let path = entry.path().ok()?.into_owned(); - Some(( - path, - ( - entry.header().mode().ok()?, - entry.header().uid().ok()?, - entry.header().gid().ok()?, - ), - )) - }) - .collect::>(); - for path in [ - ".openshell/channel/sandbox/server.crt", - ".openshell/channel/sandbox/server.key", - ] { - assert_eq!( - entries.get(Path::new(path)), - Some(&(0o600, u64::from(identity.uid), u64::from(identity.gid))) - ); - } - assert_eq!( - entries.get(Path::new(".openshell/runtime/openshell-sandbox")), - Some(&(0o555, 0, 0)), - "the trusted sandbox executable must not be writable by the workload" - ); - assert_eq!( - entries.get(Path::new(".openshell/channel")), - Some(&(0o755, 0, 0)), - "the workload must not be able to replace the supervisor secret directory" - ); - assert_eq!( - entries.get(Path::new(".openshell/channel/sandbox")), - Some(&(0o711, u64::from(identity.uid), u64::from(identity.gid))), - "the supervisor must be able to traverse to the authenticated socket without reading sandbox secrets" - ); -} - -#[test] -fn docker_identity_resolution_uses_pinned_image_accounts_and_exact_groups() { - let sandbox = test_sandbox(); - let image = DockerImageMetadata { - id: "sha256:image".to_string(), - user: "agent".to_string(), - working_dir: "/sandbox".to_string(), - volumes: Vec::new(), - }; - let resolved = resolve_docker_identity_from_accounts( - &sandbox, - &image, - b"root:x:0:0:root:/root:/bin/sh\nagent:x:10001:10002::/sandbox:/bin/sh\n", - b"root:x:0:\nagent:x:10002:\nrender:x:10003:agent\n", - ) - .unwrap(); - - assert_eq!(resolved.uid, 10001); - assert_eq!(resolved.gid, 10002); - assert_eq!(resolved.supplementary_gids, vec![10003]); - assert_eq!(resolved.source, "image"); - assert_eq!(resolved.resource_digest, "sha256:image"); -} - -#[test] -fn docker_identity_resolution_uses_numeric_default_for_userless_image() { - let image = DockerImageMetadata { - id: "sha256:image".to_string(), - user: String::new(), - working_dir: "/".to_string(), - volumes: Vec::new(), - }; - let resolved = resolve_docker_identity_from_accounts( - &test_sandbox(), - &image, - b"root:x:0:0:root:/root:/bin/sh\n", - b"root:x:0:\n", - ) - .unwrap(); - - assert_eq!( - (resolved.uid, resolved.gid), - ( - openshell_core::sandbox_env::DEFAULT_SANDBOX_UID, - openshell_core::sandbox_env::DEFAULT_SANDBOX_GID, - ) - ); - assert_eq!(resolved.source, "default"); - assert_eq!(resolved.resource_digest, "sha256:image"); -} - -#[test] -fn docker_identity_resolution_honors_policy_selectors_and_rejects_root() { - let mut sandbox = test_sandbox(); - sandbox.spec.as_mut().unwrap().workload_identity = Some(WorkloadIdentityRequest { - user: "10001".to_string(), - group: "workers".to_string(), - }); - let image = DockerImageMetadata { - id: "sha256:image".to_string(), - user: String::new(), - working_dir: "/sandbox".to_string(), - volumes: Vec::new(), - }; - let resolved = resolve_docker_identity_from_accounts( - &sandbox, - &image, - b"agent:x:10001:10002::/sandbox:/bin/sh\n", - b"workers:x:10004:agent\n", - ) - .unwrap(); - assert_eq!((resolved.uid, resolved.gid), (10001, 10004)); - assert_eq!(resolved.source, "policy"); - - sandbox.spec.as_mut().unwrap().workload_identity = Some(WorkloadIdentityRequest { - user: "root".to_string(), - group: "root".to_string(), - }); - let error = resolve_docker_identity_from_accounts( - &sandbox, - &image, - b"root:x:0:0:root:/root:/bin/sh\n", - b"root:x:0:\n", - ) - .unwrap_err(); - assert!(error.message().contains("UID or GID zero")); -} - -#[test] -fn container_creation_rejects_invalid_oci_working_dir() { - let metadata = DockerImageMetadata { - id: "sha256:immutable".to_string(), - user: "1234:1235".to_string(), - working_dir: "relative/workspace".to_string(), - volumes: Vec::new(), - }; - let err = build_container_create_body_for_image( - &test_sandbox(), - &runtime_config(), - &DockerSandboxDriverConfig::default(), - None, - &metadata, - &test_workload_identity(), - ) - .unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("must be an absolute container path")); -} - -#[test] -fn container_creation_rejects_openshell_control_path_working_dir() { - let metadata = DockerImageMetadata { - id: "sha256:immutable".to_string(), - user: "1234:1235".to_string(), - working_dir: "/opt/openshell/bin/project".to_string(), - volumes: Vec::new(), - }; - let err = build_container_create_body_for_image( - &test_sandbox(), - &runtime_config(), - &DockerSandboxDriverConfig::default(), - None, - &metadata, - &test_workload_identity(), - ) - .unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("OpenShell control path")); -} - -#[test] -fn container_creation_rejects_image_volume_that_masks_working_dir() { - let sandbox = test_sandbox(); - let metadata = DockerImageMetadata { - id: "sha256:immutable".to_string(), - user: "1234:1235".to_string(), - working_dir: "/workspace/project".to_string(), - volumes: vec!["/workspace".to_string()], - }; - - let error = build_container_create_body_for_image( - &sandbox, - &runtime_config(), - &DockerSandboxDriverConfig::default(), - None, - &metadata, - &test_workload_identity(), - ) - .unwrap_err(); - - assert!( - error - .message() - .contains("masks OCI WorkingDir '/workspace/project'") - ); -} - -#[test] -fn container_creation_reserves_resolved_workspace_root_but_allows_nested_mounts() { - let metadata = DockerImageMetadata { - id: "sha256:immutable".to_string(), - user: "1234:1235".to_string(), - working_dir: "/workspace".to_string(), - volumes: Vec::new(), - }; - let root_mount: DockerSandboxDriverConfig = serde_json::from_value(serde_json::json!({ - "mounts": [{"type": "tmpfs", "target": "/workspace"}] - })) - .unwrap(); - let err = build_container_create_body_for_image( - &test_sandbox(), - &runtime_config(), - &root_mount, - None, - &metadata, - &test_workload_identity(), - ) - .unwrap_err(); - assert!( - err.message() - .contains("reserved for the OpenShell workspace") - ); - - let ancestor_mount: DockerSandboxDriverConfig = serde_json::from_value(serde_json::json!({ - "mounts": [{"type": "tmpfs", "target": "/workspace"}] - })) - .unwrap(); - let nested_metadata = DockerImageMetadata { - working_dir: "/workspace/project".to_string(), - volumes: Vec::new(), - ..metadata.clone() - }; - let err = build_container_create_body_for_image( - &test_sandbox(), - &runtime_config(), - &ancestor_mount, - None, - &nested_metadata, - &test_workload_identity(), - ) - .unwrap_err(); - assert!( - err.message() - .contains("reserved for the OpenShell workspace") - ); - - let nested_mount: DockerSandboxDriverConfig = serde_json::from_value(serde_json::json!({ - "mounts": [{"type": "tmpfs", "target": "/workspace/cache"}] - })) - .unwrap(); - build_container_create_body_for_image( - &test_sandbox(), - &runtime_config(), - &nested_mount, - None, - &metadata, - &test_workload_identity(), - ) - .expect("nested workspace mounts remain supported"); - - let compatibility_path_mount: DockerSandboxDriverConfig = - serde_json::from_value(serde_json::json!({ - "mounts": [{"type": "tmpfs", "target": "/sandbox"}] - })) - .unwrap(); - build_container_create_body_for_image( - &test_sandbox(), - &runtime_config(), - &compatibility_path_mount, - None, - &metadata, - &test_workload_identity(), - ) - .expect("/sandbox remains mountable when the inspected workspace is elsewhere"); -} - -#[test] -fn build_binds_does_not_expose_host_runtime_material() { - let binds = build_binds(&test_sandbox(), &runtime_config()); - assert!(binds.is_empty()); -} - -#[test] -fn build_container_create_body_includes_driver_config_mounts() { - let mut sandbox = test_sandbox(); - let template = sandbox.spec.as_mut().unwrap().template.as_mut().unwrap(); - template.driver_config = Some(json_struct(serde_json::json!({ - "mounts": [ - { - "type": "volume", - "source": "work-nfs", - "target": "/sandbox/work", - "read_only": true, - "subpath": "project-a" - }, - { - "type": "tmpfs", - "target": "/sandbox/cache", - "options": ["nosuid", "size=1048576"], - "size_bytes": 1_048_576, - "mode": 511 - } - ] - }))); - - let body = build_container_create_body(&sandbox, &runtime_config()).unwrap(); - let mounts = body - .host_config - .unwrap() - .mounts - .expect("driver config mounts should be set"); - - assert_eq!(mounts.len(), 4); - assert_eq!(mounts[0].typ, Some(MountTypeEnum::VOLUME)); - assert_eq!(mounts[0].source.as_deref(), Some("work-nfs")); - assert_eq!(mounts[0].target.as_deref(), Some("/sandbox/work")); - assert_eq!(mounts[0].read_only, Some(true)); - assert_eq!( - mounts[0] - .volume_options - .as_ref() - .and_then(|options| options.subpath.as_deref()), - Some("project-a") - ); - assert_eq!(mounts[1].typ, Some(MountTypeEnum::TMPFS)); - assert_eq!(mounts[1].target.as_deref(), Some("/sandbox/cache")); - assert_eq!(mounts[2].typ, Some(MountTypeEnum::VOLUME)); - assert_eq!(mounts[2].target.as_deref(), Some(BOUNDARY_MOUNT_PATH)); - assert_eq!(mounts[2].read_only, Some(false)); - assert_eq!( - mounts[1] - .tmpfs_options - .as_ref() - .and_then(|options| options.size_bytes), - Some(1_048_576) - ); -} - -#[test] -fn driver_config_defaults_volume_mounts_to_read_only() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "volume", - "source": "work-nfs", - "target": "/sandbox/work" - }] - }))); - - let body = build_container_create_body(&sandbox, &runtime_config()).unwrap(); - let mounts = body - .host_config - .unwrap() - .mounts - .expect("driver config mounts should be set"); - - assert_eq!(mounts[0].read_only, Some(true)); -} - -#[test] -fn driver_config_allows_explicit_writable_volume_mounts() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "volume", - "source": "work-nfs", - "target": "/sandbox/work", - "read_only": false - }] - }))); - - let body = build_container_create_body(&sandbox, &runtime_config()).unwrap(); - let mounts = body - .host_config - .unwrap() - .mounts - .expect("driver config mounts should be set"); - - assert_eq!(mounts[0].read_only, Some(false)); -} - -#[test] -fn driver_config_rejects_duplicate_mount_targets() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [ - { - "type": "volume", - "source": "work-nfs", - "target": "/sandbox/work" - }, - { - "type": "tmpfs", - "target": "/sandbox/work" - } - ] - }))); - - let err = build_container_create_body(&sandbox, &runtime_config()).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!( - err.message() - .contains("duplicate docker driver_config mount target") - ); -} - -#[test] -fn driver_config_rejects_bind_mounts_unless_enabled() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "/host/path", - "target": "/sandbox/host" - }] - }))); - - let err = build_container_create_body(&sandbox, &runtime_config()).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("enable_bind_mounts = true")); -} - -#[test] -fn build_container_create_body_includes_bind_mounts_when_enabled() { - let bind_src = TempDir::new().unwrap(); - let src_path = bind_src.path().to_str().unwrap(); - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": src_path, - "target": "/sandbox/host", - "read_only": true - }] - }))); - let mut config = runtime_config(); - config.enable_bind_mounts = true; - - let body = build_container_create_body(&sandbox, &config).unwrap(); - let binds = body - .host_config - .as_ref() - .unwrap() - .binds - .as_ref() - .expect("binds should be set"); - - // User bind mount appears after the system binds. - let expected = format!("{src_path}:/sandbox/host:ro"); - assert!( - binds.iter().any(|b| b == &expected), - "expected bind entry '{expected}', got {binds:?}" - ); - // Bind mounts must not appear in the structured mounts vec. - let mounts = body.host_config.unwrap().mounts.unwrap_or_default(); - assert!( - mounts.iter().all(|m| m.typ != Some(MountTypeEnum::BIND)), - "bind mounts should not appear in structured mounts" - ); -} - -#[test] -fn driver_config_defaults_enabled_bind_mounts_to_read_only() { - let bind_src = TempDir::new().unwrap(); - let src_path = bind_src.path().to_str().unwrap(); - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": src_path, - "target": "/sandbox/host" - }] - }))); - let mut config = runtime_config(); - config.enable_bind_mounts = true; - - let body = build_container_create_body(&sandbox, &config).unwrap(); - let binds = body - .host_config - .unwrap() - .binds - .expect("binds should be set"); - - let expected = format!("{src_path}:/sandbox/host:ro"); - assert!( - binds.iter().any(|b| b == &expected), - "default bind mount should be read-only, got {binds:?}" - ); -} - -#[test] -fn bind_mount_selinux_shared_label() { - let bind_src = TempDir::new().unwrap(); - let src_path = bind_src.path().to_str().unwrap(); - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": src_path, - "target": "/sandbox/data", - "read_only": true, - "selinux_label": "shared" - }] - }))); - let mut config = runtime_config(); - config.enable_bind_mounts = true; - - let body = build_container_create_body(&sandbox, &config).unwrap(); - let binds = body - .host_config - .unwrap() - .binds - .expect("binds should be set"); - - let expected = format!("{src_path}:/sandbox/data:ro,z"); - assert!( - binds.iter().any(|b| b == &expected), - "expected ':ro,z' label, got {binds:?}" - ); -} - -#[test] -fn bind_mount_selinux_private_label() { - let bind_src = TempDir::new().unwrap(); - let src_path = bind_src.path().to_str().unwrap(); - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": src_path, - "target": "/sandbox/data", - "read_only": false, - "selinux_label": "private" - }] - }))); - let mut config = runtime_config(); - config.enable_bind_mounts = true; - - let body = build_container_create_body(&sandbox, &config).unwrap(); - let binds = body - .host_config - .unwrap() - .binds - .expect("binds should be set"); - - let expected = format!("{src_path}:/sandbox/data:Z"); - assert!( - binds.iter().any(|b| b == &expected), - "expected ':Z' label, got {binds:?}" - ); -} - -#[test] -fn bind_mount_without_selinux_label() { - let bind_src = TempDir::new().unwrap(); - let src_path = bind_src.path().to_str().unwrap(); - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": src_path, - "target": "/sandbox/host", - "read_only": false - }] - }))); - let mut config = runtime_config(); - config.enable_bind_mounts = true; - - let body = build_container_create_body(&sandbox, &config).unwrap(); - let binds = body - .host_config - .unwrap() - .binds - .expect("binds should be set"); - - let expected = format!("{src_path}:/sandbox/host"); - assert!( - binds.iter().any(|b| b == &expected), - "expected no options suffix, got {binds:?}" - ); -} - -#[test] -fn driver_config_rejects_missing_bind_source() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "/no/such/path", - "target": "/sandbox/data" - }] - }))); - let mut config = runtime_config(); - config.enable_bind_mounts = true; - - let err = build_container_create_body(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!( - err.message().contains("bind source path does not exist"), - "expected missing-source error, got: {}", - err.message() - ); -} - -#[test] -fn driver_config_rejects_relative_bind_sources_when_enabled() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "relative/path", - "target": "/sandbox/host" - }] - }))); - let mut config = runtime_config(); - config.enable_bind_mounts = true; - - let err = build_container_create_body(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!( - err.message() - .contains("bind source must be an absolute host path") - ); -} - -#[test] -fn driver_config_rejects_image_mounts() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "image", - "source": "ghcr.io/acme/tools:latest", - "target": "/opt/tools" - }] - }))); - - let err = build_container_create_body(&sandbox, &runtime_config()).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("invalid docker driver_config")); -} - -#[test] -fn driver_config_rejects_reserved_mount_targets() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "volume", - "source": "work-nfs", - "target": "/etc/openshell/auth" - }] - }))); - - let err = build_container_create_body(&sandbox, &runtime_config()).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("reserved OpenShell path")); -} - -#[test] -fn docker_local_volume_with_bind_option_is_bind_backed() { - let volume = inspected_volume( - "local", - HashMap::from([ - ("type".to_string(), "none".to_string()), - ("o".to_string(), "rw,bind".to_string()), - ("device".to_string(), "/tmp/openshell".to_string()), - ]), - ); - - assert!(docker_volume_is_bind_backed(&volume)); -} - -#[test] -fn docker_local_volume_with_rbind_option_is_bind_backed() { - let volume = inspected_volume( - "local", - HashMap::from([ - ("type".to_string(), "none".to_string()), - ("o".to_string(), "rw,rbind".to_string()), - ("device".to_string(), "/tmp/openshell".to_string()), - ]), - ); - - assert!(docker_volume_is_bind_backed(&volume)); -} - -#[test] -fn docker_local_volume_without_bind_option_is_not_bind_backed() { - let volume = inspected_volume( - "local", - HashMap::from([ - ("type".to_string(), "nfs".to_string()), - ("o".to_string(), "addr=127.0.0.1,rw".to_string()), - ("device".to_string(), ":/exports/openshell".to_string()), - ]), - ); - - assert!(!docker_volume_is_bind_backed(&volume)); -} - -#[test] -fn docker_nonlocal_volume_with_bind_option_is_not_bind_backed() { - let volume = inspected_volume( - "custom", - HashMap::from([("o".to_string(), "bind".to_string())]), - ); - - assert!(!docker_volume_is_bind_backed(&volume)); -} - -#[test] -fn managed_container_label_filters_include_gateway_namespace() { - let filters = - managed_container_label_filters("tenant-a", [format!("{LABEL_SANDBOX_ID}=sbx-123")]); - let labels = filters.get("label").unwrap(); - - assert!(labels.contains(&format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE}"))); - assert!(labels.contains(&format!("{LABEL_SANDBOX_NAMESPACE}=tenant-a"))); - assert!(labels.contains(&format!( - "{LABEL_ISOLATION_ROLE}={LABEL_ISOLATION_ROLE_SANDBOX}" - ))); - assert!(labels.contains(&format!("{LABEL_SANDBOX_ID}=sbx-123"))); -} - -#[test] -fn persistent_workspace_config_defaults_off_and_round_trips() { - let default: DockerComputeConfig = toml::from_str("").unwrap(); - assert!(!default.persist_workspace); - let enabled: DockerComputeConfig = toml::from_str("persist_workspace = true").unwrap(); - assert!(enabled.persist_workspace); - let saved = toml::to_string(&enabled).unwrap(); - assert!( - toml::from_str::(&saved) - .unwrap() - .persist_workspace - ); -} - -#[test] -fn persistent_workspace_create_mounts_only_the_owned_default_workspace() { - let sandbox = test_sandbox(); - let mut config = runtime_config(); - let old = build_container_create_body(&sandbox, &config).unwrap(); - assert!( - old.host_config - .unwrap() - .mounts - .unwrap() - .iter() - .all(|mount| mount.target.as_deref() != Some("/sandbox")) - ); - config.workspace_storage = workspace::Storage::Persistent; - let body = build_container_create_body(&sandbox, &config).unwrap(); - let mounts = body.host_config.unwrap().mounts.unwrap(); - let mounts = mounts - .iter() - .filter(|mount| mount.target.as_deref() == Some("/sandbox")) - .collect::>(); - assert_eq!(mounts.len(), 1); - assert_eq!(mounts[0].typ, Some(MountTypeEnum::VOLUME)); - assert_eq!(mounts[0].read_only, Some(false)); - assert_eq!( - mounts[0].volume_options.as_ref().unwrap().no_copy, - Some(true) - ); - assert!( - mounts[0] - .source - .as_ref() - .unwrap() - .starts_with("openshell-workspace-") - ); -} - -#[test] -fn build_container_create_body_replaces_inherited_cmd_with_sandbox_bootstrap() { - let create_body = build_container_create_body(&test_sandbox(), &runtime_config()).unwrap(); - - assert_eq!( - create_body.entrypoint, - Some(vec![SANDBOX_BINARY_PATH.to_string()]) - ); - assert_eq!( - create_body.cmd, - Some(vec![ - "--bootstrap".to_string(), - BOUNDARY_CONFIG_MOUNT_PATH.to_string(), - ]) - ); - assert!( - create_body - .host_config - .as_ref() - .and_then(|config| config.binds.as_ref()) - .is_some_and(|binds| binds - .iter() - .all(|bind| !bind.contains(ADDITIONAL_CA_MOUNT_PATH))) - ); - assert_eq!( - create_body - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_SANDBOX_NAMESPACE)), - Some(&"default".to_string()) - ); - let host_config = create_body.host_config.as_ref().unwrap(); - assert!( - host_config.device_requests.as_ref().is_none(), - "non-GPU containers should not request Docker devices" - ); - assert_eq!( - host_config.security_opt.as_ref(), - Some(&vec![ - "no-new-privileges:true".to_string(), - "apparmor=unconfined".to_string(), - ]) - ); - assert_eq!(host_config.network_mode.as_deref(), Some("none")); - assert_eq!(host_config.extra_hosts, None); - assert!(create_body.networking_config.is_none()); -} - -#[test] -fn additional_destination_trust_is_supervisor_only_and_digest_paired() { - let dir = TempDir::new().unwrap(); - let artifact = dir.path().join("normalized-additional-ca.crt"); - let pem = b"normalized certificate fixture"; - fs::write(&artifact, pem).unwrap(); - #[cfg(unix)] - fs::set_permissions( - &artifact, - std::os::unix::fs::PermissionsExt::from_mode(0o444), - ) - .unwrap(); - let bundle = NetworkSupervisorTrustBundle::new( - pem.to_vec(), - 1, - "sha256:paired-digest", - artifact.clone(), - ); - let mut config = runtime_config(); - config.network_trust = Some(bundle.clone()); - - let workload = build_container_create_body(&test_sandbox(), &config).unwrap(); - assert!( - workload - .labels - .as_ref() - .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) - .is_some() - ); - assert!( - workload - .cmd - .as_ref() - .unwrap() - .iter() - .all(|argument| argument != "--additional-ca-bundle") - ); - assert!( - workload - .host_config - .as_ref() - .and_then(|host| host.mounts.as_ref()) - .unwrap() - .iter() - .all(|mount| mount.target.as_deref() != Some(ADDITIONAL_CA_MOUNT_PATH)) - ); - - let args = docker_network_trust_supervisor_args(Some(&bundle)); - assert!( - args.windows(2) - .any(|arguments| { arguments == ["--additional-ca-bundle", ADDITIONAL_CA_MOUNT_PATH] }) - ); - let mount = docker_network_trust_supervisor_mount(&bundle).unwrap(); - assert_eq!(mount.target.as_deref(), Some(ADDITIONAL_CA_MOUNT_PATH)); - assert_eq!(mount.source.as_deref(), artifact.to_str()); - assert_eq!(mount.read_only, Some(true)); -} - -#[test] -fn tampered_additional_destination_trust_fails_closed_without_pem_contents() { - let dir = TempDir::new().unwrap(); - let artifact = dir.path().join("normalized-additional-ca.crt"); - fs::write(&artifact, b"expected").unwrap(); - #[cfg(unix)] - fs::set_permissions( - &artifact, - std::os::unix::fs::PermissionsExt::from_mode(0o444), - ) - .unwrap(); - let bundle = NetworkSupervisorTrustBundle::new( - b"expected".to_vec(), - 1, - "sha256:expected", - artifact.clone(), - ); - fs::remove_file(&artifact).unwrap(); - fs::write(&artifact, b"BEGIN CERTIFICATE modified secret data").unwrap(); - #[cfg(unix)] - fs::set_permissions( - &artifact, - std::os::unix::fs::PermissionsExt::from_mode(0o444), - ) - .unwrap(); - - let error = docker_network_trust_supervisor_mount(&bundle) - .expect_err("a changed gateway artifact must fail closed"); - assert!(error.message().contains("network additional CA artifact")); - assert!(!error.message().contains("modified secret data")); -} - -#[test] -fn user_mount_cannot_replace_network_trust_destination() { - let dir = TempDir::new().unwrap(); - let source = dir.path().join("user-ca.crt"); - fs::write(&source, b"user-controlled fixture").unwrap(); - let mut config = runtime_config(); - config.enable_bind_mounts = true; - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": source, - "target": ADDITIONAL_CA_MOUNT_PATH - }] - }))); - - let error = build_container_create_body(&sandbox, &config) - .expect_err("user mount must not mask network trust material"); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!( - error.message().contains("reserved OpenShell path"), - "unexpected error: {error}" - ); -} - -#[test] -fn validate_sandbox_rejects_gpu_when_cdi_unavailable() { - let config = runtime_config(); - let mut sandbox = test_sandbox(); - sandbox.spec.as_mut().unwrap().resource_requirements = Some(gpu_resources(None)); - - let err = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("Docker CDI")); -} - -#[test] -fn validate_sandbox_rejects_missing_gpu_support_before_request_shape() { - let config = runtime_config(); - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(Some(2))); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&["nvidia.com/gpu=0"])); - - let err = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("Docker CDI")); -} - -#[test] -fn validate_sandbox_rejects_invalid_cdi_devices_before_gpu_capability() { - let config = runtime_config(); - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(None)); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&[])); - - let err = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("invalid docker driver_config")); - assert!(err.message().contains("non-empty list")); -} - -#[test] -fn validate_sandbox_rejects_unknown_driver_config_fields() { - let config = runtime_config(); - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(None)); - spec.template.as_mut().unwrap().driver_config = - Some(cdi_device_typo_config(&["nvidia.com/gpu=0"])); - - let err = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("unknown field")); -} - -#[test] -fn sandbox_driver_config_rejects_trusted_runtime_image_overrides() { - for field in ["sandbox_runtime_image", "supervisor_image"] { - let template = DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - (field): "registry.example.com/openshell/runtime:untrusted" - }))), - ..Default::default() - }; - - let error = DockerSandboxDriverConfig::from_template(&template) - .expect_err("sandbox requests must not select trusted runtime images"); - assert!(error.contains("unknown field"), "{error}"); - assert!(error.contains(field), "{error}"); - } -} - -#[test] -fn validate_sandbox_accepts_gpu_count_request_shape() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - sandbox.spec.as_mut().unwrap().resource_requirements = Some(gpu_resources(Some(2))); - - DockerComputeDriver::validate_sandbox(&sandbox, &config) - .expect("default GPU count shape should be accepted before inventory selection"); -} - -#[test] -fn validate_sandbox_accepts_gpu_count_matching_cdi_devices() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(Some(2))); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&[ - "nvidia.com/gpu=0", - "nvidia.com/gpu=1", - ])); - - DockerComputeDriver::validate_sandbox(&sandbox, &config) - .expect("matching explicit CDI device count should be accepted"); -} - -#[test] -fn validate_sandbox_accepts_single_cdi_device_without_gpu_count() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(None)); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&["nvidia.com/gpu=0"])); - - DockerComputeDriver::validate_sandbox(&sandbox, &config) - .expect("single exact CDI device should be compatible with a default GPU request"); -} - -#[test] -fn validate_sandbox_rejects_multiple_cdi_devices_without_gpu_count() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(None)); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&[ - "nvidia.com/gpu=0", - "nvidia.com/gpu=1", - ])); - - let err = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!( - err.message() - .contains("gpu count (1) must match driver_config.cdi_devices length (2)") - ); -} - -#[test] -fn validate_sandbox_rejects_cdi_devices_without_gpu_request() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(cdi_devices_config(&["nvidia.com/gpu=0"])); - - let err = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("requires a gpu request")); -} - -#[test] -fn validate_sandbox_rejects_gpu_count_mismatched_cdi_devices() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(Some(2))); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&["nvidia.com/gpu=0"])); - - let err = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!( - err.message() - .contains("gpu count (2) must match driver_config.cdi_devices length (1)") - ); -} - -#[test] -fn validate_sandbox_rejects_template_errors_before_device_config() { - let config = runtime_config(); - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(None)); - let template = spec.template.as_mut().unwrap(); - template.agent_socket_path = "/tmp/agent.sock".to_string(); - template.driver_config = Some(cdi_devices_config(&[])); - - let err = DockerComputeDriver::validate_sandbox(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert!(err.message().contains("agent_socket_path")); -} - -#[test] -fn validate_sandbox_auth_requires_launch_authentication() { - let mut sandbox = test_sandbox(); - sandbox.spec.as_mut().unwrap().launch_authentication.clear(); - - let err = DockerComputeDriver::validate_sandbox_auth(&sandbox).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::FailedPrecondition); - assert_eq!( - err.message(), - "docker sandboxes require launch-scoped gateway authentication" - ); -} - -#[test] -fn validate_sandbox_auth_accepts_launch_authentication() { - let sandbox = test_sandbox(); - DockerComputeDriver::validate_sandbox_auth(&sandbox).unwrap(); -} - -#[test] -fn build_container_create_body_maps_default_gpu_to_selected_cdi_device() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - sandbox.spec.as_mut().unwrap().resource_requirements = Some(gpu_resources(None)); - - let driver_config = DockerSandboxDriverConfig::default(); - let gpu_devices = vec!["nvidia.com/gpu=1".to_string()]; - let create_body = build_container_create_body_with_gpu_devices( - &sandbox, - &config, - &driver_config, - Some(&gpu_devices), - ) - .unwrap(); - let request = create_body - .host_config - .as_ref() - .and_then(|host_config| host_config.device_requests.as_ref()) - .and_then(|requests| requests.first()) - .expect("GPU request should add a Docker device request"); - - assert_eq!(request.driver.as_deref(), Some("cdi")); - assert_eq!( - request.device_ids.as_ref().unwrap(), - &vec!["nvidia.com/gpu=1".to_string()] - ); -} - -#[test] -fn build_container_create_body_omits_devices_without_resolved_default_cdi_devices() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - sandbox.spec.as_mut().unwrap().resource_requirements = Some(gpu_resources(None)); - - let create_body = build_container_create_body(&sandbox, &config).unwrap(); - - assert!( - create_body - .host_config - .as_ref() - .and_then(|host_config| host_config.device_requests.as_ref()) - .is_none() - ); -} - -#[test] -fn container_spec_accepts_non_nvidia_explicit_and_resolved_cdi_devices() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - sandbox.spec.as_mut().unwrap().resource_requirements = Some(gpu_resources(None)); - for device in ["example.com/gpu=0", "intel.com/gpu=0", "amd.com/gpu=0"] { - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(cdi_devices_config(&[device])); - let explicit = build_container_create_body(&sandbox, &config).unwrap(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = None; - let resolved = build_container_create_body_with_gpu_devices( - &sandbox, - &config, - &DockerSandboxDriverConfig::default(), - Some(&[device.to_string()]), - ) - .unwrap(); - for body in [explicit, resolved] { - let requests = body.host_config.unwrap().device_requests.unwrap(); - assert_eq!(requests[0].driver.as_deref(), Some("cdi")); - assert_eq!( - requests[0].device_ids.as_ref().unwrap(), - &[device.to_string()] - ); - } - } -} - -#[test] -fn container_spec_rejects_host_paths_in_explicit_and_resolved_cdi_devices() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - sandbox.spec.as_mut().unwrap().resource_requirements = Some(gpu_resources(None)); - for device in [ - "/dev/sda", - "/dev", - "/dev/sda:/dev/sda:rwm", - "vendor/gpu=0/1", - ] { - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(cdi_devices_config(&[device])); - let explicit_error = build_container_create_body(&sandbox, &config).unwrap_err(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = None; - let resolved_error = build_container_create_body_with_gpu_devices( - &sandbox, - &config, - &DockerSandboxDriverConfig::default(), - Some(&[device.to_string()]), - ) - .unwrap_err(); - for error in [explicit_error, resolved_error] { - assert_eq!(error.code(), tonic::Code::InvalidArgument); - assert!(error.message().contains("CDI qualified names")); - } - } -} - -#[test] -fn build_container_create_body_passes_explicit_cdi_device_id_through() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(None)); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&["nvidia.com/gpu=0"])); - - let create_body = build_container_create_body(&sandbox, &config).unwrap(); - let request = create_body - .host_config - .as_ref() - .and_then(|host_config| host_config.device_requests.as_ref()) - .and_then(|requests| requests.first()) - .expect("GPU request should add a Docker device request"); - - assert_eq!(request.driver.as_deref(), Some("cdi")); - assert_eq!( - request.device_ids.as_ref().unwrap(), - &vec!["nvidia.com/gpu=0".to_string()] - ); -} - -#[test] -fn build_container_create_body_rejects_gpu_count_mismatched_cdi_devices() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(Some(2))); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&["nvidia.com/gpu=0"])); - - let err = build_container_create_body(&sandbox, &config).unwrap_err(); - - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!( - err.message() - .contains("gpu count (2) must match driver_config.cdi_devices length (1)") - ); -} - -#[test] -fn build_container_create_body_rejects_cdi_devices_without_gpu_request() { - let mut sandbox = test_sandbox(); - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(cdi_devices_config(&["nvidia.com/gpu=0"])); - - let err = build_container_create_body(&sandbox, &runtime_config()).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("requires a gpu request")); -} - -#[test] -fn build_container_create_body_rejects_empty_cdi_devices() { - let mut sandbox = test_sandbox(); - let spec = sandbox.spec.as_mut().unwrap(); - spec.resource_requirements = Some(gpu_resources(None)); - spec.template.as_mut().unwrap().driver_config = Some(cdi_devices_config(&[])); - - let err = build_container_create_body(&sandbox, &runtime_config()).unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("non-empty list")); -} - -#[test] -fn driver_default_gpu_selection_consumes_distinct_devices_for_creates() { - let mut config = runtime_config(); - config.gpu.cdi_supported = true; - let driver = test_driver_with_config(config); - driver.gpu_selector.refresh( - CdiGpuInventory::new(["nvidia.com/gpu=0", "nvidia.com/gpu=1"]), - false, - ); - let mut first_sandbox = test_sandbox(); - first_sandbox.id = "sbx-first".to_string(); - first_sandbox.name = "first".to_string(); - first_sandbox.spec.as_mut().unwrap().resource_requirements = Some(gpu_resources(None)); - let mut second_sandbox = test_sandbox(); - second_sandbox.id = "sbx-second".to_string(); - second_sandbox.name = "second".to_string(); - second_sandbox.spec.as_mut().unwrap().resource_requirements = Some(gpu_resources(None)); - - DockerComputeDriver::validate_sandbox(&first_sandbox, &driver.config).unwrap(); - assert_eq!( - driver.gpu_selector.peek_device_ids(1).unwrap(), - vec!["nvidia.com/gpu=0".to_string()] - ); - let first_devices = driver.gpu_selector.next_device_ids(1).unwrap(); - let driver_config = DockerSandboxDriverConfig::default(); - let first_create_body = build_container_create_body_with_gpu_devices( - &first_sandbox, - &driver.config, - &driver_config, - Some(&first_devices), - ) - .unwrap(); - - DockerComputeDriver::validate_sandbox(&second_sandbox, &driver.config).unwrap(); - assert_eq!( - driver.gpu_selector.peek_device_ids(1).unwrap(), - vec!["nvidia.com/gpu=1".to_string()] - ); - let second_devices = driver.gpu_selector.next_device_ids(1).unwrap(); - let second_create_body = build_container_create_body_with_gpu_devices( - &second_sandbox, - &driver.config, - &driver_config, - Some(&second_devices), - ) - .unwrap(); - - let first_request = first_create_body - .host_config - .as_ref() - .and_then(|host_config| host_config.device_requests.as_ref()) - .and_then(|requests| requests.first()) - .expect("first default GPU request should add a Docker device request"); - let second_request = second_create_body - .host_config - .as_ref() - .and_then(|host_config| host_config.device_requests.as_ref()) - .and_then(|requests| requests.first()) - .expect("second default GPU request should add a Docker device request"); - - assert_eq!( - first_request.device_ids.as_ref().unwrap(), - &vec!["nvidia.com/gpu=0".to_string()] - ); - assert_eq!( - second_request.device_ids.as_ref().unwrap(), - &vec!["nvidia.com/gpu=1".to_string()] - ); -} - -fn engine_version(name: &str, version: &str) -> SystemVersion { - SystemVersion { - components: Some(vec![bollard::models::SystemVersionComponents { - name: name.to_string(), - version: version.to_string(), - details: None, - }]), - ..Default::default() - } -} - -#[test] -fn warns_on_docker_engine_older_than_minimum() { - let warning = unsupported_docker_engine_warning(&engine_version("Engine", "26.1.5+dfsg1")) - .expect("old engine warns"); - assert!(warning.contains("26.1.5+dfsg1"), "{warning}"); - assert!(warning.contains("28.0"), "{warning}"); -} - -#[test] -fn no_warning_for_supported_unknown_or_other_engines() { - for version in [ - engine_version("Engine", "28.0.0"), - engine_version("Engine", "29.9.3"), - engine_version("Engine", "garbage"), - engine_version("Other Engine", "5.8.2"), - SystemVersion::default(), - ] { - assert!(unsupported_docker_engine_warning(&version).is_none()); - } -} - -#[test] -fn docker_info_reports_wsl2_from_kernel_version() { - let info = SystemInfo { - kernel_version: Some("5.15.153.1-microsoft-standard-WSL2".to_string()), - operating_system: Some("Docker Desktop".to_string()), - ..Default::default() - }; - - assert!(docker_info_reports_wsl2(&info)); -} - -#[test] -fn docker_info_reports_wsl2_from_operating_system() { - let info = SystemInfo { - operating_system: Some("Ubuntu 24.04.4 LTS on WSL2".to_string()), - ..Default::default() - }; - - assert!(docker_info_reports_wsl2(&info)); -} - -#[test] -fn docker_info_reports_wsl2_ignores_daemon_name_and_labels() { - let info = SystemInfo { - kernel_version: Some("6.8.0-60-generic".to_string()), - operating_system: Some("Ubuntu 24.04.4 LTS".to_string()), - name: Some("wsl-docker-daemon".to_string()), - labels: Some(vec!["com.example.platform=wsl2".to_string()]), - ..Default::default() - }; - - assert!(!docker_info_reports_wsl2(&info)); -} - -#[test] -fn docker_info_reports_wsl2_rejects_plain_linux() { - let info = SystemInfo { - kernel_version: Some("6.8.0-60-generic".to_string()), - operating_system: Some("Ubuntu 24.04.4 LTS".to_string()), - os_type: Some("linux".to_string()), - architecture: Some("x86_64".to_string()), - ..Default::default() - }; - - assert!(!docker_info_reports_wsl2(&info)); -} - -#[test] -fn require_sandbox_identifier_rejects_when_id_and_name_are_empty() { - // Regression test: `delete_sandbox` (and the other identifier-keyed - // RPCs) must refuse requests where both the id and the name are - // empty. Otherwise the empty filters fed to - // `find_managed_container_summary` match the first managed container - // in the namespace, allowing an arbitrary sandbox to be deleted. - let err = require_sandbox_identifier("", "").unwrap_err(); - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert!(err.message().contains("sandbox_id or sandbox_name")); - - require_sandbox_identifier("sbx-1", "").expect("id-only is accepted"); - require_sandbox_identifier("", "demo").expect("name-only is accepted"); - require_sandbox_identifier("sbx-1", "demo").expect("id and name is accepted"); -} - -#[test] -fn build_container_create_body_disables_docker_networking() { - let create_body = build_container_create_body(&test_sandbox(), &runtime_config()).unwrap(); - let host_config = create_body.host_config.expect("host_config is populated"); - - assert_eq!( - host_config.network_mode, - Some("none".to_string()), - "the sandbox must not receive direct Docker networking" - ); - assert_eq!(host_config.extra_hosts, None); - assert_eq!(host_config.dns, Some(vec!["127.0.0.53".to_string()])); - assert_eq!( - host_config.dns_search, - Some(vec![".".to_string()]), - "host search domains must not expand workload names before policy DNS" - ); -} - -#[test] -fn docker_supervisor_uses_host_network() { - let host = docker_supervisor_host_config( - Vec::new(), - "https://127.0.0.1:17670", - DockerSupervisorNetworkMode::Host, - None, - ); - - assert_eq!(host.network_mode.as_deref(), Some("host")); - assert_eq!( - host.extra_hosts, - Some(vec![ - "host.openshell.internal:127.0.0.1".to_string(), - "host.docker.internal:127.0.0.1".to_string(), - ]) - ); - assert_eq!(host.cap_drop, Some(vec!["ALL".to_string()])); - assert_eq!(host.cap_add, None); -} - -#[test] -fn docker_supervisor_maps_host_aliases_to_the_gateway_address() { - let host = docker_supervisor_host_config( - Vec::new(), - "https://172.20.0.4:17670", - DockerSupervisorNetworkMode::Host, - None, - ); - - assert_eq!( - host.extra_hosts, - Some(vec![ - "host.openshell.internal:172.20.0.4".to_string(), - "host.docker.internal:172.20.0.4".to_string(), - ]) - ); - assert_eq!( - docker_supervisor_host_address("https://172.20.0.4:17670"), - Some("172.20.0.4".parse().unwrap()) - ); -} - -#[test] -fn docker_supervisor_leaves_named_gateway_hosts_to_dns() { - let host = docker_supervisor_host_config( - Vec::new(), - "https://gateway.example.com:17670", - DockerSupervisorNetworkMode::Host, - None, - ); - - assert_eq!(host.extra_hosts, None); - assert_eq!( - docker_supervisor_host_address("https://gateway.example.com:17670"), - None - ); -} - -#[test] -fn docker_supervisor_healthcheck_probes_fast_only_during_startup() { - let health = docker_supervisor_healthcheck(); - - assert_eq!(health.start_interval, Some(250_000_000)); - assert_eq!(health.interval, Some(30_000_000_000)); - assert_eq!(health.start_period, Some(60_000_000_000)); -} - -#[test] -fn docker_supervisor_defaults_to_the_primary_loopback_endpoint() { - assert_eq!( - default_docker_supervisor_grpc_endpoint(17_670, false), - "http://127.0.0.1:17670" - ); - assert_eq!( - default_docker_supervisor_grpc_endpoint(17_670, true), - "https://127.0.0.1:17670" - ); -} - -#[test] -fn docker_supervisor_honors_operator_network_mode() { - for (requested, expected) in [ - ( - DockerSupervisorNetworkMode::Auto, - DockerSupervisorNetworkMode::Host, - ), - ( - DockerSupervisorNetworkMode::Host, - DockerSupervisorNetworkMode::Host, - ), - ( - DockerSupervisorNetworkMode::Bridge, - DockerSupervisorNetworkMode::Bridge, - ), - ] { - let mut config = runtime_config(); - config.supervisor_network_mode = requested; - config.supervisor_endpoint_explicit = false; - config.supervisor_grpc_endpoint = "https://127.0.0.1:8443".into(); - let (mode, endpoint) = docker_supervisor_networking(&config).unwrap(); - assert_eq!(mode, expected); - assert_eq!( - endpoint, - if mode == DockerSupervisorNetworkMode::Bridge { - "https://host.docker.internal:8443" - } else { - "https://127.0.0.1:8443" - } - ); - } -} - -#[test] -fn docker_bridge_preserves_explicit_endpoints_and_rejects_loopback() { - let mut config = runtime_config(); - config.supervisor_network_mode = DockerSupervisorNetworkMode::Bridge; - for endpoint in [ - "https://gateway.example.com:9443", - "http://172.20.0.4:8080", - "https://[fd00::2]:9443", - ] { - config.supervisor_grpc_endpoint = endpoint.into(); - let (_, selected) = docker_supervisor_networking(&config).unwrap(); - assert_eq!(selected, endpoint); - } - for endpoint in [ - "https://127.0.0.1:8443", - "http://localhost:8080", - "https://[::1]:8443", - "http://0.0.0.0:8080", - "http://[::]:8080", - ] { - config.supervisor_grpc_endpoint = endpoint.into(); - let error = docker_supervisor_networking(&config).unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!(error.message().contains("grpc_endpoint")); - } -} - -#[test] -fn docker_bridge_defaults_respect_desktop_and_linux_listener_reachability() { - assert_eq!( - default_docker_bridge_endpoint("127.0.0.1:17670".parse().unwrap(), true, true).as_deref(), - Some("https://host.docker.internal:17670") - ); - assert_eq!( - default_docker_bridge_endpoint("0.0.0.0:8080".parse().unwrap(), false, false).as_deref(), - Some("http://host.docker.internal:8080") - ); - assert_eq!( - default_docker_bridge_endpoint("192.168.1.2:8080".parse().unwrap(), true, false).as_deref(), - Some("https://192.168.1.2:8080") - ); - assert_eq!( - default_docker_bridge_endpoint("[fd00::2]:8080".parse().unwrap(), true, false).as_deref(), - Some("https://[fd00::2]:8080") - ); - assert!( - default_docker_bridge_endpoint("127.0.0.1:17670".parse().unwrap(), true, false).is_none() - ); - let mut config = runtime_config(); - config.supervisor_network_mode = DockerSupervisorNetworkMode::Bridge; - config.supervisor_endpoint_explicit = false; - config.bridge_default_endpoint = None; - let error = docker_supervisor_networking(&config).unwrap_err(); - assert!(error.message().contains("bind_address")); -} - -#[test] -fn docker_bridge_host_aliases_are_independent_of_gateway_endpoint() { - let host = docker_supervisor_host_config( - Vec::new(), - "https://gateway.example.com:9443", - DockerSupervisorNetworkMode::Bridge, - Some("172.17.0.1".parse().unwrap()), - ); - assert_eq!(host.network_mode.as_deref(), Some("bridge")); - assert_eq!( - host.extra_hosts, - Some(vec![ - "host.openshell.internal:172.17.0.1".into(), - "host.docker.internal:172.17.0.1".into() - ]) - ); - assert_eq!(host.cap_drop, Some(vec!["ALL".into()])); - assert_eq!(host.cap_add, None); - assert_eq!( - host.security_opt, - Some(vec!["no-new-privileges:true".into()]) - ); - assert_eq!( - build_container_create_body(&test_sandbox(), &runtime_config()) - .unwrap() - .host_config - .unwrap() - .network_mode - .as_deref(), - Some("none") - ); -} - -#[test] -fn docker_host_gateway_parser_prefers_one_ipv4_and_rejects_invalid_mappings() { - assert_eq!(parse_docker_host_gateway_hosts(b"172.29.0.254 host.openshell.internal\nfd00::1 host.openshell.internal\n172.29.0.254 host.openshell.internal # duplicate\n").unwrap(), "172.29.0.254".parse::().unwrap()); - assert_eq!( - parse_docker_host_gateway_hosts(b"fd00::1 HOST.OPENSHELL.INTERNAL\n").unwrap(), - "fd00::1".parse::().unwrap() - ); - for contents in [ - "127.0.0.1 localhost", - "172.17.0.1 host.docker.internal", - "172.17.0.1 host.openshell.internal\n172.18.0.1 host.openshell.internal", - "bad-ip host.openshell.internal", - "169.254.169.254 host.openshell.internal", - "127.0.0.1 host.openshell.internal", - "::ffff:127.0.0.1 host.openshell.internal", - "0.0.0.0 host.openshell.internal", - "224.0.0.1 host.openshell.internal", - ] { - assert!( - parse_docker_host_gateway_hosts(contents.as_bytes()).is_err(), - "{contents}" - ); - } - assert!(parse_docker_host_gateway_hosts(&[0xff]).is_err()); -} - -#[test] -fn docker_host_gateway_resolver_uses_the_trusted_image_without_network_or_privileges() { - let body = docker_host_gateway_resolver_body("sha256:trusted", "resolver-test"); - assert_eq!(body.image.as_deref(), Some("sha256:trusted")); - assert_eq!(body.user.as_deref(), Some("65534:65534")); - assert_eq!( - body.entrypoint.unwrap(), - [SUPERVISOR_IMAGE_CONTROL_BINARY_PATH] - ); - assert_eq!(body.cmd.unwrap(), ["--help"]); - let labels = body.labels.unwrap(); - assert_eq!( - labels.get(LABEL_SANDBOX_NAMESPACE).map(String::as_str), - Some("resolver-test") - ); - assert_eq!( - labels.get(LABEL_ISOLATION_ROLE).map(String::as_str), - Some(LABEL_ISOLATION_ROLE_STAGING) - ); - let host = body.host_config.unwrap(); - assert_eq!(host.network_mode.as_deref(), Some("none")); - assert_eq!( - host.extra_hosts.unwrap(), - ["host.openshell.internal:host-gateway"] - ); - assert_eq!(host.cap_drop.unwrap(), ["ALL"]); - assert_eq!(host.cap_add, None); - assert_eq!(host.security_opt.unwrap(), ["no-new-privileges:true"]); - assert_eq!(host.readonly_rootfs, Some(true)); - assert!(host.binds.is_none()); - assert!(host.mounts.is_none()); -} - -#[tokio::test] -#[ignore = "requires Docker and local supervisor/sandbox images; starts one confined resolver at a time"] -async fn live_docker_host_gateway_resolver_reads_daemon_mapping_and_cleans_up() { - let docker = Docker::connect_with_local_defaults().unwrap(); - let supervisor = - std::env::var("OPENSHELL_TEST_DOCKER_SUPERVISOR_IMAGE").expect("set supervisor image"); - let sandbox = std::env::var("OPENSHELL_TEST_DOCKER_SANDBOX_IMAGE") - .expect("set sandbox image with no supervisor binary"); - let temporary = TempDir::new().unwrap(); - let namespace = format!( - "host-gateway-{}", - temporary.path().file_name().unwrap().to_str().unwrap() - ); - let image_id = docker.inspect_image(&supervisor).await.unwrap().id.unwrap(); - let ip = resolve_docker_host_gateway(&docker, &image_id, &namespace) - .await - .unwrap(); - eprintln!("Docker daemon host-gateway resolved to {ip}"); - if let Ok(expected) = std::env::var("OPENSHELL_TEST_DOCKER_HOST_GATEWAY_IP") { - assert_eq!(ip, expected.parse::().unwrap()); - } - let assert_clean = || async { - let filters = HashMap::from([( - "label", - vec![format!("{LABEL_SANDBOX_NAMESPACE}={namespace}")], - )]); - let remaining = docker - .list_containers(Some( - ListContainersOptionsBuilder::default() - .all(true) - .filters(&filters) - .build(), - )) - .await - .unwrap(); - assert!( - remaining.is_empty(), - "resolver container leaked: {remaining:?}" - ); - }; - assert_clean().await; - let failure_image_id = docker.inspect_image(&sandbox).await.unwrap().id.unwrap(); - assert!( - resolve_docker_host_gateway(&docker, &failure_image_id, &namespace) - .await - .is_err() - ); - assert_clean().await; -} - -#[test] -fn docker_host_gateway_override_is_operator_owned_and_matches_the_alias_pin() { - let config: DockerComputeConfig = - toml::from_str("supervisor_network_mode = 'bridge'\nhost_gateway_ip = '172.29.0.254'") - .unwrap(); - let ip = validate_docker_host_gateway_ip( - config.host_gateway_ip.unwrap(), - config.supervisor_network_mode, - ) - .unwrap(); - let host = docker_supervisor_host_config( - Vec::new(), - "https://gateway.example.com:8443", - config.supervisor_network_mode, - Some(ip), - ); - assert_eq!( - host.extra_hosts.unwrap(), - [ - "host.openshell.internal:172.29.0.254", - "host.docker.internal:172.29.0.254" - ] - ); - assert!( - serde_json::from_value::( - serde_json::json!({"host_gateway_ip": "172.29.0.254"}) - ) - .is_err() - ); - assert!( - validate_docker_host_gateway_ip( - "127.0.0.1".parse().unwrap(), - DockerSupervisorNetworkMode::Host - ) - .is_ok() - ); - assert!( - validate_docker_host_gateway_ip( - "0.0.0.0".parse().unwrap(), - DockerSupervisorNetworkMode::Host - ) - .is_err() - ); -} - -#[test] -fn docker_supervisor_network_mode_is_an_operator_config_enum() { - assert_eq!( - toml::from_str::("") - .unwrap() - .supervisor_network_mode, - DockerSupervisorNetworkMode::Host - ); - for (value, expected) in [ - ("auto", DockerSupervisorNetworkMode::Auto), - ("host", DockerSupervisorNetworkMode::Host), - ("bridge", DockerSupervisorNetworkMode::Bridge), - ] { - let config: DockerComputeConfig = - toml::from_str(&format!("supervisor_network_mode = '{value}'")).unwrap(); - assert_eq!(config.supervisor_network_mode, expected); - } - assert!(toml::from_str::("supervisor_network_mode = 'none'").is_err()); - assert!( - serde_json::from_value::(serde_json::json!({ - "supervisor_network_mode": "host" - })) - .is_err(), - "workloads cannot select supervisor networking" - ); -} - -#[test] -fn build_container_create_body_limits_writable_runtime_storage_to_supervisor_ca() { - let create_body = build_container_create_body(&test_sandbox(), &runtime_config()).unwrap(); - let host_config = create_body.host_config.expect("host_config is populated"); - let tmpfs = host_config.tmpfs.expect("sandbox tmpfs is populated"); - - assert_eq!(tmpfs.len(), 1); - assert_eq!( - tmpfs.get(openshell_sandbox_backend::SUPERVISOR_CA_RUNTIME_DIR), - Some(&"rw,noexec,nosuid,nodev,size=1m,uid=1000,gid=1000,mode=0755".to_string()) - ); - assert!(!tmpfs.contains_key("/run")); -} - -#[test] -fn legacy_workspace_template_labels_are_preserved() { - let mut sandbox = test_sandbox(); - let labels = &mut sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .labels; - labels.insert( - "openshell.ai/workspace-storage".into(), - "caller-layout".into(), - ); - labels.insert( - "openshell.ai/workspace-volume-identity".into(), - "caller-identity".into(), - ); - labels.insert( - "openshell.ai/docker-workspace-storage".into(), - "caller-value".into(), - ); - labels.insert( - "openshell.ai/docker-workspace-volume-identity".into(), - "not-json".into(), - ); - let expected = labels.clone(); - for storage in [ - workspace::Storage::WritableLayer, - workspace::Storage::Persistent, - ] { - let mut config = runtime_config(); - config.workspace_storage = storage; - let labels = build_container_create_body(&sandbox, &config) - .unwrap() - .labels - .unwrap(); - for (key, value) in &expected { - assert_eq!(labels.get(key), Some(value)); - } - } -} - -#[test] -fn build_container_create_body_uses_runtime_namespace_label() { - // Regression test: the namespace label must come from the driver's - // runtime config, not from `DriverSandbox.namespace`. The gateway - // does not populate `DriverSandbox.namespace`, so a container created - // with that empty value would not match subsequent list/get/find - // queries (which filter on `config.sandbox_namespace`), leaking - // sandboxes that the driver itself cannot observe. - let mut config = runtime_config(); - config.sandbox_namespace = "tenant-a".to_string(); - let mut sandbox = test_sandbox(); - sandbox.namespace = "ignored-by-driver".to_string(); - - let create_body = build_container_create_body(&sandbox, &config).unwrap(); - let labels = create_body.labels.expect("labels are populated"); - - assert_eq!( - labels.get(LABEL_SANDBOX_NAMESPACE), - Some(&"tenant-a".to_string()), - "namespace label must reflect the driver's runtime config" - ); -} - -#[test] -fn driver_status_keeps_running_sandboxes_provisioning_with_stable_message() { - let running = ContainerSummary { - id: Some("cid".to_string()), - names: Some(vec!["/openshell-demo".to_string()]), - labels: Some(HashMap::from([ - (LABEL_SANDBOX_ID.to_string(), "sbx-1".to_string()), - (LABEL_SANDBOX_NAME.to_string(), "demo".to_string()), - (LABEL_SANDBOX_NAMESPACE.to_string(), "default".to_string()), - ])), - state: Some(ContainerSummaryStateEnum::RUNNING), - status: Some("Up 2 seconds".to_string()), - ..Default::default() - }; - let exited = ContainerSummary { - state: Some(ContainerSummaryStateEnum::EXITED), - status: Some("Exited (1) 3 seconds ago".to_string()), - ..running.clone() - }; - let running_later = ContainerSummary { - status: Some("Up 4 seconds".to_string()), - ..running.clone() - }; - - // A running container always emits Ready=True with BackendReady. The gateway - // composes this with supervisor-session presence to decide public SandboxPhase. - let running_status = driver_status_from_summary(&running, "demo"); - let running_later_status = driver_status_from_summary(&running_later, "demo"); - assert_eq!(running_status.conditions[0].status, "True"); - assert_eq!(running_status.conditions[0].reason, "BackendReady"); - assert_eq!(running_status.conditions[0].message, "Container is running"); - assert_eq!(running_status.conditions, running_later_status.conditions); - - let exited_status = driver_status_from_summary(&exited, "demo"); - assert_eq!(exited_status.conditions[0].status, "False"); - assert_eq!(exited_status.conditions[0].reason, "ContainerExited"); - assert_eq!(exited_status.conditions[0].message, "Container exited"); -} - -#[test] -fn driver_status_marks_restarting_sandboxes_as_error() { - let restarting = ContainerSummary { - id: Some("cid".to_string()), - names: Some(vec!["/openshell-demo".to_string()]), - labels: Some(HashMap::from([ - (LABEL_SANDBOX_ID.to_string(), "sbx-1".to_string()), - (LABEL_SANDBOX_NAME.to_string(), "demo".to_string()), - (LABEL_SANDBOX_NAMESPACE.to_string(), "default".to_string()), - ])), - state: Some(ContainerSummaryStateEnum::RESTARTING), - status: Some("Restarting (1) 2 seconds ago".to_string()), - ..Default::default() - }; - - let status = driver_status_from_summary(&restarting, "demo"); - assert_eq!(status.conditions[0].status, "False"); - assert_eq!(status.conditions[0].reason, "ContainerRestarting"); - assert_eq!( - status.conditions[0].message, - "Container is restarting after a failure" - ); -} - -#[test] -fn docker_scheduled_event_adds_progress_metadata() { - let mut metadata = HashMap::from([( - "image_ref".to_string(), - "ghcr.io/acme/sandbox:latest".to_string(), - )]); - - attach_docker_progress_metadata( - &mut metadata, - "Scheduled", - "Docker sandbox accepted for image \"ghcr.io/acme/sandbox:latest\"", - ); - - assert_eq!( - metadata.get(PROGRESS_COMPLETE_STEP_KEY).map(String::as_str), - Some(PROGRESS_STEP_REQUESTING_SANDBOX) - ); - assert_eq!( - metadata - .get(PROGRESS_COMPLETE_LABEL_KEY) - .map(String::as_str), - Some("Sandbox allocated") - ); - assert_eq!( - metadata.get(PROGRESS_ACTIVE_STEP_KEY).map(String::as_str), - Some(PROGRESS_STEP_PULLING_IMAGE) - ); - assert_eq!( - metadata.get(PROGRESS_ACTIVE_DETAIL_KEY).map(String::as_str), - Some("ghcr.io/acme/sandbox:latest") - ); -} - -#[test] -fn docker_pulled_event_advances_to_starting_progress() { - let mut metadata = HashMap::new(); - - attach_docker_progress_metadata( - &mut metadata, - "Pulled", - "Pulled Docker image \"ghcr.io/acme/sandbox:latest\"", - ); - - assert_eq!( - metadata.get(PROGRESS_COMPLETE_STEP_KEY).map(String::as_str), - Some(PROGRESS_STEP_PULLING_IMAGE) - ); - assert_eq!( - metadata - .get(PROGRESS_COMPLETE_LABEL_KEY) - .map(String::as_str), - Some("Image pulled") - ); - assert_eq!( - metadata.get(PROGRESS_ACTIVE_STEP_KEY).map(String::as_str), - Some(PROGRESS_STEP_STARTING_SANDBOX) - ); -} - -#[test] -fn docker_pull_progress_event_adds_layer_detail_metadata() { - let event = docker_pull_progress_event( - "ghcr.io/acme/sandbox:latest", - &CreateImageInfo { - id: Some("layer-1".to_string()), - status: Some("Downloading".to_string()), - progress_detail: Some(ProgressDetail { - current: Some(42 * 1024 * 1024), - total: Some(84 * 1024 * 1024), - }), - ..Default::default() - }, - ) - .expect("pull progress event"); - - assert_eq!(event.source, "docker"); - assert_eq!(event.reason, "PullingLayer"); - assert_eq!( - event - .metadata - .get(PROGRESS_ACTIVE_STEP_KEY) - .map(String::as_str), - Some(PROGRESS_STEP_PULLING_IMAGE) - ); - assert_eq!( - event - .metadata - .get(PROGRESS_ACTIVE_DETAIL_KEY) - .map(String::as_str), - Some("Downloading layer-1 (42 MB/84 MB)") - ); -} - -#[test] -fn pending_sandbox_snapshot_uses_docker_namespace_and_starting_condition() { - let sandbox = test_sandbox(); - - let snapshot = - pending_sandbox_snapshot(&sandbox, "docker-dev", provisioning_condition(), false); - - assert_eq!(snapshot.id, "sbx-123"); - assert_eq!(snapshot.name, "demo"); - assert_eq!(snapshot.namespace, "docker-dev"); - assert!(snapshot.spec.is_none()); - let pending = HashMap::from([( - snapshot.id.clone(), - PendingSandboxRecord { - sandbox: snapshot.clone(), - task: None, - }, - )]); - assert_eq!( - pending_sandbox_record_id(&pending, "sbx-123", "wrong-name").unwrap(), - Some("sbx-123".to_string()) - ); - assert_eq!( - pending_sandbox_record_id(&pending, "", "demo").unwrap(), - Some("sbx-123".to_string()) - ); - - let status = snapshot.status.expect("status"); - assert!(!status.deleting); - assert_eq!(status.name, "demo"); - assert_eq!(status.conditions.len(), 1); - assert_eq!(status.conditions[0].r#type, "Ready"); - assert_eq!(status.conditions[0].status, "False"); - assert_eq!(status.conditions[0].reason, "Starting"); - assert_eq!(status.conditions[0].message, "Docker container is starting"); -} - -#[test] -fn pending_lookup_is_id_authoritative_and_rejects_ambiguous_names() { - let mut alpha = test_sandbox(); - alpha.id = "sbx-alpha".to_string(); - alpha.workspace = "workspace-alpha".to_string(); - let mut beta = alpha.clone(); - beta.id = "sbx-beta".to_string(); - beta.workspace = "workspace-beta".to_string(); - let pending = [alpha, beta] - .into_iter() - .map(|sandbox| { - ( - sandbox.id.clone(), - PendingSandboxRecord { - sandbox, - task: None, - }, - ) - }) - .collect(); - - assert_eq!( - pending_sandbox_record_id(&pending, "sbx-alpha", "demo").unwrap(), - Some("sbx-alpha".to_string()) - ); - assert!(pending_sandbox_record_id(&pending, "", "demo").is_err()); -} - -#[test] -fn workload_mounts_only_the_shared_channel_volume() { - let config = runtime_config(); - let sandbox = test_sandbox(); - let identity = ResolvedWorkloadIdentity::new( - 65_534, - 65_534, - Vec::new(), - "65534:65534".to_string(), - "sha256:immutable".to_string(), - ) - .unwrap(); - let body = build_container_create_body_for_image( - &sandbox, - &config, - &DockerSandboxDriverConfig::default(), - None, - &DockerImageMetadata { - id: "sha256:immutable".to_string(), - user: "65534:65534".to_string(), - working_dir: "/sandbox".to_string(), - volumes: Vec::new(), - }, - &identity, - ) - .unwrap(); - let mounts = body.host_config.unwrap().mounts.unwrap(); - let sources = mounts - .iter() - .filter_map(|mount| mount.source.as_deref()) - .collect::>(); - - assert!(sources.contains(&docker_channel_volume_name(&sandbox, &config).as_str())); - assert!(!sources.contains(&docker_supervisor_volume_name(&sandbox, &config).as_str())); -} - -#[test] -fn docker_guest_tls_paths_accept_ca_only_for_https() { - let tempdir = TempDir::new().unwrap(); - let ca = tempdir.path().join("ca.crt"); - fs::write(&ca, b"ca").unwrap(); - - let paths = docker_guest_tls_paths(&DockerComputeConfig { - grpc_endpoint: "https://localhost:8443".to_string(), - guest_tls_ca: Some(ca.clone()), - ..Default::default() - }) - .unwrap() - .expect("CA-only TLS paths"); - assert_eq!(paths.ca, ca.canonicalize().unwrap()); -} - -#[test] -fn container_name_preserves_id_suffix_for_long_names() { - // Names up to 253 chars are permitted by the gRPC layer. The id - // suffix is what makes the container name unique between sandboxes - // sharing a prefix, so it must always appear in the final name. - let long_name = "a".repeat(253); - let first = DriverSandbox { - id: "sbx-first-1234567890".to_string(), - name: long_name, - namespace: "default".to_string(), - spec: None, - status: None, - workspace: "default".to_string(), - }; - let second = DriverSandbox { - id: "sbx-second-0987654321".to_string(), - ..first.clone() - }; - - let first_container = container_name_for_sandbox(&first); - let second_container = container_name_for_sandbox(&second); - - assert!( - first_container.len() <= MAX_CONTAINER_NAME_LEN, - "container name {} exceeded {MAX_CONTAINER_NAME_LEN} chars: {first_container}", - first_container.len(), - ); - assert!( - first_container.ends_with(&first.id), - "container name should end with sandbox id: {first_container}", - ); - assert_ne!( - first_container, second_container, - "container names must differ for sandboxes with distinct ids", - ); -} - -#[test] -fn container_name_empty_sandbox_name_uses_workspace_and_id() { - let sandbox = DriverSandbox { - id: "sbx-abc".to_string(), - name: String::new(), - namespace: "default".to_string(), - spec: None, - status: None, - workspace: "default".to_string(), - }; - assert_eq!( - container_name_for_sandbox(&sandbox), - "openshell-default---sbx-abc", - ); -} - -#[test] -fn trim_container_name_tail_strips_separators() { - assert_eq!(trim_container_name_tail("foo-".to_string()), "foo"); - assert_eq!(trim_container_name_tail("foo-.".to_string()), "foo"); - assert_eq!(trim_container_name_tail("foo_-.".to_string()), "foo"); - assert_eq!(trim_container_name_tail("foo".to_string()), "foo"); -} - -#[test] -fn docker_guest_tls_paths_rejects_tls_flags_without_https() { - let tempdir = TempDir::new().unwrap(); - let ca = tempdir.path().join("ca.crt"); - fs::write(&ca, b"ca").unwrap(); - - let err = docker_guest_tls_paths(&DockerComputeConfig { - grpc_endpoint: "http://localhost:8080".to_string(), - guest_tls_ca: Some(ca), - ..Default::default() - }) - .unwrap_err(); - assert!(err.to_string().contains("https://")); -} - -#[test] -fn docker_guest_tls_paths_allows_plain_http_without_tls_flags() { - let result = docker_guest_tls_paths(&DockerComputeConfig { - grpc_endpoint: "http://localhost:8080".to_string(), - ..Default::default() - }) - .unwrap(); - assert!(result.is_none()); -} - -#[test] -fn default_docker_supervisor_image_uses_quay_repo() { - let image = openshell_core::config::default_supervisor_image(); - assert!( - image.starts_with("quay.io/ai-openshell/supervisor:"), - "unexpected default image reference: {image}", - ); -} - -#[test] -fn docker_supervisor_image_tag_prefers_explicit_build_tags() { - use openshell_core::config::resolve_supervisor_image_tag; - assert_eq!( - resolve_supervisor_image_tag(&["1.2.3", "sha", "0.0.0"]), - "1.2.3" - ); - assert_eq!(resolve_supervisor_image_tag(&["", "sha", "0.0.0"]), "sha"); - assert_eq!(resolve_supervisor_image_tag(&["", "", "1.2.3"]), "1.2.3"); - assert_eq!(resolve_supervisor_image_tag(&["", "", "0.0.0"]), "dev"); -} - -#[test] -fn docker_supervisor_image_tag_sanitizes_build_metadata_for_docker() { - use openshell_core::config::resolve_supervisor_image_tag; - assert_eq!( - resolve_supervisor_image_tag(&["", "", "0.0.37-dev.156+g1d3b741ee"]), - "0.0.37-dev.156-g1d3b741ee", - ); - assert_eq!( - resolve_supervisor_image_tag(&["0.0.37-dev.156+g1d3b741ee", "", "0.0.0"]), - "0.0.37-dev.156-g1d3b741ee", - ); -} - -#[test] -fn docker_supervisor_image_refreshes_mutable_tags_only() { - assert!(supervisor_image_should_refresh( - "quay.io/ai-openshell/supervisor:dev" - )); - assert!(supervisor_image_should_refresh( - "quay.io/ai-openshell/supervisor:latest" - )); - assert!(supervisor_image_should_refresh( - "quay.io/ai-openshell/supervisor" - )); - assert!(!supervisor_image_should_refresh( - "quay.io/ai-openshell/supervisor:0.0.47-dev.13-g57b71c68f" - )); - assert!(!supervisor_image_should_refresh( - "quay.io/ai-openshell/supervisor@sha256:abc123" - )); -} - -#[test] -fn temp_extract_container_names_are_unique_per_call() { - let first = temp_extract_container_name(); - let second = temp_extract_container_name(); - assert_ne!(first, second); - assert!(first.starts_with("openshell-supervisor-extract-")); -} - -#[test] -fn extract_first_tar_entry_returns_payload_of_single_file_archive() { - // Build a tar archive with the same shape Docker returns from - // `/containers//archive` for a single file. - let payload = b"\x7fELFtest-binary-bytes"; - let mut tar_buf = Vec::new(); - { - let mut builder = tar::Builder::new(&mut tar_buf); - let mut header = tar::Header::new_gnu(); - header.set_path("openshell-sandbox").unwrap(); - header.set_size(payload.len() as u64); - header.set_mode(0o755); - header.set_cksum(); - builder.append(&header, payload.as_slice()).unwrap(); - builder.finish().unwrap(); - } - - let extracted = extract_first_tar_entry(&tar_buf).unwrap(); - assert_eq!(extracted, payload); -} - -#[test] -fn extract_first_tar_entry_rejects_empty_archive() { - let mut tar_buf = Vec::new(); - tar::Builder::new(&mut tar_buf).finish().unwrap(); - let err = extract_first_tar_entry(&tar_buf).unwrap_err(); - assert!(err.contains("empty"), "unexpected error message: {err}"); -} - -#[test] -fn container_state_needs_start_matches_startable_states() { - for state in [ - ContainerSummaryStateEnum::EXITED, - ContainerSummaryStateEnum::CREATED, - ] { - assert!( - container_state_needs_start(state), - "{state:?} should be started with Docker start", - ); - } - - for state in [ - ContainerSummaryStateEnum::RUNNING, - ContainerSummaryStateEnum::RESTARTING, - ContainerSummaryStateEnum::PAUSED, - ContainerSummaryStateEnum::DEAD, - ContainerSummaryStateEnum::REMOVING, - ContainerSummaryStateEnum::EMPTY, - ] { - assert!( - !container_state_needs_start(state), - "{state:?} should not be started with Docker start", - ); - } -} - -#[test] -fn lifecycle_fence_rejects_polled_exit_from_before_restart() { - let fences = DockerLifecycleEventFences::default(); - fences.begin_start("sandbox-1"); - assert!(fences.start_in_progress("sandbox-1")); - fences.finish_start("sandbox-1"); - assert!(!fences.start_in_progress("sandbox-1")); - - fences.request_stop("sandbox-1", "demo"); - assert!(fences.stop_requested("sandbox-1", "")); - assert!(fences.stop_requested("", "demo")); - fences.clear_stop("sandbox-1", "demo"); - assert!(!fences.stop_requested("sandbox-1", "demo")); - fences.request_stop("sandbox-1", "demo"); - - fences.record_previous_exit("sandbox-1", Some("2026-08-12T16:39:13Z")); - assert_eq!( - fences.previous_exit("sandbox-1").as_deref(), - Some("2026-08-12T16:39:13Z") - ); - - let previous_exit = ContainerState { - status: Some(ContainerStateStatusEnum::EXITED), - finished_at: Some("2026-08-12T16:39:13Z".to_string()), - ..Default::default() - }; - assert!(docker_polled_exit_is_stale( - "2026-08-12T16:39:13Z", - Some(&previous_exit), - )); - - let running = ContainerState { - status: Some(ContainerStateStatusEnum::RUNNING), - ..previous_exit.clone() - }; - assert!(docker_polled_exit_is_stale( - "2026-08-12T16:39:13Z", - Some(&running), - )); - - let new_exit = ContainerState { - finished_at: Some("2026-08-12T16:40:00Z".to_string()), - ..previous_exit - }; - assert!(!docker_polled_exit_is_stale( - "2026-08-12T16:39:13Z", - Some(&new_exit), - )); - - fences.remove("sandbox-1", "demo"); - assert!(fences.previous_exit("sandbox-1").is_none()); - assert!(!fences.stop_requested("sandbox-1", "")); - assert!(!fences.stop_requested("", "demo")); -} - -fn exited_sandbox_with_ready_reason(reason: &str) -> DriverSandbox { - DriverSandbox { - id: "sbx-exit".to_string(), - name: "demo".to_string(), - namespace: String::new(), - spec: None, - status: Some(DriverSandboxStatus { - name: "demo".to_string(), - instance_id: "container-1".to_string(), - agent_fd: String::new(), - sandbox_fd: String::new(), - conditions: vec![DriverCondition { - r#type: "Ready".to_string(), - status: "False".to_string(), - reason: reason.to_string(), - message: "Container exited".to_string(), - transition_time: None, - }], - deleting: false, - ..Default::default() - }), - workspace: String::new(), - } -} - -fn ready_reason(sandbox: &DriverSandbox) -> &str { - sandbox - .status - .as_ref() - .and_then(|status| status.conditions.iter().find(|c| c.r#type == "Ready")) - .map(|c| c.reason.as_str()) - .expect("Ready condition present") -} - -#[test] -fn docker_signal_kill_reclassified_as_runtime_restart() { - // 137 (128+SIGKILL) and 143 (128+SIGTERM) mark an external termination — - // the signature of a machine/daemon restart — and become recoverable - // `ContainerRuntimeRestart`. - for exit_code in [137, 143] { - let mut sandbox = exited_sandbox_with_ready_reason(CONDITION_EXITED); - let state = ContainerState { - status: Some(ContainerStateStatusEnum::EXITED), - oom_killed: Some(false), - exit_code: Some(exit_code), - ..Default::default() - }; - apply_docker_exit_classification(&mut sandbox, &state); - assert_eq!( - ready_reason(&sandbox), - CONDITION_RUNTIME_RESTART, - "exit code {exit_code} should reclassify as runtime restart" - ); - } -} - -#[test] -fn docker_ordinary_exit_stays_terminal() { - // An application exit (non-zero error code) stays `ContainerExited` so its - // failure signal survives instead of being relaunched on startup. - let mut sandbox = exited_sandbox_with_ready_reason(CONDITION_EXITED); - let state = ContainerState { - status: Some(ContainerStateStatusEnum::EXITED), - oom_killed: Some(false), - exit_code: Some(1), - ..Default::default() - }; - apply_docker_exit_classification(&mut sandbox, &state); - assert_eq!(ready_reason(&sandbox), CONDITION_EXITED); -} - -#[test] -fn docker_oom_kill_stays_terminal_despite_137() { - // An OOM kill reports exit 137 but must NOT be treated as a recoverable - // restart — it is a genuine failure and stays terminal. - let mut sandbox = exited_sandbox_with_ready_reason(CONDITION_EXITED); - let state = ContainerState { - status: Some(ContainerStateStatusEnum::EXITED), - oom_killed: Some(true), - exit_code: Some(137), - ..Default::default() - }; - apply_docker_exit_classification(&mut sandbox, &state); - assert_eq!(ready_reason(&sandbox), CONDITION_EXITED); -} - -#[test] -fn supervisor_workspace_validation_exit_is_reported_explicitly() { - let status = workspace_validation_status(); - assert_eq!(status.message(), WORKSPACE_VALIDATION_FAILED_MESSAGE); - assert_eq!( - supervisor_start_failure_reason(&status, "ControlSupervisorStartFailed"), - CONDITION_WORKSPACE_VALIDATION_FAILED - ); - assert_eq!( - supervisor_start_failure_reason( - &Status::failed_precondition("provider SPIFFE socket has no parent directory"), - "ControlSupervisorStartFailed" - ), - "ControlSupervisorStartFailed" - ); - assert_eq!( - supervisor_exit_reason(i64::from(SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED)), - CONDITION_WORKSPACE_VALIDATION_FAILED - ); - assert_eq!(supervisor_exit_reason(1), "ControlSupervisorExited"); - - let (reason, message) = - docker_supervisor_wait_failure(Some(Err(BollardError::DockerContainerWaitError { - code: i64::from(SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED), - error: "image workspace validation failed".into(), - }))); - assert_eq!(reason, CONDITION_WORKSPACE_VALIDATION_FAILED); - assert!(message.contains("status 78")); - assert_eq!( - docker_supervisor_wait_failure(Some(Err(BollardError::DockerContainerWaitError { - code: 1, - error: String::new(), - }))) - .0, - "ControlSupervisorExited" - ); -} - -#[tokio::test] -async fn workspace_failure_survives_supervisor_cleanup_before_readiness_inspection() { - let failures = Arc::new(Mutex::new(HashMap::from([( - "sandbox-1".to_string(), - DockerRuntimeFailure { - reason: CONDITION_WORKSPACE_VALIDATION_FAILED, - message: "Docker supervisor container exited with status 78".into(), - }, - )]))); - // There is no Docker daemon at this address: a monitor that has removed - // the supervisor must not need another inspection to retain the reason. - let docker = Docker::connect_with_http("127.0.0.1:1", 1, bollard::API_DEFAULT_VERSION).unwrap(); - let status = wait_for_docker_supervisor_ready( - &docker, - "removed-supervisor", - "workload-container-1", - "sandbox-1", - &failures, - ) - .await - .expect_err("the recorded workspace failure takes precedence over inspection"); - assert_eq!( - supervisor_start_failure_reason(&status, "ControlSupervisorStartFailed"), - CONDITION_WORKSPACE_VALIDATION_FAILED - ); -} - -#[test] -fn concurrent_container_removal_is_idempotent() { - let removing = BollardError::DockerResponseServerError { - status_code: 409, - message: "removal of container abc123 is already in progress".to_string(), - }; - let other_conflict = BollardError::DockerResponseServerError { - status_code: 409, - message: "container abc123 is running".to_string(), - }; - - assert!(is_removal_in_progress_error(&removing)); - assert!(!is_removal_in_progress_error(&other_conflict)); -} - -#[tokio::test] -async fn missing_start_generation_is_adopted() { - let directory = TempDir::new().expect("create temporary directory"); - let path = directory.path().join(START_GENERATION_FILE); - let generation = openshell_core::sandbox_generation::SandboxGenerationId::parse( - "generation-one".to_string(), - ) - .expect("valid generation"); - - adopt_or_verify_docker_start_generation_path(&path, &generation) - .await - .expect("adopt missing marker"); - - assert_eq!( - fs::read_to_string(&path).expect("read adopted marker"), - generation.as_str() - ); - adopt_or_verify_docker_start_generation_path(&path, &generation) - .await - .expect("accept adopted generation"); -} - -#[tokio::test] -async fn different_start_generation_is_rejected() { - let directory = TempDir::new().expect("create temporary directory"); - let path = directory.path().join(START_GENERATION_FILE); - fs::write(&path, "generation-one").expect("write active marker"); - let requested = openshell_core::sandbox_generation::SandboxGenerationId::parse( - "generation-two".to_string(), - ) - .expect("valid generation"); - - let error = adopt_or_verify_docker_start_generation_path(&path, &requested) - .await - .expect_err("reject a different generation"); - - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert!(error.message().contains("generation-one")); -} - -#[test] -fn admission_provisioning_failure_distinguishes_denials_from_lookup_failures() { - let denied = DockerProvisioningFailure::from_admission_status(Status::failed_precondition( - "volume is not admitted", - )); - assert_eq!(denied.reason, "ResourceAdmissionDenied"); - assert_eq!(denied.message, "volume is not admitted"); - - let lookup = DockerProvisioningFailure::from_admission_status(Status::internal( - "inspect docker volume failed", - )); - assert_eq!(lookup.reason, "ResourceAdmissionLookupFailed"); - assert_eq!(lookup.message, "inspect docker volume failed"); -} - -#[test] -fn normalize_pull_reference_appends_latest_only_when_untagged() { - // A bare repository reference must resolve to a single tag so the daemon - // does not pull every tag in the repository (issue #4029). - assert_eq!( - normalize_pull_reference("nicolaka/netshoot"), - "nicolaka/netshoot:latest" - ); - // An explicit tag is preserved untouched. - assert_eq!(normalize_pull_reference("foo:1.2"), "foo:1.2"); - // A digest-pinned reference already names an exact image. - assert_eq!( - normalize_pull_reference( - "foo@sha256:0000000000000000000000000000000000000000000000000000000000000000" - ), - "foo@sha256:0000000000000000000000000000000000000000000000000000000000000000" - ); - // A registry port is not a tag, so `:latest` is still appended. - assert_eq!( - normalize_pull_reference("registry:5000/team/app"), - "registry:5000/team/app:latest" - ); - // A registry port combined with an explicit tag is left unchanged. - assert_eq!( - normalize_pull_reference("registry:5000/team/app:v1"), - "registry:5000/team/app:v1" - ); -} diff --git a/crates/openshell-driver-docker/src/workspace.rs b/crates/openshell-driver-docker/src/workspace.rs deleted file mode 100644 index 9c0cc1a85d..0000000000 --- a/crates/openshell-driver-docker/src/workspace.rs +++ /dev/null @@ -1,806 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Opt-in workspace storage, separate from disposable runtime/channel volumes. - -use super::{ - DockerDriverRuntimeConfig, DockerImageMetadata, DriverSandbox, LABEL_ISOLATION_BACKEND, - LABEL_ISOLATION_BACKEND_OPEN_SHELL, LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, - LABEL_SANDBOX_NAMESPACE, LABEL_SANDBOX_WORKSPACE, docker_channel_volume_name_by_id, - docker_volume_identity, driver_mounts, is_not_found_error, remove_docker_volume, -}; -use bollard::Docker; -use bollard::models::{ - ContainerInspectResponse, Mount, MountTypeEnum, MountVolumeOptions, Volume, VolumeCreateRequest, -}; -use openshell_isolation_interface::contract::ResolvedWorkloadIdentity; -use serde::{Deserialize, Serialize}; -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use tonic::Status; - -pub const ROLE_LABEL: &str = "openshell.ai/storage-role"; -pub const ROLE: &str = "workspace"; -pub const RECORD_FILE: &str = "workspace-storage.json"; -pub const RECORD_CLAIM: &str = "docker.workspace_storage"; -const MAX_RECORD_BYTES: u64 = 16 * 1024; - -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -struct Record { - version: u32, - namespace: String, - sandbox_id: String, - uid: u32, - gid: u32, - volume_identity: serde_json::Value, -} - -pub fn record_path(id: &str, config: &DockerDriverRuntimeConfig) -> Result { - Ok(super::docker_boundary_state_dir_by_id(id, config)?.join(RECORD_FILE)) -} - -pub fn record_bytes( - id: &str, - config: &DockerDriverRuntimeConfig, - volume: &Volume, - identity: &ResolvedWorkloadIdentity, -) -> Result, Status> { - serde_json::to_vec(&Record { - version: 1, - namespace: config.sandbox_namespace.clone(), - sandbox_id: id.into(), - uid: identity.uid, - gid: identity.gid, - volume_identity: docker_volume_identity(volume), - }) - .map_err(|_| Status::internal("encode private Docker workspace record")) -} - -fn read_record(id: &str, config: &DockerDriverRuntimeConfig) -> Result, Status> { - let path = record_path(id, config)?; - let metadata = match std::fs::symlink_metadata(&path) { - Ok(metadata) => metadata, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(_) => { - return Err(Status::failed_precondition( - "private Docker workspace record cannot be read", - )); - } - }; - if !metadata.is_file() || metadata.len() > MAX_RECORD_BYTES { - return Err(Status::failed_precondition( - "private Docker workspace record must be a bounded regular file", - )); - } - let record: Record = serde_json::from_slice(&std::fs::read(path).map_err(|_| { - Status::failed_precondition("private Docker workspace record cannot be read") - })?) - .map_err(|_| Status::failed_precondition("private Docker workspace record is invalid"))?; - if record.version != 1 - || record.namespace != config.sandbox_namespace - || record.sandbox_id != id - || record.uid == 0 - || record.gid == 0 - || record - .volume_identity - .get("name") - .and_then(serde_json::Value::as_str) - != Some(volume_name(id, config).as_str()) - { - return Err(Status::failed_precondition( - "private Docker workspace record belongs to another resource", - )); - } - Ok(Some(record)) -} - -pub fn record_claim( - id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result, Status> { - read_record(id, config)? - .map(|record| { - serde_json::to_string(&record) - .map_err(|_| Status::internal("encode private Docker workspace claim")) - }) - .transpose() -} - -async fn load_record( - id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result, Status> { - let record = read_record(id, config)?; - let descriptor = super::read_docker_runtime_descriptor(id, config).await?; - let claim = descriptor - .as_ref() - .and_then(|descriptor| descriptor.resource_claims.get(RECORD_CLAIM)); - match (&record, claim) { - (None, None) => return Ok(None), // Legacy container: labels are caller data. - (None, Some(_)) => { - return Err(Status::failed_precondition( - "private Docker workspace record is missing", - )); - } - (Some(record), Some(claim)) => { - if serde_json::to_string(record) - .map_err(|_| Status::internal("encode private Docker workspace claim"))? - != *claim - { - return Err(Status::failed_precondition( - "private Docker workspace record and descriptor disagree", - )); - } - } - (Some(_), None) if descriptor.is_some() => { - return Err(Status::failed_precondition( - "Docker descriptor lacks its private workspace claim", - )); - } - (Some(_), None) => {} // Fresh create: record precedes container/descriptor. - } - if let (Some(record), Some(descriptor)) = (&record, descriptor) - && (descriptor.boundary_id != id - || descriptor.workload_identity.uid != record.uid - || descriptor.workload_identity.gid != record.gid) - { - return Err(Status::failed_precondition( - "private Docker workspace runtime identity changed", - )); - } - Ok(record) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Storage { - WritableLayer, - Persistent, -} - -const UID_LABEL: &str = "openshell.ai/workspace-uid"; -const GID_LABEL: &str = "openshell.ai/workspace-gid"; - -fn volume_name(sandbox_id: &str, config: &DockerDriverRuntimeConfig) -> String { - docker_channel_volume_name_by_id(sandbox_id, config).replacen( - "openshell-channel-", - "openshell-workspace-", - 1, - ) -} - -pub fn mount( - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - image: &DockerImageMetadata, -) -> Result, Status> { - if config.workspace_storage != Storage::Persistent { - return Ok(None); - } - let root = driver_mounts::resolve_oci_workspace_root(&image.working_dir) - .map_err(Status::failed_precondition)?; - if root != driver_mounts::DEFAULT_WORKSPACE_ROOT { - return Err(Status::failed_precondition( - "persistent Docker workspaces currently require /sandbox", - )); - } - if image - .volumes - .iter() - .any(|target| Path::new(target).starts_with(&root) || Path::new(&root).starts_with(target)) - { - return Err(Status::failed_precondition( - "image-declared volumes overlap the persistent Docker workspace", - )); - } - Ok(Some(Mount { - target: Some(root), - source: Some(volume_name(&sandbox.id, config)), - typ: Some(MountTypeEnum::VOLUME), - read_only: Some(false), - volume_options: Some(MountVolumeOptions { - no_copy: Some(true), - ..Default::default() - }), - ..Default::default() - })) -} - -fn ownership_labels( - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> HashMap { - HashMap::from([ - (LABEL_MANAGED_BY.into(), LABEL_MANAGED_BY_VALUE.into()), - (LABEL_SANDBOX_ID.into(), sandbox_id.into()), - ( - LABEL_SANDBOX_NAMESPACE.into(), - config.sandbox_namespace.clone(), - ), - ( - LABEL_ISOLATION_BACKEND.into(), - LABEL_ISOLATION_BACKEND_OPEN_SHELL.into(), - ), - (ROLE_LABEL.into(), ROLE.into()), - ]) -} - -fn validate_volume( - volume: &Volume, - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result<(), Status> { - if volume.name != volume_name(sandbox_id, config) - || volume.driver != "local" - || !volume.options.is_empty() - || ownership_labels(sandbox_id, config) - .iter() - .any(|(key, value)| volume.labels.get(key) != Some(value)) - { - return Err(Status::failed_precondition( - "persistent Docker workspace ownership changed", - )); - } - Ok(()) -} - -pub async fn prepare( - docker: &Docker, - sandbox: &DriverSandbox, - config: &DockerDriverRuntimeConfig, - image: &DockerImageMetadata, - identity: &ResolvedWorkloadIdentity, -) -> Result, Status> { - if mount(sandbox, config, image)?.is_none() { - return Ok(None); - } - if read_record(&sandbox.id, config)?.is_some() { - return Err(Status::failed_precondition( - "persistent Docker workspace is already recorded; explicit recovery or removal is required", - )); - } - let name = volume_name(&sandbox.id, config); - // Initial creation must not adopt an existing data volume. Recovery/update - // will use the recorded volume identity, rather than this creation path. - match docker.inspect_volume(&name).await { - Ok(_) => { - return Err(Status::failed_precondition( - "persistent Docker workspace already exists; explicit recovery or removal is required", - )); - } - Err(error) if is_not_found_error(&error) => {} - Err(error) => { - return Err(Status::unavailable(format!( - "inspect persistent Docker workspace: {error}" - ))); - } - } - let mut labels = ownership_labels(&sandbox.id, config); - labels.insert(LABEL_SANDBOX_WORKSPACE.into(), sandbox.workspace.clone()); - labels.insert(UID_LABEL.into(), identity.uid.to_string()); - labels.insert(GID_LABEL.into(), identity.gid.to_string()); - let volume = docker - .create_volume(VolumeCreateRequest { - name: Some(name), - driver: Some("local".into()), - labels: Some(labels.clone()), - ..Default::default() - }) - .await - .map_err(|error| { - Status::unavailable(format!("create persistent Docker workspace: {error}")) - })?; - validate_volume(&volume, &sandbox.id, config)?; - if labels - .iter() - .any(|(key, value)| volume.labels.get(key) != Some(value)) - { - return Err(Status::failed_precondition( - "persistent Docker workspace initialization identity changed", - )); - } - super::prepare_docker_boundary_state_dir(sandbox, config)?; - let bytes = record_bytes(&sandbox.id, config, &volume, identity)?; - if bytes.len() as u64 > MAX_RECORD_BYTES { - return Err(Status::failed_precondition( - "private Docker workspace record exceeds its bound", - )); - } - super::image_update::durable_write(&record_path(&sandbox.id, config)?, &bytes)?; - Ok(Some(volume)) -} - -fn validate_attachment( - container: &ContainerInspectResponse, - volume: &Volume, - recorded: &serde_json::Value, - config: &DockerDriverRuntimeConfig, -) -> Result<(), Status> { - let labels = container - .config - .as_ref() - .and_then(|config| config.labels.as_ref()) - .ok_or_else(|| { - Status::failed_precondition("persistent Docker workspace lacks sandbox ownership") - })?; - let id = labels - .get(LABEL_SANDBOX_ID) - .filter(|id| !id.is_empty()) - .ok_or_else(|| { - Status::failed_precondition("persistent Docker workspace lacks sandbox ID") - })?; - validate_volume(volume, id, config)?; - let matching_mounts = container - .mounts - .as_deref() - .unwrap_or_default() - .iter() - .filter(|mount| mount.destination.as_deref() == Some(driver_mounts::DEFAULT_WORKSPACE_ROOT)) - .collect::>(); - let user = container - .config - .as_ref() - .and_then(|config| config.user.as_deref()); - let expected_user = match (volume.labels.get(UID_LABEL), volume.labels.get(GID_LABEL)) { - (Some(uid), Some(gid)) => format!("{uid}:{gid}"), - _ => { - return Err(Status::failed_precondition( - "persistent Docker workspace lacks workload identity", - )); - } - }; - if labels.get(LABEL_SANDBOX_NAMESPACE) != Some(&config.sandbox_namespace) - || labels.get(LABEL_SANDBOX_WORKSPACE) != volume.labels.get(LABEL_SANDBOX_WORKSPACE) - || user != Some(expected_user.as_str()) - || *recorded != docker_volume_identity(volume) - || matching_mounts.len() != 1 - || matching_mounts[0].typ != Some(bollard::models::MountPointTypeEnum::VOLUME) - || matching_mounts[0].name.as_deref() != Some(volume.name.as_str()) - || matching_mounts[0].rw != Some(true) - { - return Err(Status::failed_precondition( - "persistent Docker workspace attachment or identity changed", - )); - } - Ok(()) -} - -pub async fn admit( - docker: &Docker, - container: &ContainerInspectResponse, - config: &DockerDriverRuntimeConfig, -) -> Result { - let Some(id) = container - .config - .as_ref() - .and_then(|config| config.labels.as_ref()) - .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) - .filter(|id| !id.is_empty()) - else { - return Ok(false); - }; - let Some(record) = load_record(id, config).await? else { - return Ok(false); - }; - if container - .config - .as_ref() - .and_then(|value| value.user.as_deref()) - != Some(format!("{}:{}", record.uid, record.gid).as_str()) - { - return Err(Status::failed_precondition( - "persistent Docker workspace workload identity changed", - )); - } - let name = volume_name(id, config); - let volume = docker.inspect_volume(&name).await.map_err(|error| { - Status::unavailable(format!("inspect retained Docker workspace: {error}")) - })?; - validate_attachment(container, &volume, &record.volume_identity, config)?; - Ok(true) -} - -pub async fn remove( - docker: &Docker, - sandbox_id: &str, - config: &DockerDriverRuntimeConfig, -) -> Result<(), Status> { - let Some(record) = load_record(sandbox_id, config).await? else { - return Ok(()); - }; - let name = volume_name(sandbox_id, config); - let volume = match docker.inspect_volume(&name).await { - Ok(volume) => volume, - Err(error) if is_not_found_error(&error) => return Ok(()), - Err(error) => { - return Err(Status::unavailable(format!( - "inspect Docker workspace for removal: {error}" - ))); - } - }; - validate_volume(&volume, sandbox_id, config)?; - if docker_volume_identity(&volume) != record.volume_identity { - return Err(Status::failed_precondition( - "persistent Docker workspace identity changed before removal", - )); - } - // Docker refuses removal while another container still uses the volume. - remove_docker_volume(docker, &name).await -} - -#[cfg(test)] -pub mod tests { - use super::*; - use crate::tests::{ - runtime_config, test_driver_with_config, test_sandbox, test_workload_identity, - }; - use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; - - // Exercise the real Bollard request/response path, without a Docker engine. - pub async fn docker_api( - replies: Vec<(&'static str, String, u16, serde_json::Value)>, - ) -> (Docker, tokio::task::JoinHandle>) { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let endpoint = format!("http://{}", listener.local_addr().unwrap()); - let task = tokio::spawn(async move { - let mut requests = Vec::new(); - for (method, suffix, status, response) in replies { - let (mut stream, _) = listener.accept().await.unwrap(); - let mut bytes = Vec::new(); - let (header_end, body_size) = loop { - let mut buffer = [0_u8; 4096]; - let count = stream.read(&mut buffer).await.unwrap(); - assert!(count > 0, "incomplete Docker request"); - bytes.extend_from_slice(&buffer[..count]); - assert!(bytes.len() < 65536, "oversized Docker request"); - if let Some(end) = bytes.windows(4).position(|v| v == b"\r\n\r\n") { - let headers = std::str::from_utf8(&bytes[..end]).unwrap(); - let size = headers - .lines() - .find_map(|line| { - let (key, value) = line.split_once(':')?; - key.eq_ignore_ascii_case("content-length") - .then(|| value.trim().parse::().unwrap()) - }) - .unwrap_or(0); - break (end + 4, size); - } - }; - while bytes.len() < header_end + body_size { - let mut buffer = [0_u8; 4096]; - let count = stream.read(&mut buffer).await.unwrap(); - assert!(count > 0); - bytes.extend_from_slice(&buffer[..count]); - } - let request_line = std::str::from_utf8(&bytes[..header_end]) - .unwrap() - .lines() - .next() - .unwrap(); - let fields = request_line.split_whitespace().collect::>(); - assert_eq!(fields[0], method); - assert!( - fields[1].ends_with(&suffix), - "unexpected path: {}", - fields[1] - ); - requests.push(if body_size == 0 { - serde_json::Value::Null - } else { - serde_json::from_slice(&bytes[header_end..header_end + body_size]).unwrap() - }); - let body = response.to_string(); - let reply = format!( - "HTTP/1.1 {status} Response\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", - body.len() - ); - stream.write_all(reply.as_bytes()).await.unwrap(); - } - requests - }); - ( - Docker::connect_with_http(&endpoint, 2, bollard::API_DEFAULT_VERSION).unwrap(), - task, - ) - } - - fn fixture() -> (ContainerInspectResponse, Volume, DockerDriverRuntimeConfig) { - let mut config = runtime_config(); - config.sandbox_namespace = - format!("workspace-test-{}", openshell_core::SandboxSessionId::new()); - fixture_for(test_sandbox(), config) - } - - fn save_fixture_record(volume: &Volume, config: &DockerDriverRuntimeConfig) -> PathBuf { - let sandbox = test_sandbox(); - let directory = super::super::prepare_docker_boundary_state_dir(&sandbox, config).unwrap(); - super::super::image_update::durable_write( - &directory.join(RECORD_FILE), - &record_bytes(&sandbox.id, config, volume, &test_workload_identity()).unwrap(), - ) - .unwrap(); - directory - } - - pub fn fixture_for( - sandbox: DriverSandbox, - config: DockerDriverRuntimeConfig, - ) -> (ContainerInspectResponse, Volume, DockerDriverRuntimeConfig) { - let identity = test_workload_identity(); - let mut labels = ownership_labels(&sandbox.id, &config); - labels.insert(LABEL_SANDBOX_WORKSPACE.into(), sandbox.workspace.clone()); - labels.insert(UID_LABEL.into(), identity.uid.to_string()); - labels.insert(GID_LABEL.into(), identity.gid.to_string()); - let volume: Volume = serde_json::from_value(serde_json::json!({ - "Name": volume_name(&sandbox.id, &config), "Driver": "local", "Options": {}, - "Labels": labels, "Mountpoint": "/synthetic/workspace", "Scope": "local", "CreatedAt": "2026-11-10T00:00:00Z" - })).unwrap(); - let labels = HashMap::from([ - (LABEL_SANDBOX_ID.to_string(), sandbox.id), - ( - LABEL_SANDBOX_NAMESPACE.to_string(), - config.sandbox_namespace.clone(), - ), - (LABEL_SANDBOX_WORKSPACE.to_string(), sandbox.workspace), - ]); - let container = serde_json::from_value(serde_json::json!({ - "Config": {"Labels": labels, "User": format!("{}:{}", identity.uid, identity.gid)}, - "Mounts": [{"Type": "volume", "Name": volume.name, "Destination": "/sandbox", "RW": true}] - })).unwrap(); - (container, volume, config) - } - - #[tokio::test] - async fn legacy_workspace_labels_are_not_a_driver_storage_record() { - // These keys were previously accepted as arbitrary template labels. - // Their values, even persistent-v1 or invalid JSON, must not turn an - // existing writable-layer container into a driver-owned volume claim. - for labels in [ - serde_json::json!({"openshell.ai/workspace-storage":"persistent-v1"}), - serde_json::json!({"openshell.ai/workspace-volume-identity":"not-json"}), - serde_json::json!({"openshell.ai/workspace-storage":"persistent-v1", "openshell.ai/workspace-volume-identity":"not-json"}), - serde_json::json!({"openshell.ai/docker-workspace-storage":"persistent-v1", "openshell.ai/docker-workspace-volume-identity":"not-json"}), - ] { - let mut labels = labels; - labels[LABEL_SANDBOX_ID] = "sbx-123".into(); - let container = - serde_json::from_value(serde_json::json!({"Config":{"Labels":labels}})).unwrap(); - let (_, _, config) = fixture(); - let (docker, server) = docker_api(vec![]).await; - assert!(!admit(&docker, &container, &config).await.unwrap()); - server.await.unwrap(); - } - } - - #[tokio::test] - async fn legacy_removal_never_probes_or_removes_an_unrecorded_workspace() { - let (_, _, config) = fixture(); - let (docker, server) = docker_api(vec![]).await; - remove(&docker, "sbx-123", &config).await.unwrap(); - assert!(server.await.unwrap().is_empty()); - } - - #[test] - fn failed_creation_keeps_storage_authority_until_explicit_deletion() { - let (_, volume, config) = fixture(); - let sandbox = test_sandbox(); - let directory = save_fixture_record(&volume, &config); - super::super::cleanup_failed_docker_boundary_state(&sandbox, &config); - assert!(record_claim(&sandbox.id, &config).unwrap().is_some()); - super::super::cleanup_docker_boundary_state(&sandbox, &config); - assert!(!directory.exists()); - - let directory = super::super::prepare_docker_boundary_state_dir(&sandbox, &config).unwrap(); - super::super::cleanup_failed_docker_boundary_state(&sandbox, &config); - assert!(!directory.exists()); - } - - #[test] - fn retained_workspace_requires_original_volume_identity() { - let (container, mut volume, config) = fixture(); - let recorded = docker_volume_identity(&volume); - validate_attachment(&container, &volume, &recorded, &config).unwrap(); - volume.created_at = Some("2026-11-11T00:00:00Z".into()); - assert!(validate_attachment(&container, &volume, &recorded, &config).is_err()); - } - - #[test] - fn retained_workspace_rejects_foreign_backing_and_workload_user() { - let (mut container, mut volume, config) = fixture(); - let recorded = docker_volume_identity(&volume); - container.config.as_mut().unwrap().user = Some("2000:2000".into()); - assert!(validate_attachment(&container, &volume, &recorded, &config).is_err()); - volume - .options - .insert("device".into(), "/private/foreign".into()); - assert!(validate_volume(&volume, "sbx-123", &config).is_err()); - } - - #[test] - fn retained_workspace_rejects_unrecorded_mount_and_foreign_namespace() { - let (mut container, mut volume, config) = fixture(); - let recorded = docker_volume_identity(&volume); - volume - .labels - .insert(LABEL_SANDBOX_NAMESPACE.into(), "foreign".into()); - assert!(validate_volume(&volume, "sbx-123", &config).is_err()); - container.mounts = None; - assert!(validate_attachment(&container, &volume, &recorded, &config).is_err()); - } - - #[tokio::test] - async fn legacy_custom_workspace_mount_keeps_existing_admission_path() { - let container = serde_json::from_value(serde_json::json!({ - "Config": {"Labels": {}, "WorkingDir": "/project"}, - "Mounts": [{"Type":"volume", "Name":"external-data", "Destination":"/sandbox", "RW":true}] - })).unwrap(); - let (docker, server) = docker_api(vec![]).await; - assert!(!admit(&docker, &container, &runtime_config()).await.unwrap()); - server.await.unwrap(); - } - - #[test] - fn persistent_layout_is_opt_in_and_rejects_custom_workdir_and_nested_image_volume() { - let sandbox = test_sandbox(); - let mut config = runtime_config(); - let mut image = DockerImageMetadata { - id: "image".into(), - user: "1000:1000".into(), - working_dir: "/sandbox".into(), - volumes: vec![], - }; - assert!(mount(&sandbox, &config, &image).unwrap().is_none()); - config.workspace_storage = Storage::Persistent; - let persistent = mount(&sandbox, &config, &image).unwrap().unwrap(); - assert_eq!(persistent.volume_options.unwrap().no_copy, Some(true)); - image.working_dir = "/custom".into(); - assert!(mount(&sandbox, &config, &image).is_err()); - image.working_dir = "/sandbox".into(); - image.volumes.push("/sandbox/cache".into()); - assert!(mount(&sandbox, &config, &image).is_err()); - } - - #[tokio::test] - async fn creation_refuses_existing_data_without_relabeling_it() { - let (_, volume, mut config) = fixture(); - config.workspace_storage = Storage::Persistent; - let path = format!("/volumes/{}", volume.name); - let (docker, server) = docker_api(vec![( - "GET", - path, - 200, - serde_json::to_value(&volume).unwrap(), - )]) - .await; - let image = DockerImageMetadata { - id: "image".into(), - user: "1234:1235".into(), - working_dir: "/sandbox".into(), - volumes: vec![], - }; - let error = prepare( - &docker, - &test_sandbox(), - &config, - &image, - &test_workload_identity(), - ) - .await - .unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - assert_eq!(server.await.unwrap().len(), 1); - } - - #[tokio::test] - async fn creation_records_only_fresh_owned_workspace_storage() { - let (_, volume, mut config) = fixture(); - config.workspace_storage = Storage::Persistent; - let path = format!("/volumes/{}", volume.name); - let (docker, server) = docker_api(vec![ - ("GET", path, 404, serde_json::json!({"message":"not found"})), - ( - "POST", - "/volumes/create".into(), - 201, - serde_json::to_value(&volume).unwrap(), - ), - ]) - .await; - let image = DockerImageMetadata { - id: "image".into(), - user: "1234:1235".into(), - working_dir: "/sandbox".into(), - volumes: vec![], - }; - let created = prepare( - &docker, - &test_sandbox(), - &config, - &image, - &test_workload_identity(), - ) - .await - .unwrap() - .unwrap(); - assert_eq!( - docker_volume_identity(&created), - docker_volume_identity(&volume) - ); - let requests = server.await.unwrap(); - assert_eq!(requests[1]["Name"], volume.name); - assert_eq!(requests[1]["Driver"], "local"); - assert_eq!(requests[1]["Labels"][ROLE_LABEL], ROLE); - assert!(record_claim("sbx-123", &config).unwrap().is_some()); - std::fs::remove_dir_all(record_path("sbx-123", &config).unwrap().parent().unwrap()) - .unwrap(); - } - - #[tokio::test] - async fn disabling_external_admission_does_not_adopt_recreated_workspace_volume() { - let (container, mut volume, config) = fixture(); - assert!(config.allow_driver_config && !config.resource_admission.enabled); - let directory = save_fixture_record(&volume, &config); - volume.created_at = Some("2026-11-11T00:00:00Z".into()); - let (docker, server) = docker_api(vec![( - "GET", - format!("/volumes/{}", volume.name), - 200, - serde_json::to_value(&volume).unwrap(), - )]) - .await; - let mut driver = test_driver_with_config(config); - driver.docker = std::sync::Arc::new(docker); - let error = driver - .admit_container_resources(&container) - .await - .unwrap_err(); - assert_eq!(error.code(), tonic::Code::FailedPrecondition); - server.await.unwrap(); - std::fs::remove_dir_all(directory).unwrap(); - } - - #[tokio::test] - async fn removal_checks_ownership_and_never_forces_an_in_use_volume() { - let (_, mut volume, config) = fixture(); - let original = volume.clone(); - let directory = save_fixture_record(&volume, &config); - volume - .labels - .insert(LABEL_SANDBOX_NAMESPACE.into(), "foreign".into()); - let path = format!("/volumes/{}", volume.name); - let (docker, server) = docker_api(vec![( - "GET", - path.clone(), - 200, - serde_json::to_value(&volume).unwrap(), - )]) - .await; - assert_eq!( - remove(&docker, "sbx-123", &config) - .await - .unwrap_err() - .code(), - tonic::Code::FailedPrecondition - ); - server.await.unwrap(); - let volume = original; - let (docker, server) = docker_api(vec![ - ( - "GET", - path.clone(), - 200, - serde_json::to_value(&volume).unwrap(), - ), - ( - "DELETE", - path, - 409, - serde_json::json!({"message":"volume in use"}), - ), - ]) - .await; - assert!(remove(&docker, "sbx-123", &config).await.is_err()); - server.await.unwrap(); - std::fs::remove_dir_all(directory).unwrap(); - } -} diff --git a/crates/openshell-driver-docker/tests/fixtures/image-update/Dockerfile b/crates/openshell-driver-docker/tests/fixtures/image-update/Dockerfile deleted file mode 100644 index 7ac1dce075..0000000000 --- a/crates/openshell-driver-docker/tests/fixtures/image-update/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -FROM alpine@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8 -ARG VERSION -ARG WORKLOAD_USER=1234:1235 -RUN mkdir -p /app \ - && printf '%s\n' "$VERSION" > /app/version \ - && printf 'other:x:2000:2000::/sandbox:/bin/sh\n' >> /etc/passwd \ - && printf 'other:x:2000:\n' >> /etc/group -USER ${WORKLOAD_USER} -WORKDIR /sandbox diff --git a/crates/openshell-driver-docker/tests/serve_configure.rs b/crates/openshell-driver-docker/tests/serve_configure.rs deleted file mode 100644 index 28ca4b1d62..0000000000 --- a/crates/openshell-driver-docker/tests/serve_configure.rs +++ /dev/null @@ -1,317 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Runs the real `openshell-driver-docker` binary through `serve` and -//! `preflight` against a fake Docker API socket. - -#![cfg(unix)] - -use std::io::{Read as _, Write as _}; -use std::os::unix::net::UnixListener; -use std::path::Path; -use std::process::{Child, Command, Output, Stdio}; -use std::time::{Duration, Instant}; - -use hyper_util::rt::TokioIo; -use openshell_core::proto::compute::v1::GetCapabilitiesRequest; -use openshell_core::proto::compute::v1::UpdateSandboxConfigurationRequest; -use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; -use openshell_core::proto::compute::v1::compute_driver_configuration_updates_client::ComputeDriverConfigurationUpdatesClient; -use openshell_driver_sdk::launch::proto::driver_launch_client::DriverLaunchClient; -use openshell_driver_sdk::launch::{ - ConfigureRequest, GetLaunchInfoRequest, PROTOCOL_VERSION, ShutdownRequest, -}; -use tonic::Code; -use tonic::transport::{Channel, Endpoint}; - -const BIN: &str = env!("CARGO_BIN_EXE_openshell-driver-docker"); - -fn command(args: &[&str], table: &str, dir: &Path) -> Command { - // The table is a file, as the gateway provides it, so it always ends. - let stdin = dir.join("table.toml"); - std::fs::write(&stdin, table).unwrap(); - let mut command = Command::new(BIN); - command - .args(args) - .env_remove("DOCKER_HOST") - .stdin(std::fs::File::open(stdin).unwrap()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()); - command -} - -fn run(args: &[&str], table: &str) -> Output { - let dir = tempfile::tempdir().unwrap(); - command(args, table, dir.path()).output().unwrap() -} - -/// A Docker API that answers every request with `200 OK`. -fn fake_docker(path: &Path) { - let listener = UnixListener::bind(path).unwrap(); - std::thread::spawn(move || { - for stream in listener.incoming() { - let Ok(mut stream) = stream else { continue }; - let mut buffer = [0_u8; 4096]; - let _ = stream.read(&mut buffer); - let _ = stream - .write_all(b"HTTP/1.1 200 OK\r\nApi-Version: 1.45\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK"); - } - }); -} - -struct Serving { - child: Child, - channel: Channel, - _dir: tempfile::TempDir, -} - -impl Drop for Serving { - fn drop(&mut self) { - let _ = self.child.kill(); - let _ = self.child.wait(); - } -} - -async fn connect(path: &Path) -> Option { - let path = path.to_path_buf(); - Endpoint::try_from("http://localhost") - .unwrap() - .connect_with_connector(tower::service_fn(move |_| { - let path = path.clone(); - async move { - Ok::<_, std::io::Error>(TokioIo::new(tokio::net::UnixStream::connect(path).await?)) - } - })) - .await - .ok() -} - -async fn serve() -> Serving { - let dir = tempfile::tempdir().unwrap(); - let docker = dir.path().join("docker.sock"); - fake_docker(&docker); - let socket = dir.path().join("driver.sock"); - let table = format!("socket_path = \"{}\"\n", docker.display()); - let mut child = command( - &[ - "serve", - "--bind-socket", - socket.to_str().unwrap(), - "--expected-peer-pid", - &std::process::id().to_string(), - ], - &table, - dir.path(), - ) - .spawn() - .unwrap(); - let deadline = Instant::now() + Duration::from_mins(1); - loop { - if let Some(status) = child.try_wait().unwrap() { - panic!("driver exited early: {status}"); - } - if let Some(channel) = connect(&socket).await { - return Serving { - child, - channel, - _dir: dir, - }; - } - assert!( - Instant::now() < deadline, - "driver never accepted a connection" - ); - tokio::time::sleep(Duration::from_millis(50)).await; - } -} - -fn configure(version: u32) -> ConfigureRequest { - ConfigureRequest { - protocol_version: version, - gateway: Some(openshell_driver_sdk::launch::GatewayContext { - gateway_port: 8080, - bind_address: "127.0.0.1:8080".to_string(), - ..Default::default() - }), - ..Default::default() - } -} - -#[tokio::test] -async fn launch_info_answers_and_compute_calls_wait_for_configure() { - let serving = serve().await; - - let info = DriverLaunchClient::new(serving.channel.clone()) - .get_launch_info(GetLaunchInfoRequest {}) - .await - .unwrap() - .into_inner(); - assert_eq!(info.driver_name, "docker"); - assert_eq!(info.protocol_versions, [PROTOCOL_VERSION]); - - let status = ComputeDriverClient::new(serving.channel.clone()) - .get_capabilities(GetCapabilitiesRequest::default()) - .await - .unwrap_err(); - assert_eq!(status.code(), Code::Unavailable); - - // The configuration-updates service is gated the same way. - let status = ComputeDriverConfigurationUpdatesClient::new(serving.channel.clone()) - .update_sandbox_configuration(UpdateSandboxConfigurationRequest::default()) - .await - .unwrap_err(); - assert_eq!(status.code(), Code::Unavailable); -} - -#[tokio::test] -async fn a_failed_configure_leaves_the_driver_running_for_a_retry() { - let mut serving = serve().await; - let mut client = DriverLaunchClient::new(serving.channel.clone()); - - let unsupported = client - .configure(configure(PROTOCOL_VERSION + 1)) - .await - .unwrap_err(); - assert_eq!(unsupported.code(), Code::FailedPrecondition); - - // The fake Docker cannot describe itself, so construction fails here. - let failed = client - .configure(configure(PROTOCOL_VERSION)) - .await - .unwrap_err(); - assert_ne!(failed.code(), Code::Ok); - assert!(serving.child.try_wait().unwrap().is_none()); - - let retried = client - .configure(configure(PROTOCOL_VERSION)) - .await - .unwrap_err(); - assert_ne!(retried.code(), Code::FailedPrecondition, "{retried}"); - let still_unavailable = ComputeDriverClient::new(serving.channel.clone()) - .get_capabilities(GetCapabilitiesRequest::default()) - .await - .unwrap_err(); - assert_eq!(still_unavailable.code(), Code::Unavailable); -} - -fn report_of(output: &Output) -> openshell_driver_sdk::StartReport { - let stdout = String::from_utf8_lossy(&output.stdout); - openshell_driver_sdk::StartReport::from_output(&stdout) - .unwrap_or_else(|| panic!("no report line in: {stdout}")) -} - -const SERVE_ARGS: [&str; 5] = [ - "serve", - "--bind-socket", - "/nonexistent/driver.sock", - "--expected-peer-pid", - "1", -]; - -#[test] -fn an_invalid_table_exits_with_the_config_code_and_one_json_line() { - let output = run(&SERVE_ARGS, "no_such_key = 1"); - assert_eq!(output.status.code(), Some(78)); - let report = report_of(&output); - assert_eq!(report.kind, openshell_driver_sdk::StartKind::InvalidConfig); - assert!(report.reason.contains("no_such_key"), "{}", report.reason); -} - -#[test] -fn an_unreachable_socket_exits_as_unavailable() { - let output = run(&SERVE_ARGS, "socket_path = \"/nonexistent/docker.sock\""); - assert_eq!(output.status.code(), Some(69)); - assert_eq!( - report_of(&output).kind, - openshell_driver_sdk::StartKind::Unavailable - ); -} - -#[test] -fn preflight_accepts_a_valid_table_without_contacting_docker() { - let table = "socket_path = \"/nonexistent/docker.sock\"\nsandbox_label = \"example\"\n"; - let output = run(&["preflight"], table); - assert_eq!(output.status.code(), Some(0), "{:?}", output.stdout); - assert_eq!(run(&["preflight"], "").status.code(), Some(0)); -} - -#[test] -fn preflight_rejects_an_unknown_key() { - let output = run(&["preflight"], "no_such_key = 1"); - assert_eq!(output.status.code(), Some(78)); - assert_eq!( - report_of(&output).kind, - openshell_driver_sdk::StartKind::InvalidConfig - ); -} - -#[test] -fn docker_host_finds_the_socket_when_the_table_sets_none() { - let dir = tempfile::tempdir().unwrap(); - let docker = dir.path().join("docker.sock"); - fake_docker(&docker); - let socket = dir.path().join("driver.sock"); - let mut child = command( - &[ - "serve", - "--bind-socket", - socket.to_str().unwrap(), - "--expected-peer-pid", - &std::process::id().to_string(), - ], - "", - dir.path(), - ) - .env("DOCKER_HOST", format!("unix://{}", docker.display())) - .spawn() - .unwrap(); - let deadline = Instant::now() + Duration::from_secs(30); - while !socket.exists() { - assert!( - child.try_wait().unwrap().is_none(), - "the driver should have found the socket from DOCKER_HOST" - ); - assert!(Instant::now() < deadline, "driver never bound its socket"); - std::thread::sleep(Duration::from_millis(50)); - } - let _ = child.kill(); - let _ = child.wait(); -} - -#[tokio::test] -async fn a_stop_signal_waits_for_the_gateway_to_release_the_driver() { - let mut serving = serve().await; - let signalled = Command::new("kill") - .args(["-TERM", &serving.child.id().to_string()]) - .status() - .unwrap(); - assert!(signalled.success()); - - // The driver defers the signal, so the gateway can still use it. - tokio::time::sleep(Duration::from_millis(500)).await; - assert!( - serving.child.try_wait().unwrap().is_none(), - "the driver stopped on SIGTERM before the gateway released it" - ); - DriverLaunchClient::new(serving.channel.clone()) - .get_launch_info(GetLaunchInfoRequest {}) - .await - .unwrap(); - - DriverLaunchClient::new(serving.channel.clone()) - .shutdown(ShutdownRequest {}) - .await - .unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - let status = loop { - if let Some(status) = serving.child.try_wait().unwrap() { - break status; - } - assert!( - Instant::now() < deadline, - "the driver did not stop after Shutdown" - ); - tokio::time::sleep(Duration::from_millis(50)).await; - }; - assert!(status.success(), "{status}"); -} diff --git a/crates/openshell-driver-podman/Cargo.toml b/crates/openshell-driver-podman/Cargo.toml deleted file mode 100644 index e8604057db..0000000000 --- a/crates/openshell-driver-podman/Cargo.toml +++ /dev/null @@ -1,66 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -[package] -name = "openshell-driver-podman" -description = "Podman compute driver for OpenShell" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true - -[[bin]] -name = "openshell-driver-podman" -path = "src/main.rs" - -[dependencies] -openshell-core = { path = "../openshell-core", default-features = false, features = ["driver-extraction", "otel", "clap"] } -openshell-container-runtime = { path = "../openshell-container-runtime" } -openshell-driver-sdk = { path = "../openshell-driver-sdk" } -openshell-otel = { path = "../openshell-otel" } -openshell-isolation-interface = { path = "../openshell-isolation-interface" } -openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } -tar = "0.4" -tempfile = "3" -uuid = { workspace = true } - -tokio = { workspace = true } -tonic = { workspace = true, features = ["transport"] } -futures = { workspace = true } -tokio-stream = { workspace = true } -hyper = { workspace = true } -hyper-util = { workspace = true } -http-body-util = { workspace = true } -serde = { workspace = true } -serde_json = { workspace = true } -prost-types = { workspace = true } -clap = { workspace = true } -nix = { workspace = true } -rustix = { workspace = true } -tracing = { workspace = true } -tracing-subscriber = { workspace = true } -tracing-opentelemetry = { workspace = true } -opentelemetry = { workspace = true } -opentelemetry_sdk = { workspace = true } -tower-http = { workspace = true } -http = { workspace = true } -thiserror = { workspace = true } -miette = { workspace = true } -sha2 = { workspace = true } -url = { workspace = true } -toml = { workspace = true } - -[dev-dependencies] -hyper-util = { workspace = true } -tower = { workspace = true } -openshell-crypto = { workspace = true } -openshell-otel-test-support = { path = "../openshell-otel-test-support" } -opentelemetry_sdk = { workspace = true, features = ["testing"] } -prost-types = { workspace = true } -rcgen = { workspace = true } -temp-env = "0.3" -tokio = { workspace = true, features = ["test-util"] } - -[lints] -workspace = true diff --git a/crates/openshell-driver-podman/NETWORKING.md b/crates/openshell-driver-podman/NETWORKING.md deleted file mode 100644 index 37361395aa..0000000000 --- a/crates/openshell-driver-podman/NETWORKING.md +++ /dev/null @@ -1,66 +0,0 @@ -# Podman Networking - -Only the external supervisor has external network connectivity. The workload -container uses `network=none`; its loopback DNS relay and TCP socket mediation -reach the supervisor through a protected Unix socket, not a veth or proxy -environment variable. - -```text -workload container supervisor container -agent -> sandbox -- private UDS / gRPC -> policy proxy -> host network -> destination - | - +-- authenticated gateway session -``` - -## Outer network fence - -The driver creates the workload without networks, host aliases, published -ports, or added capabilities. It checks the Podman inspect response before -launch and restart. The sandbox installs seccomp mediation and Landlock before -executing the agent. It does not create network namespaces, configure nftables, -or require `CAP_NET_ADMIN`. - -TCP opens, TCP byte streams, DNS requests/replies, and lifecycle operations -share the authenticated gRPC channel. DNS is resolved and authorized by the -supervisor. General UDP is unsupported. - -The driver mounts a read-only, driver-owned `/etc/resolv.conf` into the -workload with `nameserver 127.0.0.53`. This prevents the disconnected Podman -network namespace from replacing the policy-DNS relay with a runtime resolver. -The supervisor answers `host.openshell.internal` with a trusted concrete -destination: `127.0.0.1` on native Linux, the configured Podman Machine host -address on macOS. That destination is part of the supervisor bootstrap and is -reapplied when a sandbox restarts. - -## Supervisor network - -The supervisor companion uses Podman's host network. On Linux it connects to -the gateway's primary loopback endpoint. On macOS, Podman Machine provides the -host-loopback route. The upstream corporate proxy applies only to the -supervisor. The gateway's SSH tunnel uses the supervisor relay over its private -Unix socket, so the driver does not publish a supervisor port. - -These runtime-managed network helpers are outside the workload trust boundary. -Sharing the workload's user namespace preserves volume UID/GID mapping; it -does not share the workload's PID, mount, or network namespaces. - -## Troubleshooting - -Inspect both containers with the same sandbox-ID label, distinguishing -`openshell.ai/isolation-role=sandbox` from -`openshell.ai/isolation-role=supervisor`. - -- Sandbox fails its qualification probe: use its log to identify the denied - kernel/runtime primitive. Do not add capabilities or disable runtime seccomp. -- Sandbox cannot authenticate to supervisor: check the private channel volume, - matching user namespace mappings, and shared SELinux label. -- Supervisor cannot connect: inspect its configured gateway endpoint, - credentials, host network, and the gateway's primary listener. -- DNS or egress denied: inspect supervisor policy decisions. Do not add a - workload network, resolver bypass, or direct gateway route. -- Pair is not Ready: check the supervisor health socket and gateway session. - A running workload container alone does not establish readiness. - -See the [driver overview](README.md) and -[Podman runtime documentation](https://docs.podman.io/en/latest/markdown/podman-run.1.html) -for runtime options. diff --git a/crates/openshell-driver-podman/README.md b/crates/openshell-driver-podman/README.md deleted file mode 100644 index b60b472b03..0000000000 --- a/crates/openshell-driver-podman/README.md +++ /dev/null @@ -1,179 +0,0 @@ -# openshell-driver-podman - -The Podman compute driver runs as a subprocess of the gateway and uses the native libpod -REST API over a Unix socket. Each sandbox has two independent containers: - -- `openshell-sandbox` owns the agent process in the workload container. -- `openshell-supervisor` evaluates policy, holds gateway credentials, and - proxies approved egress in a separate companion container. - -New containers dial the supervisor over a separate private Unix socket volume -at `/.openshell/channel/control/control.sock`; workload networking remains -`none`. The supervisor's bootstrap-key mount stays read-only. Restart metadata -records the direction, with missing metadata retaining the legacy runtime -listener. Deploy matching supervisor and sandbox runtime binaries for new -containers. - -The driver provisions placement, identity, credentials, transport, and lifecycle. -The shared isolation interface supplies exec, attach, signal, terminate, binary -identity, DNS, TCP, and loopback-forwarding semantics. - -## Runtime posture - -Caller driver config is disabled by default. Existing volumes require -administrator-controlled approval labels; bind and supplemental image mounts -are denied under enforcement. Private-volume names alone do not prove -ownership. GPU devices are temporarily exempt. Admission runs before launch, -restart, and periodically for running workloads. -See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission). - -| Property | Workload | Supervisor | -|---|---|---| -| UID/GID | Pinned non-root workload identity | Same mapped identity | -| Capabilities | Drop all; add none | Drop all; add none | -| Seccomp | Runtime default plus sandbox-installed filters | Runtime default | -| Network | `none`; loopback only | Podman host network | -| Gateway JWT and upstream credentials | Never mounted | Podman secrets | -| User volumes and CDI devices | Workload only | Never mounted | -| Channel | Private named volume, writable | Same volume, read-only | - -Podman creates the namespaces and volume ownership before the workload runs. -Rootless operation uses the operator's Podman service and subordinate-ID -configuration; it does not require adding capabilities to either container. -The supervisor joins the workload's **user namespace only** to preserve UID/GID -mapping for shared-volume access. PID, mount, and network namespaces remain -separate. The channel volume uses shared SELinux relabeling (`:z`). - -Before starting either container, the driver uploads volume-relative archives -directly to the channel and workspace volume destinations. A rootfs upload on a -stopped Podman container does not populate nested named volumes. Restart restores -only the channel bootstrap into the existing channel volume, preserving the -workspace. The workload starts before the supervisor so its user namespace exists -when the supervisor joins it; a stopped supervisor resolves that namespace again -on its next start. The driver creates the managed workspace volume owned by -the workload's final UID and GID, so the workload never starts as root. Custom -image workspaces have no workspace volume or upload. - -The runtime must pass the sandbox's unprivileged enforcement probe, including -nested seccomp notification and Landlock. Unsupported runtime defaults fail -closed; do not switch to an unconfined profile or add capabilities. - -## Protected channel and network enforcement - -```text -agent -> openshell-sandbox === authenticated gRPC / private UDS === supervisor -> network - network=none TCP, DNS, control streams policy + gateway JWT -``` - -The workload has no external interface or published port. Seccomp socket -mediation carries TCP and DNS through one authenticated gRPC connection. -DNS remains supervisor-mediated; general UDP is unsupported. The driver sets -`net.ipv4.ip_unprivileged_port_start=0` in the isolated workload network -namespace so the sandbox's loopback DNS relay can bind port 53 without a -capability. No nftables or nested network namespace setup runs in the sandbox. - -The channel contains the sandbox bootstrap and sandbox-side TLS identity only. -Supervisor private keys and the runtime descriptor stay in the supervisor's private filesystem. -Landlock denies agent access to the top-level `/.openshell` control hierarchy. -The driver verifies Podman's reported `network=none` fence before launch and -restart. Host networking applies to the supervisor, not the agent. - -Gateway sessions use the sandbox JWT and optional server-authenticated TLS. -Only the gateway CA is delivered to the supervisor; user client certificates -and private keys are not mounted into either container. The sandbox/supervisor channel always uses its separate, per-sandbox -mutual TLS material. These are distinct authentication relationships. - -## Identity and trusted binaries - -Both workload and supervisor images are pinned by immutable image ID. The -driver reads account files from a stopped workload-image container; it never -executes the image to resolve an account. Policy identity fields override OCI -`USER` independently. Named users/groups resolve against that image, including -supplementary groups. Root and unresolved identities fail before provisioning. -Images must not prepopulate the reserved `/.openshell` hierarchy; this prevents -image-controlled symlinks from aliasing private control state into user mounts. - -`sandbox_runtime_image` supplies the statically linked musl -`/openshell-sandbox` binary. Podman's read-only image volume delivers it to the -workload; user-namespace modes that cannot use image volumes retain the trusted -binary extraction path. `supervisor_image` supplies the dynamically linked -glibc `/openshell-supervisor` binary outside the workload. Image and request -environment belong to agent children, never the supervisor process. - -## OCI working directory - -OpenShell reads `WORKDIR` from the workload image. If it is unset, `/`, or -`/sandbox`, OpenShell uses its managed `/sandbox` workspace volume. A custom -path must be absolute and normalized, and cannot overlap `/proc`, `/sys`, -`/dev`, OpenShell-reserved paths, or the workload's private control and CA -mounts. Image volumes and driver mounts cannot cover it; mounts nested below it -remain valid. - -A custom path stays in the image's container filesystem with its ownership and -permissions. The workload starts as the final non-root user, which must be able -to reach and write the directory. Agent commands use the path as their working -directory. - -Custom workspace contents survive stop/start of the same workload container, -but are removed with that container. They do not live in a managed named volume -and are not copied to a replacement container. - -## Lifecycle and readiness - -Create builds both stopped containers and stages the private archives before -starting either container. The sandbox does not execute the agent until the -supervisor authenticates and confirms the common boundary contract. Failed -creation removes only containers created by that attempt, then cleans up -driver-owned volumes and secrets. - -Stop retains both containers, workspace, channel, and secrets. Start restores -the consumed sandbox bootstrap from a copy in the supervisor's private -filesystem, verifies the fence, and starts the same pair. A failed supervisor -start stops the workload. Delete removes the companion first, then the workload, -channel, workspace, and driver-owned secrets. User-owned volumes are retained. -Delete keeps a channel, control, or workspace volume whose -`openshell.ai/sandbox-id` label is missing or names another sandbox, and logs a -warning. - -Only workload containers appear in sandbox list/watch results. Readiness uses -the supervisor's private health socket; there is no shell, legacy marker, or -TCP-listener shortcut. Watch reconciliation and supervisor exit/removal events -stop a running workload whose companion is unavailable. The gateway also -requires the authenticated supervisor session before publishing Ready. - -## Mounts, GPUs, and configuration - -User `bind`, `volume`, `tmpfs`, and `image` mounts and CDI GPU selection remain -native Podman features and apply only to the workload. Bind mounts require the -operator's `enable_bind_mounts` opt-in and disabled label admission. Supplemental -image mounts also require disabled admission. Driver JSON requires -`allow_driver_config = true`. Reserved control paths and the workspace -root cannot be replaced. User-owned volumes are never created or deleted. - -See [gateway configuration](../../docs/how-it-works/gateways/configuration.mdx) for -operator settings and [NETWORKING.md](NETWORKING.md) for supervisor networking. -The supervisor uses Podman's host network and owns the upstream proxy settings. -Omit `health_check_interval_secs` to disable Podman's periodic health command. -Explicit zero is invalid. OpenShell still gates readiness on the supervisor's -authenticated health signal. - -Gateway OTLP configuration continues to export compute-driver spans under the -`openshell-driver-podman` service, preserving gateway trace context. -When `[openshell.gateway.otlp.agent]` is enabled, the driver sets -`OPENSHELL_OTLP_AGENT_ENDPOINT` on the supervisor container, plus -`OPENSHELL_OTLP_AGENT_PROTOCOL` for a non-gRPC collector, which starts the -agent trace relay. On Podman Machine it rewrites a loopback agent endpoint to -the desktop host, as it does for the supervisor's trace endpoint. - -## Launched mode - -```text -openshell-driver-podman serve --bind-socket --expected-peer-pid --log-level < table.toml -openshell-driver-podman preflight < table.toml -``` - -The gateway passes the `[openshell.drivers.podman]` table on stdin and gateway metadata in a `Configure` call (`proto/driver_launch.proto`). `settings_from_table` in `src/config.rs` is the only place the table is parsed and validated. - -`serve` resolves the Podman socket from `OPENSHELL_PODMAN_SOCKET`, `socket_path`, or discovery, and pings it before it binds. The ping gets 20 seconds, so the gateway, which waits 30 seconds for a driver to start, receives the report instead of killing the driver. It exits 69 when Podman is not reachable and 78 when the table is invalid. Until `Configure` succeeds, `ComputeDriver` calls return `UNAVAILABLE` and the driver creates no networks, volumes, or secrets. `preflight` validates the table without contacting Podman. - -The gateway port and name, trusted runtime images, and OTLP settings come from `Configure`. Trusted runtime images from the gateway's environment take precedence over the table, as they did when the driver ran in process. The gateway supplies `gateway_port` and the CA, so the table rejects `gateway_port`, `guest_tls_ca` and the admission keys (`allow_driver_config`, `resource_admission`), which the gateway delivers in `Configure`. `grpc_endpoint` remains an optional override, and an `https://` endpoint needs the gateway CA. diff --git a/crates/openshell-driver-podman/src/client.rs b/crates/openshell-driver-podman/src/client.rs deleted file mode 100644 index 793b92271c..0000000000 --- a/crates/openshell-driver-podman/src/client.rs +++ /dev/null @@ -1,1533 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Thin async HTTP client for the Podman REST API over a Unix socket. - -use http_body_util::{BodyExt, Full}; -use hyper::Request; -use hyper::body::Bytes; -use hyper_util::rt::TokioIo; -use serde::de::DeserializeOwned; -use serde_json::Value; -use std::collections::HashMap; -use std::path::PathBuf; -use std::pin::Pin; -use std::time::Duration; -use tokio::net::UnixStream; -use tokio::sync::mpsc; -use tracing::{debug, warn}; - -/// Podman libpod API version prefix. -const API_VERSION: &str = "v5.0.0"; - -/// Timeout for individual Podman API calls. -const API_TIMEOUT: Duration = Duration::from_mins(1); - -/// Maximum allowed size for the event stream line buffer (1 MB). -const MAX_EVENT_BUFFER: usize = 1_048_576; - -#[derive(Debug, thiserror::Error)] -pub enum PodmanApiError { - #[error("podman API not found (404): {0}")] - NotFound(String), - #[error("podman API conflict (409): {0}")] - Conflict(String), - #[error("podman API error ({status}): {message}")] - Api { status: u16, message: String }, - #[error("connection error: {0}")] - Connection(String), - #[error("timeout after {0:?}")] - Timeout(Duration), - #[error("JSON error: {0}")] - Json(String), - #[error("invalid input: {0}")] - InvalidInput(String), -} - -/// Maximum resource name length. Podman container names become directory -/// names in the storage driver, so we cap at 255 to stay within ext4/xfs -/// filename limits. -pub const MAX_NAME_LEN: usize = 255; - -/// Validate that a resource name is safe for URL path interpolation. -/// -/// Valid names start with an alphanumeric character and contain only -/// alphanumerics, dots, underscores, and hyphens — matching Podman's -/// own naming rules. Names longer than [`MAX_NAME_LEN`] are rejected. -pub fn validate_name(name: &str) -> Result<(), PodmanApiError> { - // Regex-equivalent: ^[a-zA-Z0-9][a-zA-Z0-9._-]*$ - if name.is_empty() { - return Err(PodmanApiError::InvalidInput( - "name must not be empty".to_string(), - )); - } - if name.len() > MAX_NAME_LEN { - return Err(PodmanApiError::InvalidInput(format!( - "name exceeds maximum length of {MAX_NAME_LEN} characters (got {})", - name.len() - ))); - } - let bytes = name.as_bytes(); - if !bytes[0].is_ascii_alphanumeric() { - return Err(PodmanApiError::InvalidInput(format!( - "name must start with an alphanumeric character: {name:?}" - ))); - } - if !bytes - .iter() - .all(|&b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-') - { - return Err(PodmanApiError::InvalidInput(format!( - "name contains invalid characters: {name:?}" - ))); - } - Ok(()) -} - -/// A container state snapshot returned by inspect APIs. -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct ContainerInspect { - #[serde(default)] - pub mounts: Option>, - pub id: String, - pub name: String, - pub state: ContainerState, - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub network_settings: NetworkSettings, - #[serde(default)] - pub config: ContainerConfig, -} - -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct ContainerState { - pub status: String, - #[allow(dead_code)] // kept for podman API compat - pub running: bool, - #[serde(default)] - pub exit_code: i64, - #[serde(rename = "OOMKilled")] - #[serde(default)] - pub oom_killed: bool, - #[serde(default)] - pub health: Option, - #[serde(default)] - pub started_at: Option, - #[serde(default)] - pub finished_at: Option, - /// A driver-local diagnostic derived from a narrowly allow-listed - /// container-log marker. It is never deserialized from Podman. - #[serde(skip)] - pub startup_diagnostic: Option, - /// Exit status of the sandbox's supervisor companion when it stopped - /// before the workload. It is never deserialized from Podman. - #[serde(skip)] - pub supervisor_exit_code: Option, -} - -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct HealthState { - pub status: String, -} - -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct NetworkSettings { - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub networks: HashMap, - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub ports: HashMap>>, -} - -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct NetworkInfo { - #[serde(rename = "IPAddress")] - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub ip_address: String, -} - -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct PortBinding { - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub host_port: String, - #[serde(rename = "HostIp")] - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub host_ip: String, -} - -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct ContainerConfig { - #[serde(default)] - pub labels: HashMap, - #[serde(default)] - pub user: String, - /// The immutable image ID the container was created from. Podman records - /// the reference used at creation time here; workloads are always created - /// from a resolved image ID, so this pins the image the container runs - /// independently of any later tag movement. - #[serde(default)] - pub image: String, -} - -/// Immutable image metadata needed to bind OCI identity inspection to launch. -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct ImageInspect { - #[serde(alias = "ID")] - pub id: String, - #[serde(default)] - pub config: Option, -} - -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(default, rename_all = "PascalCase")] -pub struct ImageConfig { - pub user: String, - pub env: Vec, - pub working_dir: String, - pub volumes: Option>, -} - -/// A container summary returned by the list API. -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct ContainerListEntry { - pub id: String, - #[serde(default)] - pub names: Vec, - pub state: String, - #[serde(default)] - pub labels: HashMap, - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub ports: Option>, - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub networks: Option>, - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub exit_code: i64, -} - -#[derive(Debug, Clone, serde::Deserialize)] -pub struct PortMappingEntry { - #[allow(dead_code)] // kept for podman API compat - pub host_port: u16, - #[allow(dead_code)] // kept for podman API compat - pub container_port: u16, - #[allow(dead_code)] // kept for podman API compat - pub protocol: String, - #[serde(default)] - #[allow(dead_code)] // kept for podman API compat - pub host_ip: String, -} - -/// A named Podman volume returned by the libpod inspect API. -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct VolumeInspect { - #[serde(default)] - pub created_at: Option, - #[serde(default)] - pub labels: Option>, - #[serde(default)] - pub name: String, - #[serde(default)] - pub driver: String, - #[serde(default)] - pub options: HashMap, -} - -impl VolumeInspect { - /// Whether metadata matches a managed local volume with the exact labels - /// and requested ownership options. This does not inspect filesystem ownership. - pub(crate) fn matches_managed_volume( - &self, - labels: &HashMap, - requested_owner: Option<(u32, u32)>, - ) -> bool { - self.driver == "local" - && self.labels.as_ref() == Some(labels) - && self.options_match_requested_owner(requested_owner) - } - - /// Whether option metadata matches the requested owner. `None` means no - /// ownership options were requested and requires an empty options map. - /// This does not inspect filesystem ownership. Podman records the parsed - /// `UID` and `GID` next to the raw `o` option. - pub(crate) fn options_match_requested_owner( - &self, - requested_owner: Option<(u32, u32)>, - ) -> bool { - let Some((uid, gid)) = requested_owner else { - return self.options.is_empty(); - }; - self.options.get("o").map(String::as_str) == Some(format!("uid={uid},gid={gid}").as_str()) - && self.options.iter().all(|(key, value)| match key.as_str() { - "o" => true, - "UID" => *value == uid.to_string(), - "GID" => *value == gid.to_string(), - _ => false, - }) - } - - pub(crate) fn admission_identity(&self) -> Value { - serde_json::json!({"name": self.name, "driver": self.driver, "options": self.options, "created_at": self.created_at}) - } -} - -/// A Podman event from the events stream. -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct PodmanEvent { - #[serde(rename = "Type")] - #[allow(dead_code)] // kept for podman API compat - pub event_type: String, - pub action: String, - #[serde(default)] - pub actor: EventActor, - #[serde(rename = "timeNano", default)] - #[allow(dead_code)] // kept for podman API compat - pub time_nano: i64, -} - -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(rename_all = "PascalCase")] -pub struct EventActor { - #[serde(rename = "ID")] - #[serde(default)] - pub id: String, - #[serde(default)] - pub attributes: HashMap, -} - -/// System info response (subset of fields we care about). -#[derive(Debug, Clone, serde::Deserialize)] -pub struct SystemInfo { - pub host: HostInfo, -} - -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct HostInfo { - #[serde(default)] - pub cgroup_version: String, - #[serde(default)] - pub network_backend: String, - #[serde(default)] - pub rootless_network_cmd: String, - #[serde(default)] - pub security: SecurityInfo, -} - -/// Security-related fields from the Podman system info response. -/// -/// Podman returns `host.security.rootless: true` when the daemon is -/// running without root privileges (rootless mode). -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SecurityInfo { - #[serde(default)] - pub rootless: bool, - /// Whether the Podman host has `AppArmor` support enabled. - #[serde(default)] - pub apparmor_enabled: bool, -} - -// ── Client ─────────────────────────────────────────────────────────────── - -/// Async Podman REST API client communicating over a Unix socket. -#[derive(Debug, Clone)] -pub struct PodmanClient { - socket_path: PathBuf, -} - -impl PodmanClient { - /// Create a new client targeting the given socket path. - #[must_use] - pub fn new(socket_path: PathBuf) -> Self { - Self { socket_path } - } - - /// Open a new HTTP/1.1 connection to the Podman socket. - async fn connect( - &self, - ) -> Result>, PodmanApiError> { - let stream = UnixStream::connect(&self.socket_path).await.map_err(|e| { - PodmanApiError::Connection(format!("{}: {e}", self.socket_path.display())) - })?; - - let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) - .await - .map_err(|e| PodmanApiError::Connection(e.to_string()))?; - - tokio::spawn(async move { - if let Err(e) = conn.await { - debug!(error = %e, "Podman API connection closed"); - } - }); - - Ok(sender) - } - - // ── Request infrastructure ─────────────────────────────────────────── - - /// Build an HTTP request from components. - fn build_request( - method: hyper::Method, - path: &str, - body: Full, - content_type: Option<&str>, - ) -> Request> { - let mut builder = Request::builder() - .method(method) - .uri(format!("http://localhost{path}")) - .header("Host", "localhost"); - if let Some(ct) = content_type { - builder = builder.header("Content-Type", ct); - } - builder.body(body).expect("valid request") - } - - /// Send a pre-built HTTP request and return status + body bytes. - async fn send_request( - &self, - req: Request>, - timeout: Duration, - ) -> Result<(hyper::StatusCode, Bytes), PodmanApiError> { - let mut sender = self.connect().await?; - let response = tokio::time::timeout(timeout, sender.send_request(req)) - .await - .map_err(|_| PodmanApiError::Timeout(timeout))? - .map_err(|e| PodmanApiError::Connection(e.to_string()))?; - let status = response.status(); - let bytes = tokio::time::timeout(timeout, response.into_body().collect()) - .await - .map_err(|_| PodmanApiError::Timeout(timeout))? - .map_err(|e| PodmanApiError::Connection(e.to_string()))? - .to_bytes(); - Ok((status, bytes)) - } - - /// Perform a versioned HTTP request and return status + body bytes. - async fn request( - &self, - method: hyper::Method, - path: &str, - body: Option<&Value>, - timeout: Duration, - ) -> Result<(hyper::StatusCode, Bytes), PodmanApiError> { - let (full_body, content_type) = match body { - Some(json) => { - let payload = - serde_json::to_vec(json).map_err(|e| PodmanApiError::Json(e.to_string()))?; - (Full::new(Bytes::from(payload)), Some("application/json")) - } - None => (Full::new(Bytes::new()), None), - }; - let req = Self::build_request( - method, - &format!("/{API_VERSION}{path}"), - full_body, - content_type, - ); - self.send_request(req, timeout).await - } - - /// Perform a request and deserialize the JSON response. - async fn request_json( - &self, - method: hyper::Method, - path: &str, - body: Option<&Value>, - ) -> Result { - let (status, bytes) = self.request(method, path, body, API_TIMEOUT).await?; - if status.is_success() { - serde_json::from_slice(&bytes).map_err(|e| { - PodmanApiError::Json(format!("{e}: {}", String::from_utf8_lossy(&bytes))) - }) - } else { - Err(error_from_response(status.as_u16(), &bytes)) - } - } - - /// Perform a request that returns no meaningful body. - async fn request_ok( - &self, - method: hyper::Method, - path: &str, - body: Option<&Value>, - ) -> Result<(), PodmanApiError> { - let (status, bytes) = self.request(method, path, body, API_TIMEOUT).await?; - let code = status.as_u16(); - if status.is_success() || code == 304 { - Ok(()) - } else { - Err(error_from_response(code, &bytes)) - } - } - - /// Perform a versioned HTTP request with a raw byte body (not JSON). - async fn request_raw( - &self, - method: hyper::Method, - path: &str, - content_type: &str, - body: Bytes, - ) -> Result<(hyper::StatusCode, Bytes), PodmanApiError> { - let req = Self::build_request( - method, - &format!("/{API_VERSION}{path}"), - Full::new(body), - Some(content_type), - ); - self.send_request(req, API_TIMEOUT).await - } - - /// POST a JSON body and ignore 409 Conflict (resource already exists). - async fn create_ignore_conflict(&self, path: &str, body: &Value) -> Result<(), PodmanApiError> { - match self - .request_json::(hyper::Method::POST, path, Some(body)) - .await - { - Ok(_) | Err(PodmanApiError::Conflict(_)) => Ok(()), - Err(e) => Err(e), - } - } - - // ── Container operations ───────────────────────────────────────────── - - /// Create a container from a JSON spec. - pub async fn create_container(&self, spec: &Value) -> Result { - self.request_json(hyper::Method::POST, "/libpod/containers/create", Some(spec)) - .await - } - - pub(crate) async fn create_typed_container( - &self, - spec: &(impl serde::Serialize + Sync), - ) -> Result { - #[derive(serde::Deserialize)] - struct Created { - #[serde(rename = "Id", alias = "ID")] - id: String, - } - let body = - serde_json::to_vec(spec).map_err(|error| PodmanApiError::Json(error.to_string()))?; - let (status, bytes) = self - .request_raw( - hyper::Method::POST, - "/libpod/containers/create", - "application/json", - body.into(), - ) - .await?; - if !status.is_success() { - return Err(error_from_response(status.as_u16(), &bytes)); - } - let created: Created = serde_json::from_slice(&bytes) - .map_err(|error| PodmanApiError::Json(error.to_string()))?; - validate_name(&created.id)?; - Ok(created.id) - } - - pub(crate) async fn copy_to_container( - &self, - name: &str, - destination: &str, - archive: Vec, - ) -> Result<(), PodmanApiError> { - validate_name(name)?; - let (status, bytes) = self - .request_raw( - hyper::Method::PUT, - &format!( - "/libpod/containers/{name}/archive?path={}", - url_encode(destination) - ), - "application/x-tar", - archive.into(), - ) - .await?; - if status.is_success() { - Ok(()) - } else { - Err(error_from_response(status.as_u16(), &bytes)) - } - } - - pub(crate) async fn verify_isolation_fence(&self, id: &str) -> Result<(), PodmanApiError> { - #[derive(serde::Deserialize)] - #[serde(rename_all = "PascalCase")] - struct HostConfig { - network_mode: String, - privileged: bool, - } - #[derive(serde::Deserialize)] - #[serde(rename_all = "PascalCase")] - struct FenceInspect { - host_config: HostConfig, - network_settings: NetworkSettings, - } - validate_name(id)?; - let inspected: FenceInspect = self - .request_json( - hyper::Method::GET, - &format!("/libpod/containers/{id}/json"), - None, - ) - .await?; - if inspected.host_config.network_mode != "none" - || inspected.host_config.privileged - || inspected - .network_settings - .networks - .keys() - .any(|name| name != "none") - { - return Err(PodmanApiError::InvalidInput("sandbox requires an unprivileged container with network mode none and no attached networks".into())); - } - Ok(()) - } - - /// Start a container by name or ID. - pub async fn start_container(&self, name: &str) -> Result<(), PodmanApiError> { - validate_name(name)?; - self.request_ok( - hyper::Method::POST, - &format!("/libpod/containers/{name}/start"), - None, - ) - .await - } - - /// Stop a container with a grace period in seconds. - pub async fn stop_container( - &self, - name: &str, - timeout_secs: u32, - ) -> Result<(), PodmanApiError> { - validate_name(name)?; - let http_timeout = Duration::from_secs(u64::from(timeout_secs) + 5); - let (status, bytes) = self - .request( - hyper::Method::POST, - &format!("/libpod/containers/{name}/stop?timeout={timeout_secs}"), - None, - http_timeout, - ) - .await?; - let code = status.as_u16(); - if status.is_success() || code == 304 { - Ok(()) - } else { - Err(error_from_response(code, &bytes)) - } - } - - /// Remove a container in one timed, forced Libpod delete operation. - /// - /// The Libpod endpoint uses `volumes` for anonymous-volume removal. Its - /// Docker-compatible counterpart uses the shorter `v` parameter. - pub async fn remove_container( - &self, - name: &str, - timeout_secs: u32, - ) -> Result<(), PodmanApiError> { - validate_name(name)?; - // The delete request covers both the graceful stop and the subsequent - // storage, network, and anonymous-volume cleanup. Preserve the normal - // API timeout as cleanup headroom after the stop grace period. - let http_timeout = Duration::from_secs(u64::from(timeout_secs)) + API_TIMEOUT; - let (status, bytes) = self - .request( - hyper::Method::DELETE, - &format!( - "/libpod/containers/{name}?force=true&volumes=true&timeout={timeout_secs}" - ), - None, - http_timeout, - ) - .await?; - let code = status.as_u16(); - if status.is_success() || code == 304 { - Ok(()) - } else { - Err(error_from_response(code, &bytes)) - } - } - - /// Rename a stopped container by name or ID. - /// - /// The libpod rename endpoint frees the old canonical name without - /// deleting the container. Reconciliation uses it as a rollback point - /// while a replacement is created. - pub async fn rename_container(&self, name: &str, new_name: &str) -> Result<(), PodmanApiError> { - validate_name(name)?; - validate_name(new_name)?; - self.request_ok( - hyper::Method::POST, - &format!("/libpod/containers/{name}/rename?name={new_name}"), - None, - ) - .await - } - - /// Remove a stopped container without asking Podman to remove volumes. - /// - /// This is deliberately separate from [`Self::remove_container`]: stopped - /// sandbox trust reconciliation replaces only the container and must never - /// remove its pre-existing named workspace volume. - pub async fn remove_container_preserving_volumes( - &self, - name: &str, - ) -> Result<(), PodmanApiError> { - validate_name(name)?; - self.request_ok( - hyper::Method::DELETE, - &format!("/libpod/containers/{name}?force=true&volumes=false&timeout=0"), - None, - ) - .await - } - - /// Download a file from a container as a tar archive. - /// - /// Calls `GET /libpod/containers/{name}/archive?path={path}` and returns - /// the raw tar bytes. The container does not need to be running. - pub async fn copy_from_container( - &self, - name: &str, - path: &str, - ) -> Result { - validate_name(name)?; - let encoded_path = url_encode(path); - let (status, bytes) = self - .request( - hyper::Method::GET, - &format!("/libpod/containers/{name}/archive?path={encoded_path}"), - None, - API_TIMEOUT, - ) - .await?; - if status.is_success() { - Ok(bytes) - } else { - Err(error_from_response(status.as_u16(), &bytes)) - } - } - - /// Inspect a container by name or ID. - pub async fn inspect_container(&self, name: &str) -> Result { - validate_name(name)?; - self.request_json( - hyper::Method::GET, - &format!("/libpod/containers/{name}/json"), - None, - ) - .await - } - - /// Read a bounded tail of a container's combined output. - /// - /// Callers must treat this as sensitive workload output. The Podman - /// watcher uses it only to recognize fixed, driver-owned startup markers; - /// it never forwards the raw output to the gateway. - pub async fn container_logs(&self, name: &str) -> Result { - validate_name(name)?; - let (status, bytes) = self - .request( - hyper::Method::GET, - &format!("/libpod/containers/{name}/logs?stdout=true&stderr=true&tail=200"), - None, - API_TIMEOUT, - ) - .await?; - if status.is_success() { - Ok(bytes) - } else { - Err(error_from_response(status.as_u16(), &bytes)) - } - } - - /// List containers matching label filters (e.g. `&["openshell.managed=true"]`). - pub async fn list_containers( - &self, - label_filters: &[&str], - ) -> Result, PodmanApiError> { - let filters = serde_json::json!({"label": label_filters}); - let encoded = url_encode(&filters.to_string()); - self.request_json( - hyper::Method::GET, - &format!("/libpod/containers/json?all=true&filters={encoded}"), - None, - ) - .await - } - - // ── Volume operations ──────────────────────────────────────────────── - - /// Create and inspect a local volume. HTTP 409 conflicts also proceed to - /// inspection; callers must verify the returned labels and options. - async fn create_volume( - &self, - name: &str, - labels: &HashMap, - options: &HashMap, - ) -> Result { - validate_name(name)?; - let mut body = serde_json::json!({ - "Name": name, - "Driver": "local", - "Labels": labels, - }); - if !options.is_empty() { - body["Options"] = serde_json::json!(options); - } - self.create_ignore_conflict("/libpod/volumes/create", &body) - .await?; - self.inspect_volume(name).await - } - - /// Never adopt an unrelated existing volume on a private provisioning path. - /// - /// With `owner`, Podman creates the volume root owned by that UID and GID, - /// so a non-root workload can use it without a privileged chown. - pub(crate) async fn create_owned_volume( - &self, - name: &str, - sandbox_id: &str, - workspace: &str, - owner: Option<(u32, u32)>, - ) -> Result<(), PodmanApiError> { - let labels = HashMap::from([ - ( - openshell_core::driver_utils::LABEL_SANDBOX_ID.to_string(), - sandbox_id.to_string(), - ), - ( - openshell_core::driver_utils::LABEL_SANDBOX_WORKSPACE.to_string(), - workspace.to_string(), - ), - ]); - match self.inspect_volume(name).await { - Ok(existing) => { - if !existing.matches_managed_volume(&labels, owner) { - return Err(PodmanApiError::InvalidInput( - "private volume name collides with an unrelated resource".into(), - )); - } - return Ok(()); - } - Err(PodmanApiError::NotFound(_)) => {} - Err(error) => return Err(error), - } - let options = owner.map_or_else(HashMap::new, |(uid, gid)| { - HashMap::from([("o".to_string(), format!("uid={uid},gid={gid}"))]) - }); - let created = self.create_volume(name, &labels, &options).await?; - if !created.matches_managed_volume(&labels, owner) { - return Err(PodmanApiError::InvalidInput( - "private volume ownership verification failed".into(), - )); - } - Ok(()) - } - - /// Remove a managed volume only when its sandbox ID label names - /// `sandbox_id`. A missing volume is a no-op; any other volume is kept - /// with a warning. - pub(crate) async fn remove_owned_volume( - &self, - name: &str, - sandbox_id: &str, - ) -> Result<(), PodmanApiError> { - let labels = match self.inspect_volume(name).await { - Ok(volume) => volume.labels.unwrap_or_default(), - Err(PodmanApiError::NotFound(_)) => return Ok(()), - Err(error) => return Err(error), - }; - let reason = match labels.get(openshell_core::driver_utils::LABEL_SANDBOX_ID) { - Some(owner) if owner == sandbox_id => return self.remove_volume(name).await, - Some(_) => "sandbox ID label names another sandbox", - None => "sandbox ID label is missing", - }; - warn!(%sandbox_id, volume = %name, %reason, "Kept volume not owned by sandbox"); - Ok(()) - } - - /// Remove a named volume. Idempotent (not-found is ignored). - pub async fn remove_volume(&self, name: &str) -> Result<(), PodmanApiError> { - validate_name(name)?; - match self - .request_ok( - hyper::Method::DELETE, - &format!("/libpod/volumes/{name}"), - None, - ) - .await - { - Ok(()) | Err(PodmanApiError::NotFound(_)) => Ok(()), - Err(e) => Err(e), - } - } - - /// Inspect a named volume. Does not create the volume. - pub async fn inspect_volume(&self, name: &str) -> Result { - validate_name(name)?; - self.request_json( - hyper::Method::GET, - &format!("/libpod/volumes/{name}/json"), - None, - ) - .await - } - - // ── Secret operations ──────────────────────────────────────────────── - - /// Create a Podman secret with the given name and raw value. - /// - /// Idempotent: if a secret with the same name already exists it is - /// replaced (delete + recreate) so the value is always up-to-date. - pub async fn create_secret(&self, name: &str, value: &[u8]) -> Result<(), PodmanApiError> { - validate_name(name)?; - let encoded_name = url_encode(name); - let path = format!("/libpod/secrets/create?name={encoded_name}"); - let (status, bytes) = self - .request_raw( - hyper::Method::POST, - &path, - "application/octet-stream", - Bytes::copy_from_slice(value), - ) - .await?; - - match status.as_u16() { - 200 | 201 => Ok(()), - 409 => { - self.remove_secret(name).await?; - let (status2, bytes2) = self - .request_raw( - hyper::Method::POST, - &path, - "application/octet-stream", - Bytes::copy_from_slice(value), - ) - .await?; - if status2.is_success() { - Ok(()) - } else { - Err(error_from_response(status2.as_u16(), &bytes2)) - } - } - _ => Err(error_from_response(status.as_u16(), &bytes)), - } - } - - /// Check whether a named Podman secret exists without reading its value. - /// - /// A 404 is an expected compatibility signal for legacy tokenless - /// sandboxes, so return it as `Ok(false)` without parsing or exposing the - /// response body. All other API failures remain errors. - pub async fn secret_exists(&self, name: &str) -> Result { - validate_name(name)?; - let (status, bytes) = self - .request( - hyper::Method::GET, - &format!("/libpod/secrets/{name}/json"), - None, - API_TIMEOUT, - ) - .await?; - if status.is_success() { - Ok(true) - } else if status == hyper::StatusCode::NOT_FOUND { - Ok(false) - } else { - Err(error_from_response(status.as_u16(), &bytes)) - } - } - - /// Remove a Podman secret by name. Idempotent (not-found is ignored). - pub async fn remove_secret(&self, name: &str) -> Result<(), PodmanApiError> { - validate_name(name)?; - match self - .request_ok( - hyper::Method::DELETE, - &format!("/libpod/secrets/{name}"), - None, - ) - .await - { - Ok(()) | Err(PodmanApiError::NotFound(_)) => Ok(()), - Err(e) => Err(e), - } - } - - // ── Network operations ─────────────────────────────────────────────── - - /// Create a bridge network with DNS enabled. Idempotent. - pub async fn ensure_network(&self, name: &str) -> Result<(), PodmanApiError> { - validate_name(name)?; - self.create_ignore_conflict( - "/libpod/networks/create", - &serde_json::json!({ - "name": name, - "driver": "bridge", - "dns_enabled": true, - }), - ) - .await - } - - // ── Image operations ──────────────────────────────────────────────── - - /// Pull an image if it is not already present locally. - /// - /// Uses the `policy` parameter to decide whether to pull: - /// - `"always"` — always pull, even if a local copy exists - /// - `"missing"` — pull only when no local copy exists (default) - /// - `"never"` — never pull, fail if not local - /// - `"newer"` — pull only if the remote image is newer - /// - /// The pull `policy` is passed directly to Podman's API so that - /// Podman handles local-image resolution and registry fallback - /// natively. This avoids name-resolution mismatches between the - /// exists API and the local image store (e.g. `openshell/supervisor:dev` - /// vs `localhost/openshell/supervisor:dev`). - /// - /// The Podman pull endpoint streams NDJSON progress. We consume the - /// entire stream and check for an `error` field in the final object. - pub async fn pull_image(&self, reference: &str, policy: &str) -> Result<(), PodmanApiError> { - let path = format!( - "/libpod/images/pull?reference={}&policy={}", - url_encode(reference), - url_encode(policy), - ); - // Image pulls can be slow — use a generous timeout. - let pull_timeout = Duration::from_mins(10); - let (status, bytes) = self - .request(hyper::Method::POST, &path, None, pull_timeout) - .await?; - if !status.is_success() { - return Err(error_from_response(status.as_u16(), &bytes)); - } - // The response is NDJSON. Check the last line for an error field. - let body = String::from_utf8_lossy(&bytes); - if let Some(last_line) = body.lines().rfind(|l| !l.is_empty()) - && let Ok(obj) = serde_json::from_str::(last_line) - && let Some(err) = obj.get("error").and_then(|v| v.as_str()) - && !err.is_empty() - { - return Err(PodmanApiError::Api { - status: 500, - message: format!("image pull failed: {err}"), - }); - } - Ok(()) - } - - /// Inspect a locally selected image for immutable ID and OCI config. - pub async fn inspect_image(&self, reference: &str) -> Result { - self.request_json( - hyper::Method::GET, - &format!("/libpod/images/{}/json", url_encode(reference)), - None, - ) - .await - } - - // ── System operations ──────────────────────────────────────────────── - - /// Ping the Podman API to verify connectivity. - pub async fn ping(&self) -> Result<(), PodmanApiError> { - // _ping is outside the versioned API path. - let req = Self::build_request(hyper::Method::GET, "/_ping", Full::new(Bytes::new()), None); - let (status, _) = self.send_request(req, API_TIMEOUT).await?; - if status.is_success() { - Ok(()) - } else { - Err(PodmanApiError::Api { - status: status.as_u16(), - message: "ping failed".to_string(), - }) - } - } - - /// Get system info. - pub async fn system_info(&self) -> Result { - self.request_json(hyper::Method::GET, "/libpod/info", None) - .await - } - - // ── Event streaming ────────────────────────────────────────────────── - - /// Start streaming container events filtered by label. - /// - /// Events are sent to the returned receiver. The background task runs - /// until the receiver is dropped. - pub async fn events_stream( - &self, - label_filter: &str, - ) -> Result>, PodmanApiError> { - let filters = serde_json::json!({ - "label": [label_filter], - "type": ["container"], - }); - let encoded = url_encode(&filters.to_string()); - let path = - format!("http://localhost/{API_VERSION}/libpod/events?stream=true&filters={encoded}"); - - let mut sender = self.connect().await?; - - let req = Request::builder() - .method(hyper::Method::GET) - .uri(&path) - .header("Host", "localhost") - .body(Full::new(Bytes::new())) - .map_err(|e| PodmanApiError::Connection(e.to_string()))?; - - let response = tokio::time::timeout(API_TIMEOUT, sender.send_request(req)) - .await - .map_err(|_| PodmanApiError::Timeout(API_TIMEOUT))? - .map_err(|e| PodmanApiError::Connection(e.to_string()))?; - - if !response.status().is_success() { - return Err(PodmanApiError::Api { - status: response.status().as_u16(), - message: "events stream request failed".to_string(), - }); - } - - let (tx, rx) = mpsc::channel(256); - let body = response.into_body(); - - tokio::spawn(async move { - let mut buffer = Vec::new(); - let mut body = body; - - loop { - use hyper::body::Body; - - let frame = - match std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await { - Some(Ok(frame)) => frame, - Some(Err(e)) => { - let _ = tx - .send(Err(PodmanApiError::Connection(e.to_string()))) - .await; - break; - } - None => break, - }; - - if let Some(data) = frame.data_ref() { - buffer.extend_from_slice(data); - } - - if buffer.len() > MAX_EVENT_BUFFER { - tracing::error!("event stream buffer exceeded maximum size, disconnecting"); - let _ = tx - .send(Err(PodmanApiError::Connection( - "event buffer exceeded 1 MB limit".to_string(), - ))) - .await; - break; - } - - // Parse complete newline-delimited JSON lines. - while let Some(pos) = buffer.iter().position(|&b| b == b'\n') { - let line: Vec = buffer.drain(..=pos).collect(); - let trimmed = line.strip_suffix(b"\n").unwrap_or(&line); - if trimmed.is_empty() { - continue; - } - let event = serde_json::from_slice::(trimmed).map_err(|e| { - PodmanApiError::Json(format!("{e}: {}", String::from_utf8_lossy(trimmed))) - }); - if tx.send(event).await.is_err() { - return; - } - } - } - }); - - Ok(rx) - } -} - -// ── Helpers ────────────────────────────────────────────────────────────── - -fn error_from_response(status: u16, bytes: &Bytes) -> PodmanApiError { - let message = serde_json::from_slice::(bytes) - .ok() - .and_then(|v| { - v.get("message") - .or_else(|| v.get("cause")) - .and_then(Value::as_str) - .map(String::from) - }) - .unwrap_or_else(|| String::from_utf8_lossy(bytes).to_string()); - - match status { - 404 => PodmanApiError::NotFound(message), - 409 => PodmanApiError::Conflict(message), - _ => PodmanApiError::Api { status, message }, - } -} - -/// Minimal percent-encoding for query parameter values. -/// -/// Note: `percent-encoding` is available as a transitive dependency but is not -/// a direct dependency of this crate. Rather than adding a new dep for one -/// call site, we keep this self-contained implementation. -fn url_encode(s: &str) -> String { - s.bytes() - .map(|b| match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { - String::from(b as char) - } - _ => format!("%{b:02X}"), - }) - .collect() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::test_utils::{StubResponse, spawn_podman_stub}; - use hyper::StatusCode; - - #[test] - fn url_encode_encodes_special_characters() { - assert_eq!(url_encode("hello world"), "hello%20world"); - assert_eq!(url_encode("a=b&c=d"), "a%3Db%26c%3Dd"); - assert_eq!(url_encode("safe-_.~chars"), "safe-_.~chars"); - } - - #[test] - fn validate_name_accepts_valid_names() { - // alphanumeric, dots, hyphens, underscores - assert!(validate_name("my-container").is_ok()); - assert!(validate_name("my_container.v2").is_ok()); - assert!(validate_name("a").is_ok()); - assert!(validate_name("Container123").is_ok()); - } - - #[test] - fn validate_name_rejects_invalid_names() { - assert!(validate_name("").is_err()); // empty - assert!(validate_name("-leading").is_err()); // starts with dash - assert!(validate_name(".leading").is_err()); // starts with dot - assert!(validate_name("has/slash").is_err()); // path traversal - assert!(validate_name("../etc").is_err()); // path traversal - assert!(validate_name("has space").is_err()); // space - assert!(validate_name("has%20encoded").is_err()); // percent - assert!(validate_name("has?query").is_err()); // query char - } - - #[test] - fn validate_name_rejects_names_exceeding_max_length() { - let long_name = format!("a{}", "b".repeat(MAX_NAME_LEN)); - assert!(long_name.len() > MAX_NAME_LEN); - assert!(validate_name(&long_name).is_err()); - - // Exactly at the limit should be accepted. - let exact_name = "a".repeat(MAX_NAME_LEN); - assert!(validate_name(&exact_name).is_ok()); - } - - #[test] - fn system_info_parses_rootless_network_helper() { - let info: SystemInfo = serde_json::from_str( - r#"{ - "host": { - "cgroupVersion": "v2", - "networkBackend": "netavark", - "rootlessNetworkCmd": "pasta", - "security": { - "rootless": true, - "apparmorEnabled": true - } - } - }"#, - ) - .unwrap(); - - assert!(info.host.security.rootless); - assert!(info.host.security.apparmor_enabled); - assert_eq!(info.host.rootless_network_cmd, "pasta"); - } - - #[tokio::test] - async fn inspect_volume_parses_driver_options() { - let (socket_path, request_log, handle) = spawn_podman_stub( - "inspect-volume", - vec![StubResponse::new( - StatusCode::OK, - r#"{"Name":"work-bind","Driver":"local","Options":{"type":"none","o":"rw,bind","device":"/srv/work"}}"#, - )], - ); - let client = PodmanClient::new(socket_path.clone()); - - let volume = client - .inspect_volume("work-bind") - .await - .expect("volume inspect should parse"); - - assert_eq!(volume.driver, "local"); - assert_eq!(volume.options.get("o").map(String::as_str), Some("rw,bind")); - handle.await.expect("stub task should finish"); - assert_eq!( - request_log - .lock() - .expect("request log lock should not be poisoned") - .as_slice(), - ["GET /v5.0.0/libpod/volumes/work-bind/json"] - ); - let _ = std::fs::remove_file(socket_path); - } - - #[tokio::test] - async fn create_owned_volume_verifies_requested_options() { - let labels = - r#"{"openshell.ai/sandbox-id":"sandbox-1","openshell.ai/sandbox-workspace":"team-a"}"#; - for (owner, options, accepted) in [ - ( - Some((1234, 1235)), - r#"{"o":"uid=1234,gid=1235","UID":"1234","GID":"1235"}"#, - true, - ), - (Some((1234, 1235)), r#"{"o":"uid=1234,gid=1235"}"#, true), - // Podman accepts either order, but OpenShell always requests uid first. - (Some((1234, 1235)), r#"{"o":"gid=1235,uid=1234"}"#, false), - ( - Some((1234, 1235)), - r#"{"o":"uid=1234,gid=1235","UID":"0","GID":"1235"}"#, - false, - ), - ( - Some((1234, 1235)), - r#"{"o":"uid=1234,gid=1235","device":"/srv/work"}"#, - false, - ), - (Some((1234, 1235)), "{}", false), - (None, "{}", true), - (None, r#"{"o":"uid=1234,gid=1235"}"#, false), - (None, r#"{"o":"bind","device":"/srv/work"}"#, false), - ] { - for existing in [false, true] { - let inspected = || { - StubResponse::new( - StatusCode::OK, - format!( - r#"{{"Name":"work","Driver":"local","Options":{options},"Labels":{labels}}}"# - ), - ) - }; - let responses = if existing { - vec![inspected()] - } else { - vec![ - StubResponse::new(StatusCode::NOT_FOUND, ""), - StubResponse::new(StatusCode::CREATED, "{}"), - inspected(), - ] - }; - let (socket_path, request_log, handle) = - spawn_podman_stub("owned-volume", responses); - let result = PodmanClient::new(socket_path.clone()) - .create_owned_volume("work", "sandbox-1", "team-a", owner) - .await; - assert_eq!( - result.is_ok(), - accepted, - "owner {owner:?}, options {options}, existing {existing}: {result:?}" - ); - handle.await.expect("stub task should finish"); - let expected_requests = if existing { - vec!["GET /v5.0.0/libpod/volumes/work/json"] - } else { - vec![ - "GET /v5.0.0/libpod/volumes/work/json", - "POST /v5.0.0/libpod/volumes/create", - "GET /v5.0.0/libpod/volumes/work/json", - ] - }; - assert_eq!( - request_log.lock().expect("request log lock").as_slice(), - expected_requests, - ); - let _ = std::fs::remove_file(socket_path); - } - } - } - - #[test] - fn image_config_defaults_missing_oci_fields() { - let empty: ImageConfig = serde_json::from_str("{}").unwrap(); - assert!(empty.user.is_empty()); - assert!(empty.env.is_empty()); - assert!(empty.working_dir.is_empty()); - assert!(empty.volumes.is_none()); - - let partial: ImageConfig = serde_json::from_str(r#"{"User":"app:staff"}"#).unwrap(); - assert_eq!(partial.user, "app:staff"); - assert!(partial.env.is_empty()); - assert!(partial.working_dir.is_empty()); - assert!(partial.volumes.is_none()); - } - - #[tokio::test] - async fn inspect_image_reads_immutable_id_and_oci_config() { - let (socket_path, request_log, handle) = spawn_podman_stub( - "inspect-image", - vec![StubResponse::new( - StatusCode::OK, - r#"{"Id":"sha256:immutable","Config":{"User":"app:staff","Env":["A=one"],"WorkingDir":"/workspace/project","Volumes":{"/workspace/project/cache":{}}}}"#, - )], - ); - let client = PodmanClient::new(socket_path.clone()); - - let image = client - .inspect_image("example/image:latest") - .await - .expect("image inspect should parse"); - - assert_eq!(image.id, "sha256:immutable"); - let config = image.config.expect("fixture image config"); - assert_eq!(config.user, "app:staff"); - assert_eq!(config.env, vec!["A=one"]); - assert_eq!(config.working_dir, "/workspace/project"); - assert!( - config - .volumes - .as_ref() - .is_some_and(|volumes| volumes.contains_key("/workspace/project/cache")) - ); - handle.await.expect("stub task should finish"); - assert_eq!( - request_log - .lock() - .expect("request log lock should not be poisoned") - .as_slice(), - ["GET /v5.0.0/libpod/images/example%2Fimage%3Alatest/json"] - ); - let _ = std::fs::remove_file(socket_path); - } - - #[tokio::test] - async fn secret_exists_treats_not_found_as_absent_without_exposing_body() { - let (socket_path, request_log, handle) = spawn_podman_stub( - "secret-not-found", - vec![StubResponse::new( - StatusCode::NOT_FOUND, - "sensitive daemon diagnostic", - )], - ); - let client = PodmanClient::new(socket_path.clone()); - - assert!( - !client - .secret_exists("openshell-token-sandbox-1") - .await - .expect("404 must be a normal absent-secret result") - ); - handle.await.expect("stub should finish"); - assert_eq!( - request_log - .lock() - .expect("request log lock should not be poisoned") - .as_slice(), - ["GET /v5.0.0/libpod/secrets/openshell-token-sandbox-1/json"] - ); - let _ = std::fs::remove_file(socket_path); - } - - #[tokio::test] - async fn rename_container_uses_libpod_rename_endpoint() { - let (socket_path, request_log, handle) = spawn_podman_stub( - "rename-container", - vec![StubResponse::new(StatusCode::NO_CONTENT, "")], - ); - let client = PodmanClient::new(socket_path.clone()); - - client - .rename_container("sandbox-123", "sandbox-123-rollback-1") - .await - .expect("container rename should succeed"); - - handle.await.expect("stub task should finish"); - assert_eq!( - request_log - .lock() - .expect("request log lock should not be poisoned") - .as_slice(), - ["POST /v5.0.0/libpod/containers/sandbox-123/rename?name=sandbox-123-rollback-1"] - ); - let _ = std::fs::remove_file(socket_path); - } - - #[tokio::test] - async fn remove_container_uses_single_timed_libpod_removal() { - let (socket_path, request_log, handle) = spawn_podman_stub( - "remove-container", - vec![StubResponse::new(StatusCode::NO_CONTENT, "")], - ); - let client = PodmanClient::new(socket_path.clone()); - - client - .remove_container("sandbox-123", 10) - .await - .expect("container removal should succeed"); - - handle.await.expect("stub task should finish"); - assert_eq!( - request_log - .lock() - .expect("request log lock should not be poisoned") - .as_slice(), - ["DELETE /v5.0.0/libpod/containers/sandbox-123?force=true&volumes=true&timeout=10"] - ); - let _ = std::fs::remove_file(socket_path); - } - - #[tokio::test(start_paused = true)] - async fn remove_container_allows_cleanup_after_stop_timeout() { - let (socket_path, request_log, handle) = spawn_podman_stub( - "remove-container-delayed", - vec![StubResponse::new(StatusCode::NO_CONTENT, "").with_delay(Duration::from_secs(6))], - ); - let client = PodmanClient::new(socket_path.clone()); - - let removal = tokio::spawn(async move { client.remove_container("sandbox-123", 0).await }); - while request_log - .lock() - .expect("request log lock should not be poisoned") - .is_empty() - { - tokio::task::yield_now().await; - } - tokio::task::yield_now().await; - tokio::time::advance(Duration::from_secs(6)).await; - - removal - .await - .expect("removal task should finish") - .expect("container removal should retain the API timeout for cleanup"); - - handle.await.expect("stub task should finish"); - let _ = std::fs::remove_file(socket_path); - } -} diff --git a/crates/openshell-driver-podman/src/config.rs b/crates/openshell-driver-podman/src/config.rs deleted file mode 100644 index 185958652f..0000000000 --- a/crates/openshell-driver-podman/src/config.rs +++ /dev/null @@ -1,1453 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use std::net::{IpAddr, Ipv4Addr}; -use std::num::{NonZeroI64, NonZeroU64}; -use std::path::PathBuf; - -use openshell_core::{AppArmorProfile, ImagePullPolicy}; - -/// Default Podman bridge network name. -pub const DEFAULT_NETWORK_NAME: &str = "openshell"; -pub const MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP: &str = "192.168.127.254"; -/// Default Podman stop timeout in seconds (SIGTERM → SIGKILL). -pub const DEFAULT_PODMAN_STOP_TIMEOUT_SECS: u32 = 45; - -/// Translate the shared pull-policy vocabulary to the Podman libpod API. -#[must_use] -pub const fn podman_image_pull_policy(policy: ImagePullPolicy) -> &'static str { - match policy { - ImagePullPolicy::Always => "always", - ImagePullPolicy::IfNotPresent => "missing", - ImagePullPolicy::Never => "never", - ImagePullPolicy::Newer => "newer", - } -} - -#[derive(Clone, serde::Serialize, serde::Deserialize)] -#[serde(default, deny_unknown_fields)] -pub struct PodmanComputeConfig { - /// Permit caller-supplied driver JSON. Does not waive resource admission. - pub allow_driver_config: bool, - /// Operator-owned external attachment approval policy. - pub resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig, - /// Podman API Unix socket. When unset, use the socket selected by - /// gateway auto-detection. - pub socket_path: Option, - /// Default OCI image for sandboxes. - pub default_image: String, - /// Image pull policy for sandbox images. - pub image_pull_policy: ImagePullPolicy, - /// Gateway gRPC endpoint the sandbox connects back to. - /// - /// When empty, the driver selects loopback on Linux or - /// `host.containers.internal` with Podman Machine, using `gateway_port`. - pub grpc_endpoint: String, - /// OTLP exports passed to supervisors. The gateway supplies them from - /// `[otlp]`; driver TOML cannot set them. - #[serde(skip)] - pub supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, - - /// Gateway name passed to supervisors for their telemetry. The gateway - /// supplies its own name; driver TOML cannot set it. - #[serde(skip)] - pub supervisor_gateway_name: Option, - /// Port the gateway server is actually listening on. - /// - /// Used by the driver's auto-detection fallback when `grpc_endpoint` - /// is empty. The server must set this to `config.bind_address.port()` - /// so the correct port is used even when `--port` differs from the - /// default. Defaults to [`openshell_core::config::DEFAULT_SERVER_PORT`]. - pub gateway_port: u16, - /// Unix socket path the in-container supervisor bridges relay traffic to. - pub ssh_socket_path: String, - /// Name of the Podman bridge network used for driver-managed resources. - pub network_name: String, - /// Trusted supervisor-side destination for sandbox host-gateway aliases. - /// - /// Empty uses supervisor loopback on Linux and gvproxy's host-loopback IP - /// with Podman Machine. The resolved address is pinned into the protected - /// runtime descriptor; sandbox policy DNS never trusts workload resolver - /// state for `host.openshell.internal`. - pub host_gateway_ip: String, - /// Container stop timeout in seconds (SIGTERM → SIGKILL). - pub stop_timeout_secs: u32, - /// OCI image containing the statically linked `openshell-sandbox` binary. - /// The driver extracts the binary from this image into a verified host - /// cache and mounts it read-only into each sandbox container. - pub sandbox_runtime_image: String, - /// OCI image containing the dynamically linked `openshell-supervisor` binary. - pub supervisor_image: String, - /// Host path to the CA certificate for sandbox-to-gateway TLS. - /// - /// When set, the driver mounts the CA into supervisor containers and - /// switches the auto-detected endpoint from `http://` to `https://`. - pub guest_tls_ca: Option, - /// Deprecated. Sandboxes authenticate with bearer tokens. - pub guest_tls_cert: Option, - /// Deprecated. Sandboxes authenticate with bearer tokens. - pub guest_tls_key: Option, - /// Container cgroup PID limit for Podman-managed sandboxes. - /// - /// Omit the field to use `OpenShell`'s 2048-process sandbox limit. Explicit - /// zero is invalid. - #[serde( - default = "openshell_core::config::default_sandbox_pids_limit", - skip_serializing_if = "Option::is_none" - )] - pub sandbox_pids_limit: Option, - /// Allow sandbox requests to attach host bind mounts through - /// `template.driver_config`. - #[serde(default)] - pub enable_bind_mounts: bool, - /// Host path to a SPIFFE Workload API Unix socket exposed to sandbox - /// supervisors for provider token exchange client assertions. - pub provider_spiffe_workload_api_socket: Option, - /// `AppArmor` confinement requested for the workload container. Omission - /// sends no override and preserves Podman's runtime-selected profile. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub app_armor_profile: Option, - /// Health check interval in seconds for supervisor containers. - /// - /// Podman runs the health check command at this interval to determine - /// container readiness. Lower values detect readiness faster but - /// increase process churn (each check spawns a conmon subprocess). - /// Omit the field to disable health checks entirely. Explicit zero is - /// invalid. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub health_check_interval_secs: Option, - /// Corporate forward proxy URL passed to the in-container supervisor - /// (e.g. `http://proxy.corp.com:8080` or `https://proxy.corp.com:3130`). - /// - /// The supervisor chains policy-approved TLS tunnels through this proxy - /// with HTTP CONNECT instead of dialing upstream destinations directly. - /// `http://` and `https://` proxy URLs in explicit `scheme://host:port` - /// form (scheme and port required) are supported; for an `https://` proxy - /// the supervisor wraps the proxy connection in TLS, verifying the proxy - /// certificate against the built-in and system roots plus the optional - /// [`proxy_ca_bundle`](Self::proxy_ca_bundle). This is an operator-owned - /// egress boundary delivered on the supervisor's command line, so - /// sandbox/template environment cannot override it, and the conventional - /// `HTTPS_PROXY` variables are not used. - pub https_proxy: Option, - /// Comma-separated `NO_PROXY` list passed alongside the proxy URL (e.g. - /// `*.svc.cluster.local,10.0.0.0/8`). Destinations matching an entry are - /// dialed directly instead of through the corporate proxy. Entries take - /// an optional `:port` qualifier that limits them to that destination - /// port, and IP/CIDR entries also match hostnames through their - /// validated DNS resolution. - pub no_proxy: Option, - /// Path (on the gateway host) to a file containing the corporate proxy - /// credentials as `user:pass`. - /// - /// Credentials must be supplied through this file, never embedded in the - /// proxy URL: an inline `user:pass@` in `https_proxy` is - /// rejected at startup because it would leak into `gateway.toml` and - /// container metadata. The gateway reads this file at sandbox-create time - /// and delivers it to the supervisor through a root-only secret mount. - pub proxy_auth_file: Option, - /// Explicit acknowledgement that proxy credentials are sent in cleartext. - /// - /// `Proxy-Authorization: Basic` is base64, not encryption, and the - /// connection to an `http://` corporate proxy is plain TCP, so anyone on - /// the network path between the sandbox host and the proxy can recover - /// the credential. Setting `proxy_auth_file` therefore requires - /// `proxy_auth_allow_insecure = true`; without it the configuration is - /// rejected at startup. Set it only when the path to the proxy is a - /// trusted network segment. - pub proxy_auth_allow_insecure: Option, - /// Send the destination *hostname* in CONNECT requests to the corporate - /// proxy instead of a validated IP. - /// - /// By default the supervisor CONNECTs to an address that already passed - /// SSRF and `allowed_ips` validation, so the proxy performs no DNS - /// resolution and the tunnel stays bound to the validated answer. Set - /// this to `true` only when the proxy's ACLs filter on hostnames and - /// reject IP CONNECT targets: the proxy then resolves the name itself, - /// so a name that resolves differently at the proxy (split-horizon DNS, - /// rebinding) can reach destinations the sandbox policy never approved, - /// and the proxy's own ACLs become the effective egress control. Prefer - /// pointing the gateway host at the corporate resolver so validated-IP - /// CONNECT works in split-horizon networks. - pub proxy_connect_by_hostname: Option, - /// Path (on the gateway host) to a PEM CA bundle trusted for the corporate - /// proxy. - /// - /// A CA certificate is not secret, so the gateway bind-mounts this file - /// read-only into the sandbox (at - /// [`PROXY_CA_MOUNT_PATH`](openshell_core::driver_utils::PROXY_CA_MOUNT_PATH)) - /// and passes its path to the supervisor via `--upstream-proxy-ca-bundle`. - /// The supervisor trusts it for the TLS handshake with an `https://` - /// proxy and, because a TLS-intercepting proxy re-signs tunneled server - /// certificates with the same CA, folds it into the sandbox trust bundle - /// and upstream verification. Only meaningful with `https_proxy` set; the - /// bundle must exist and contain at least one certificate. - pub proxy_ca_bundle: Option, - /// Path (on the gateway host) to a PEM CA bundle trusted for direct - /// (non-proxied), policy-inspected HTTPS egress to destinations signed by - /// a private CA. - /// - /// Unlike [`proxy_ca_bundle`](Self::proxy_ca_bundle), this applies - /// regardless of whether `https_proxy` is configured: it addresses - /// supervisors that run as their own container, separate from the - /// workload image, and therefore cannot inherit a private CA baked into - /// the workload's system trust store. The gateway bind-mounts this file - /// read-only into the supervisor container (at - /// [`ADDITIONAL_CA_MOUNT_PATH`](openshell_core::driver_utils::ADDITIONAL_CA_MOUNT_PATH)) - /// and passes its path via `--additional-ca-bundle`. The supervisor folds - /// it into its upstream TLS trust store alongside (not instead of) the - /// system CA bundle. The bundle must exist and contain at least one - /// certificate; this is validated on the gateway host at sandbox-create - /// time, not deferred until the supervisor container starts. - /// - /// Populated only from the `--sandbox-additional-ca-bundle` CLI argument - /// (or `OPENSHELL_SANDBOX_ADDITIONAL_CA_BUNDLE`) for standalone drivers. - /// Deliberately excluded from driver JSON config (`#[serde(skip)]` + - /// `deny_unknown_fields`): gateway-managed deployments must use the - /// global `[openshell.supervisor.network]` setting so every driver - /// receives the same staged bundle, and a per-driver path in operator - /// JSON is rejected instead of silently diverging from it. - #[serde(skip)] - pub additional_ca_bundle: Option, - /// AAAA handling for the supervisor's mediated policy DNS (`auto`, - /// `enabled` or `disabled`). Unset means the supervisor default, `auto`. - pub policy_dns_ipv6_egress: Option, - /// NAT64 prefixes (RFC 6052) of the sandbox network. The supervisor - /// classifies addresses inside them by their embedded IPv4 address. - #[serde(default)] - pub nat64_prefixes: Vec, - /// User namespace mode for sandbox containers (e.g. `auto`, `private`). - /// When unset, containers use the default user namespace. - pub userns: Option, - /// Explicit UID mappings for `userns = "private"`. - /// Each entry is `"container_id:host_id:size"`. - #[serde(default)] - pub uidmap: Vec, - /// Explicit GID mappings for `userns = "private"`. - /// Each entry is `"container_id:host_id:size"`. - #[serde(default)] - pub gidmap: Vec, -} - -/// Parse a single `"container_id:host_id:size"` mapping entry. -/// -/// Returns `(container_id, host_id, size)` on success. -pub fn parse_id_map_entry( - field: &str, - entry: &str, -) -> Result<(u32, u32, u32), crate::client::PodmanApiError> { - let parts: Vec<&str> = entry.split(':').collect(); - if parts.len() != 3 { - return Err(crate::client::PodmanApiError::InvalidInput(format!( - "{field} entry '{entry}' must be 'container_id:host_id:size'", - ))); - } - let container_id: u32 = parts[0].parse().map_err(|_| { - crate::client::PodmanApiError::InvalidInput(format!( - "{field} entry '{entry}': container_id must be a non-negative integer", - )) - })?; - let host_id: u32 = parts[1].parse().map_err(|_| { - crate::client::PodmanApiError::InvalidInput(format!( - "{field} entry '{entry}': host_id must be a non-negative integer", - )) - })?; - let size: u32 = parts[2].parse().map_err(|_| { - crate::client::PodmanApiError::InvalidInput(format!( - "{field} entry '{entry}': size must be a non-negative integer", - )) - })?; - if size == 0 { - return Err(crate::client::PodmanApiError::InvalidInput(format!( - "{field} entry '{entry}': size must be greater than 0", - ))); - } - Ok((container_id, host_id, size)) -} - -/// Parse and validate the operator's `[openshell.drivers.podman]` table. -/// -/// This is the only place the table is parsed. It has no side effects: it -/// needs neither the gateway context nor Podman. An empty table selects the -/// defaults. -pub fn settings_from_table(table: &str) -> Result { - // The gateway supplies these through `Configure`. The standalone driver - // still takes them as flags, so the struct keeps the fields. - let keys: toml::Table = - toml::from_str(table).map_err(|error| format!("invalid podman driver table: {error}"))?; - if let Some(key) = GATEWAY_SUPPLIED_KEYS - .iter() - .find(|key| keys.contains_key(**key)) - { - return Err(format!( - "invalid podman driver table: `{key}` is supplied by the gateway and cannot be set here" - )); - } - let mut config: PodmanComputeConfig = - toml::from_str(table).map_err(|error| format!("invalid podman driver table: {error}"))?; - if !config.grpc_endpoint.trim().is_empty() { - openshell_driver_sdk::validate_grpc_endpoint(&config.grpc_endpoint)?; - } - config - .validate_configuration() - .map_err(|error| error.to_string())?; - Ok(config) -} - -/// Settings the gateway supplies through `Configure` instead of the table. -const GATEWAY_SUPPLIED_KEYS: &[&str] = &[ - "gateway_port", - "guest_tls_ca", - "allow_driver_config", - "resource_admission", -]; - -impl PodmanComputeConfig { - /// Validate and normalize startup configuration without connecting to Podman. - pub fn validate_configuration(&mut self) -> Result<(), crate::client::PodmanApiError> { - self.resource_admission - .validate() - .map_err(crate::client::PodmanApiError::InvalidInput)?; - self.validate_tls_config()?; - self.validate_runtime_limits()?; - self.validate_host_gateway_ip()?; - self.validate_proxy_config()?; - self.ipv6_egress_config() - .validate() - .map_err(crate::client::PodmanApiError::InvalidInput)?; - self.validate_app_armor_profile()?; - if let Some(socket) = self.provider_spiffe_workload_api_socket.as_deref() { - let raw = socket.to_str().ok_or_else(|| { - crate::client::PodmanApiError::InvalidInput( - "provider_spiffe_workload_api_socket must be valid UTF-8".to_string(), - ) - })?; - // Preserve pass-through support for an explicitly configured - // container-reachable Workload API TCP endpoint. - if !raw.starts_with("tcp:") { - openshell_core::driver_utils::validate_provider_spiffe_unix_socket(socket) - .map_err(crate::client::PodmanApiError::InvalidInput)?; - } - } - self.canonicalize_userns()?; - self.validate_userns_mappings() - } - - /// Supervisor IPv6 egress settings in their shared form. - #[must_use] - pub fn ipv6_egress_config(&self) -> openshell_core::SupervisorIpv6EgressConfig { - openshell_core::SupervisorIpv6EgressConfig { - policy_dns_ipv6_egress: self.policy_dns_ipv6_egress, - nat64_prefixes: self.nat64_prefixes.clone(), - } - } - - /// Returns `true` when the gateway CA is configured. - #[must_use] - pub fn tls_enabled(&self) -> bool { - self.guest_tls_ca.is_some() - } - - /// Validate TLS configuration consistency. - /// - /// Client certificates are rejected because sandbox identity is carried - /// by bearer tokens rather than the gateway user's mTLS identity. - pub fn validate_tls_config(&self) -> Result<(), crate::client::PodmanApiError> { - let has_cert = self.guest_tls_cert.is_some(); - let has_key = self.guest_tls_key.is_some(); - - if !has_cert && !has_key { - return Ok(()); - } - Err(crate::client::PodmanApiError::InvalidInput(format!( - "Sandbox client certificates are no longer supported; remove {}", - [ - has_cert.then_some("--podman-tls-cert / OPENSHELL_PODMAN_TLS_CERT"), - has_key.then_some("--podman-tls-key / OPENSHELL_PODMAN_TLS_KEY"), - ] - .into_iter() - .flatten() - .collect::>() - .join(" and ") - ))) - } - - /// Validate runtime resource-limit configuration. - pub fn validate_runtime_limits(&self) -> Result<(), crate::client::PodmanApiError> { - if self.sandbox_pids_limit.is_some_and(|limit| limit.get() < 0) { - return Err(crate::client::PodmanApiError::InvalidInput( - "sandbox_pids_limit must be positive when set".to_string(), - )); - } - Ok(()) - } - - /// Validate optional corporate proxy configuration. - /// - /// Shares validation semantics with the in-container supervisor through - /// [`openshell_core::driver_utils::parse_upstream_proxy_url`], so a value - /// accepted here can never be rejected by the supervisor at sandbox - /// startup (or vice versa). The supervisor supports `http://` and - /// `https://` forward proxies, so other schemes (SOCKS, etc.) are rejected - /// at config time instead of failing inside every sandbox. Credentials - /// must be supplied through `proxy_auth_file`; an inline `user:pass@` in - /// the URL is rejected because it would otherwise be stored in - /// `gateway.toml` and exposed in container metadata. - pub fn validate_proxy_config(&self) -> Result<(), crate::client::PodmanApiError> { - // Keep the Podman-only CA-bundle behaviour below, but delegate the - // shared URL, bypass-list, credential-file, and acknowledgement - // contract to openshell-core so Docker and VM cannot drift. - openshell_core::UpstreamProxyConfig { - https_proxy: self.https_proxy.clone(), - no_proxy: self.no_proxy.clone(), - proxy_auth_file: self.proxy_auth_file.as_ref().map(PathBuf::from), - proxy_auth_allow_insecure: self.proxy_auth_allow_insecure, - proxy_connect_by_hostname: self.proxy_connect_by_hostname, - } - .validate() - .map_err(crate::client::PodmanApiError::InvalidInput)?; - - if let Some(path) = self.proxy_ca_bundle.as_deref() { - if path.trim().is_empty() { - return Err(crate::client::PodmanApiError::InvalidInput( - "proxy_ca_bundle must not be empty when set".to_string(), - )); - } - if self.https_proxy.is_none() { - return Err(crate::client::PodmanApiError::InvalidInput( - "proxy_ca_bundle is set but no https_proxy is configured".to_string(), - )); - } - } - // additional_ca_bundle is independent of the corporate proxy setting - // above: it applies to direct, inspected egress and has no - // https_proxy dependency. Read and validate the actual host file - // here (this path is not yet mounted into any container), rather - // than only checking it is non-empty: an operator with a mistyped - // path or a certificate-free bundle should see a config-validation - // error when the driver starts, not a failed/crash-looping sandbox - // once the supervisor container starts and tries to read it. - if let Some(path) = self.additional_ca_bundle.as_deref() { - openshell_core::driver_utils::read_upstream_proxy_ca_bundle_file( - path, - "additional_ca_bundle", - ) - .map_err(crate::client::PodmanApiError::InvalidInput)?; - } - Ok(()) - } - - /// Validate and canonicalize the optional `userns` mode. - /// - /// Supported modes: `auto` (with optional params, e.g. `auto:size=65536`), - /// `host`, `keep-id` (with optional params), `no-map` (alias `nomap`), - /// and `private` (requires explicit `uidmap`/`gidmap`). - /// Modes that don't accept parameters (`host`, `no-map`, `private`) are - /// rejected when a colon-separated suffix is present. - /// - /// On success, `self.userns` is rewritten with the canonical lowercase - /// mode string so downstream code can rely on exact matches. - pub fn canonicalize_userns(&mut self) -> Result<(), crate::client::PodmanApiError> { - let Some(mode) = self.userns.as_deref() else { - return Ok(()); - }; - let (base, has_params) = mode - .split_once(':') - .map_or((mode, false), |(b, _)| (b, true)); - let canonical = match base.to_ascii_lowercase().as_str() { - "auto" => "auto", - "host" => "host", - "keep-id" => "keep-id", - "nomap" | "no-map" => "no-map", - "private" => "private", - _ => { - return Err(crate::client::PodmanApiError::InvalidInput(format!( - "unsupported userns mode '{mode}'; \ - supported modes: auto, host, keep-id, no-map, private", - ))); - } - }; - if has_params { - match canonical { - "auto" | "keep-id" => {} - _ => { - return Err(crate::client::PodmanApiError::InvalidInput(format!( - "userns mode '{canonical}' does not accept parameters", - ))); - } - } - } - self.userns = Some(if has_params { - let params = mode.split_once(':').unwrap().1; - format!("{canonical}:{params}") - } else { - canonical.to_string() - }); - Ok(()) - } - - /// Validate `uidmap`/`gidmap` consistency with the userns mode. - /// - /// `private` requires at least one entry in both `uidmap` and `gidmap`; - /// other modes (or no userns) reject non-empty mappings. Each entry must - /// be `"container_id:host_id:size"` with `size > 0`. - pub fn validate_userns_mappings(&self) -> Result<(), crate::client::PodmanApiError> { - let is_private = self - .userns - .as_deref() - .is_some_and(|m| m.eq_ignore_ascii_case("private")); - - if is_private { - if self.uidmap.is_empty() || self.gidmap.is_empty() { - return Err(crate::client::PodmanApiError::InvalidInput( - "userns mode 'private' requires at least one entry in both \ - uidmap and gidmap" - .to_string(), - )); - } - } else if !self.uidmap.is_empty() || !self.gidmap.is_empty() { - return Err(crate::client::PodmanApiError::InvalidInput( - "uidmap/gidmap are only valid with userns = \"private\"".to_string(), - )); - } - - for (field, entries) in [("uidmap", &self.uidmap), ("gidmap", &self.gidmap)] { - for entry in entries { - parse_id_map_entry(field, entry)?; - } - } - Ok(()) - } - - /// Validate optional host gateway override. - /// Validate `AppArmor` syntax before contacting the runtime. Drivers check - /// runtime availability after querying their backend. - pub fn validate_app_armor_profile(&self) -> Result<(), crate::client::PodmanApiError> { - if matches!(self.app_armor_profile, Some(AppArmorProfile::Localhost(ref name)) if name.is_empty()) - { - return Err(crate::client::PodmanApiError::InvalidInput( - "app_armor_profile Localhost profile must not be empty".to_string(), - )); - } - Ok(()) - } - - pub fn validate_host_gateway_ip(&self) -> Result<(), crate::client::PodmanApiError> { - self.resolved_host_gateway_ip().map(|_| ()) - } - - /// Resolve the trusted supervisor-side destination for host-gateway aliases. - pub fn resolved_host_gateway_ip(&self) -> Result { - let trimmed = self.host_gateway_ip.trim(); - let address = if trimmed.is_empty() { - #[cfg(target_os = "macos")] - { - MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP - .parse::() - .expect("Podman Machine host gateway constant must be an IP address") - } - #[cfg(not(target_os = "macos"))] - { - IpAddr::V4(Ipv4Addr::LOCALHOST) - } - } else { - trimmed.parse::().map_err(|err| { - crate::client::PodmanApiError::InvalidInput(format!( - "invalid host_gateway_ip value '{trimmed}': {err}" - )) - })? - }; - - let normalized = match address { - IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or(address, IpAddr::V4), - IpAddr::V4(_) => address, - }; - if address.is_unspecified() - || address.is_multicast() - || normalized == IpAddr::V4(Ipv4Addr::BROADCAST) - || normalized == IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254)) - { - return Err(crate::client::PodmanApiError::InvalidInput(format!( - "invalid host_gateway_ip value '{address}': address is not a safe concrete host destination" - ))); - } - - Ok(address) - } - - /// Resolve the default host gateway override for the current platform. - #[must_use] - pub fn default_host_gateway_ip() -> String { - #[cfg(target_os = "macos")] - { - MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP.to_string() - } - #[cfg(not(target_os = "macos"))] - { - String::new() - } - } -} - -impl Default for PodmanComputeConfig { - fn default() -> Self { - Self { - socket_path: None, - allow_driver_config: false, - resource_admission: - openshell_core::resource_admission::ResourceAdmissionConfig::default(), - default_image: openshell_core::image::default_sandbox_image(), - image_pull_policy: ImagePullPolicy::default(), - grpc_endpoint: String::new(), - supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp::default(), - supervisor_gateway_name: None, - gateway_port: openshell_core::config::DEFAULT_SERVER_PORT, - ssh_socket_path: openshell_core::container_paths::SSH_SOCKET_PATH.to_string(), - network_name: DEFAULT_NETWORK_NAME.to_string(), - host_gateway_ip: Self::default_host_gateway_ip(), - stop_timeout_secs: DEFAULT_PODMAN_STOP_TIMEOUT_SECS, - sandbox_runtime_image: openshell_core::config::default_sandbox_runtime_image(), - supervisor_image: openshell_core::config::default_supervisor_image(), - guest_tls_ca: None, - guest_tls_cert: None, - guest_tls_key: None, - sandbox_pids_limit: openshell_core::config::default_sandbox_pids_limit(), - enable_bind_mounts: false, - provider_spiffe_workload_api_socket: None, - app_armor_profile: None, - health_check_interval_secs: None, - https_proxy: None, - no_proxy: None, - proxy_auth_file: None, - proxy_auth_allow_insecure: None, - proxy_connect_by_hostname: None, - proxy_ca_bundle: None, - additional_ca_bundle: None, - policy_dns_ipv6_egress: None, - nat64_prefixes: Vec::new(), - userns: None, - uidmap: Vec::new(), - gidmap: Vec::new(), - } - } -} - -impl std::fmt::Debug for PodmanComputeConfig { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("PodmanComputeConfig") - .field("socket_path", &self.socket_path) - .field("default_image", &self.default_image) - .field("image_pull_policy", &self.image_pull_policy) - .field("grpc_endpoint", &self.grpc_endpoint) - .field("gateway_port", &self.gateway_port) - .field("ssh_socket_path", &self.ssh_socket_path) - .field("network_name", &self.network_name) - .field("host_gateway_ip", &self.host_gateway_ip) - .field("stop_timeout_secs", &self.stop_timeout_secs) - .field("sandbox_runtime_image", &self.sandbox_runtime_image) - .field("supervisor_image", &self.supervisor_image) - .field("guest_tls_ca", &self.guest_tls_ca) - .field("guest_tls_cert", &self.guest_tls_cert) - .field("guest_tls_key", &self.guest_tls_key) - .field("sandbox_pids_limit", &self.sandbox_pids_limit) - .field("enable_bind_mounts", &self.enable_bind_mounts) - .field( - "provider_spiffe_workload_api_socket", - &self.provider_spiffe_workload_api_socket, - ) - .field("app_armor_profile", &self.app_armor_profile) - .field( - "health_check_interval_secs", - &self.health_check_interval_secs, - ) - // Proxy URLs may embed credentials in userinfo; log presence only. - .field("https_proxy", &self.https_proxy.is_some()) - .field("no_proxy", &self.no_proxy) - .field("proxy_auth_file", &self.proxy_auth_file.is_some()) - .field("proxy_auth_allow_insecure", &self.proxy_auth_allow_insecure) - .field("proxy_connect_by_hostname", &self.proxy_connect_by_hostname) - .field("proxy_ca_bundle", &self.proxy_ca_bundle) - .field("policy_dns_ipv6_egress", &self.policy_dns_ipv6_egress) - .field("nat64_prefixes", &self.nat64_prefixes) - .field("userns", &self.userns) - .field("uidmap", &self.uidmap) - .field("gidmap", &self.gidmap) - .finish() - } -} - -#[cfg(test)] -mod table_tests { - use super::*; - - #[test] - fn gateway_supplied_keys_are_rejected() { - for key in [ - "gateway_port = 8080", - "guest_tls_ca = \"/ca.pem\"", - "allow_driver_config = true", - "resource_admission = {}", - ] { - let error = settings_from_table(key).unwrap_err(); - assert!(error.contains("supplied by the gateway"), "{error}"); - } - } - - #[test] - fn grpc_endpoint_is_checked_for_syntax_and_scheme() { - settings_from_table("grpc_endpoint = \"https://gw.test:8443\"").unwrap(); - for bad in ["ftp://gw.test:1", "gw.test:8080"] { - assert!( - settings_from_table(&format!("grpc_endpoint = \"{bad}\"")).is_err(), - "accepted: {bad}" - ); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shared_image_pull_policies_map_to_podman_vocabulary() { - for (policy, expected) in [ - (ImagePullPolicy::Always, "always"), - (ImagePullPolicy::IfNotPresent, "missing"), - (ImagePullPolicy::Never, "never"), - (ImagePullPolicy::Newer, "newer"), - ] { - assert_eq!(podman_image_pull_policy(policy), expected); - } - } - - #[test] - fn config_uses_canonical_ssh_socket_path_name() { - let config: PodmanComputeConfig = - serde_json::from_value(serde_json::json!({ "ssh_socket_path": "/run/test.sock" })) - .unwrap(); - assert_eq!(config.ssh_socket_path, "/run/test.sock"); - - let serialized = serde_json::to_value(config).unwrap(); - assert_eq!(serialized["ssh_socket_path"], "/run/test.sock"); - assert!(serialized.get("sandbox_ssh_socket_path").is_none()); - } - - #[test] - fn config_rejects_legacy_sandbox_ssh_socket_path() { - let error = serde_json::from_value::(serde_json::json!({ - "sandbox_ssh_socket_path": "/run/test.sock" - })) - .expect_err("legacy sandbox_ssh_socket_path must be rejected"); - assert!(error.to_string().contains("sandbox_ssh_socket_path")); - } - - #[test] - fn config_rejects_driver_specific_destination_ca_setting() { - let error = serde_json::from_value::(serde_json::json!({ - "additional_ca_bundle": ["/operator/ca.crt"] - })) - .expect_err("destination trust is global, not a Podman driver setting"); - assert!(error.to_string().contains("additional_ca_bundle")); - } - - #[test] - fn default_config_disables_health_checks() { - assert_eq!( - PodmanComputeConfig::default().health_check_interval_secs, - None - ); - } - - #[test] - fn omitted_apparmor_profile_preserves_runtime_default() { - let config: PodmanComputeConfig = serde_json::from_value(serde_json::json!({})) - .expect("omitted AppArmor profile should deserialize"); - assert_eq!(config.app_armor_profile, None); - - let serialized = serde_json::to_value(config).expect("config should serialize"); - assert!(serialized.get("app_armor_profile").is_none()); - } - - #[test] - fn explicit_apparmor_profiles_round_trip() { - for value in [ - "RuntimeDefault", - "Unconfined", - "Localhost/openshell-supervisor", - ] { - let config: PodmanComputeConfig = serde_json::from_value(serde_json::json!({ - "app_armor_profile": value, - })) - .expect("explicit AppArmor profile should deserialize"); - let serialized = serde_json::to_value(config).expect("config should serialize"); - assert_eq!(serialized["app_armor_profile"], value); - } - } - - #[test] - fn default_config_sets_podman_stop_timeout() { - let cfg = PodmanComputeConfig::default(); - assert_eq!(cfg.stop_timeout_secs, DEFAULT_PODMAN_STOP_TIMEOUT_SECS); - } - - #[test] - fn default_config_sets_driver_owned_pids_limit() { - let cfg = PodmanComputeConfig::default(); - assert_eq!( - cfg.sandbox_pids_limit.map(NonZeroI64::get), - Some(openshell_core::config::DEFAULT_SANDBOX_PIDS_LIMIT) - ); - assert!(!cfg.enable_bind_mounts); - } - - #[test] - fn omitted_pids_limit_uses_driver_owned_default() { - let cfg: PodmanComputeConfig = serde_json::from_value(serde_json::json!({})) - .expect("default Podman config should deserialize"); - assert_eq!( - cfg.sandbox_pids_limit.map(NonZeroI64::get), - Some(openshell_core::config::DEFAULT_SANDBOX_PIDS_LIMIT) - ); - } - - #[test] - #[cfg(target_os = "macos")] - fn default_config_uses_gvproxy_host_gateway_ip_on_macos() { - let cfg = PodmanComputeConfig::default(); - assert_eq!(cfg.host_gateway_ip, MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP); - assert!(cfg.validate_host_gateway_ip().is_ok()); - assert_eq!( - cfg.resolved_host_gateway_ip().unwrap(), - MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP - .parse::() - .unwrap() - ); - } - - #[test] - #[cfg(not(target_os = "macos"))] - fn default_config_leaves_host_gateway_ip_empty_off_macos() { - let cfg = PodmanComputeConfig::default(); - assert!(cfg.host_gateway_ip.is_empty()); - assert!(cfg.validate_host_gateway_ip().is_ok()); - assert_eq!( - cfg.resolved_host_gateway_ip().unwrap(), - IpAddr::V4(Ipv4Addr::LOCALHOST) - ); - } - - #[test] - fn host_gateway_ip_validation_rejects_invalid_values() { - let cfg = PodmanComputeConfig { - host_gateway_ip: "not-an-ip".to_string(), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_host_gateway_ip().unwrap_err(); - assert!(err.to_string().contains("host_gateway_ip")); - } - - #[test] - fn host_gateway_ip_resolution_preserves_explicit_address() { - let cfg = PodmanComputeConfig { - host_gateway_ip: "192.168.127.254".to_string(), - ..PodmanComputeConfig::default() - }; - assert_eq!( - cfg.resolved_host_gateway_ip().unwrap(), - "192.168.127.254".parse::().unwrap() - ); - } - - #[test] - fn host_gateway_ip_validation_rejects_unsafe_destinations() { - for address in ["0.0.0.0", "224.0.0.1", "255.255.255.255", "169.254.169.254"] { - let cfg = PodmanComputeConfig { - host_gateway_ip: address.to_string(), - ..PodmanComputeConfig::default() - }; - let error = cfg.validate_host_gateway_ip().unwrap_err(); - assert!( - error.to_string().contains("safe concrete host destination"), - "unexpected validation error for {address}: {error}" - ); - } - } - - #[test] - fn runtime_limit_rejects_invalid_pids_limits() { - let zero = serde_json::from_value::(serde_json::json!({ - "sandbox_pids_limit": 0 - })) - .expect_err("zero PID limit must be rejected"); - assert!(zero.to_string().contains("invalid value: integer `0`")); - - let negative: PodmanComputeConfig = serde_json::from_value(serde_json::json!({ - "sandbox_pids_limit": -1 - })) - .expect("nonzero integer deserializes before semantic validation"); - let error = negative.validate_runtime_limits().unwrap_err(); - assert!(error.to_string().contains("must be positive")); - } - - #[test] - fn health_check_interval_rejects_zero() { - let error = serde_json::from_value::(serde_json::json!({ - "health_check_interval_secs": 0 - })) - .expect_err("zero health-check interval must be rejected"); - assert!(error.to_string().contains("invalid value: integer `0`")); - } - - // ── Proxy config validation ─────────────────────────────────────── - - #[test] - fn validate_proxy_config_accepts_unset_http_and_https() { - assert!( - PodmanComputeConfig::default() - .validate_proxy_config() - .is_ok() - ); - let cfg = PodmanComputeConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - no_proxy: Some("*.svc.cluster.local".to_string()), - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_proxy_config().is_ok()); - // An https:// proxy URL is now supported (scheme and port required). - let cfg = PodmanComputeConfig { - https_proxy: Some("https://proxy.corp.com:3130".to_string()), - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_proxy_config().is_ok()); - } - - #[test] - fn validate_proxy_config_rejects_socks_schemes() { - // http:// and https:// are supported; only other schemes are rejected. - for url in ["socks5://proxy:1080", "ftp://proxy:21"] { - let cfg = PodmanComputeConfig { - https_proxy: Some(url.to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!( - err.to_string().contains("unsupported proxy scheme"), - "{url}: {err}" - ); - } - } - - #[test] - fn validate_proxy_config_accepts_ca_bundle_with_proxy() { - let cfg = PodmanComputeConfig { - https_proxy: Some("https://proxy.corp.com:3130".to_string()), - proxy_ca_bundle: Some("/etc/openshell/proxy-ca.pem".to_string()), - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_proxy_config().is_ok()); - // A CA bundle is also valid with an http:// proxy: a TLS-intercepting - // proxy reached over plain HTTP still re-signs upstream certificates. - let cfg = PodmanComputeConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - proxy_ca_bundle: Some("/etc/openshell/proxy-ca.pem".to_string()), - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_proxy_config().is_ok()); - } - - #[test] - fn validate_proxy_config_rejects_ca_bundle_without_proxy() { - let cfg = PodmanComputeConfig { - proxy_ca_bundle: Some("/etc/openshell/proxy-ca.pem".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("proxy_ca_bundle"), "{err}"); - assert!(err.to_string().contains("no https_proxy"), "{err}"); - } - - #[test] - fn validate_proxy_config_rejects_empty_ca_bundle() { - let cfg = PodmanComputeConfig { - https_proxy: Some("https://proxy.corp.com:3130".to_string()), - proxy_ca_bundle: Some(" ".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("proxy_ca_bundle"), "{err}"); - } - - #[test] - fn validate_configuration_accepts_additional_ca_bundle_without_proxy() { - // #3781: unlike proxy_ca_bundle, this must work with no corporate - // proxy configured at all. - let directory = tempfile::tempdir().unwrap(); - let ca_path = directory.path().join("additional-ca.pem"); - std::fs::write(&ca_path, generate_test_ca_pem()).unwrap(); - - let cfg = PodmanComputeConfig { - additional_ca_bundle: Some(ca_path.to_str().unwrap().to_string()), - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_proxy_config().is_ok()); - assert!(cfg.https_proxy.is_none()); - } - - #[test] - fn validate_configuration_rejects_empty_additional_ca_bundle() { - let cfg = PodmanComputeConfig { - additional_ca_bundle: Some(" ".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("additional_ca_bundle"), "{err}"); - } - - #[test] - fn validate_configuration_rejects_nonexistent_additional_ca_bundle() { - // #3781 fix requirement: an operator with a mistyped path must see - // this at config-validation time, not a failed sandbox later. - let cfg = PodmanComputeConfig { - additional_ca_bundle: Some("/nonexistent/additional-ca.pem".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("additional_ca_bundle"), "{err}"); - } - - #[test] - fn validate_configuration_rejects_certificate_free_additional_ca_bundle() { - let directory = tempfile::tempdir().unwrap(); - let ca_path = directory.path().join("not-a-cert.pem"); - std::fs::write(&ca_path, "not a certificate\n").unwrap(); - - let cfg = PodmanComputeConfig { - additional_ca_bundle: Some(ca_path.to_str().unwrap().to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("additional_ca_bundle"), "{err}"); - } - - /// Generate a real, valid self-signed CA certificate PEM for tests. - fn generate_test_ca_pem() -> String { - let key_pair = openshell_crypto::pki::generate_keypair().unwrap(); - let params = rcgen::CertificateParams::new(Vec::new()).unwrap(); - openshell_crypto::pki::self_signed(params, &key_pair) - .unwrap() - .pem() - } - - #[test] - fn validate_proxy_config_rejects_url_components() { - for url in [ - "http://proxy.corp.com:8080/path", - "http://proxy.corp.com:8080?x=1", - "http://proxy.corp.com:8080#frag", - ] { - let cfg = PodmanComputeConfig { - https_proxy: Some(url.to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!( - err.to_string().contains("scheme://host:port"), - "{url}: {err}" - ); - } - } - - #[test] - fn validate_proxy_config_rejects_zero_port() { - let cfg = PodmanComputeConfig { - https_proxy: Some("http://proxy.corp.com:0".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("port must not be 0"), "{err}"); - } - - #[test] - fn validate_proxy_config_rejects_missing_scheme_or_port() { - // A scheme-less value (previously normalized to http://) and a - // port-less value (previously defaulted to 80) are both rejected so - // gateway.toml matches the documented http://host:port grammar. - for url in ["proxy.corp.com:8080", "http://proxy.corp.com"] { - let cfg = PodmanComputeConfig { - https_proxy: Some(url.to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("explicit"), "{url}: {err}"); - } - } - - #[test] - fn validate_proxy_config_rejects_empty_value() { - let cfg = PodmanComputeConfig { - https_proxy: Some(" ".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("https_proxy"), "{err}"); - } - - #[test] - fn validate_proxy_config_rejects_empty_no_proxy() { - let cfg = PodmanComputeConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - no_proxy: Some(" ".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("no_proxy"), "{err}"); - } - - #[test] - fn validate_proxy_config_rejects_no_proxy_without_proxy() { - let cfg = PodmanComputeConfig { - no_proxy: Some("*.svc.cluster.local".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("no_proxy"), "{err}"); - } - - #[test] - fn validate_proxy_config_rejects_inline_credentials() { - for url in [ - "http://user:pass@proxy.corp.com:8080", - "http://user@proxy.corp.com:8080", - ] { - let cfg = PodmanComputeConfig { - https_proxy: Some(url.to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!( - err.to_string().contains("proxy_auth_file"), - "{url} should be rejected and point at proxy_auth_file: {err}" - ); - } - } - - #[test] - fn validate_proxy_config_accepts_auth_file_with_proxy_and_acknowledgement() { - let cfg = PodmanComputeConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()), - proxy_auth_allow_insecure: Some(true), - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_proxy_config().is_ok()); - } - - #[test] - fn validate_proxy_config_rejects_auth_file_without_insecure_acknowledgement() { - // Basic auth over the plain-TCP proxy connection is readable on the - // network path; sending it must be an explicit operator decision. - for allow in [None, Some(false)] { - let cfg = PodmanComputeConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()), - proxy_auth_allow_insecure: allow, - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!( - err.to_string().contains("proxy_auth_allow_insecure"), - "{allow:?}: {err}" - ); - assert!(err.to_string().contains("cleartext"), "{allow:?}: {err}"); - } - } - - #[test] - fn validate_proxy_config_accepts_auth_file_without_acknowledgement_for_https_proxy() { - let cfg = PodmanComputeConfig { - https_proxy: Some("https://proxy.corp.com:3130".to_string()), - proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()), - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_proxy_config().is_ok()); - } - - #[test] - fn validate_proxy_config_accepts_connect_by_hostname_with_proxy() { - for by_hostname in [Some(true), Some(false)] { - let cfg = PodmanComputeConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - proxy_connect_by_hostname: by_hostname, - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_proxy_config().is_ok(), "{by_hostname:?}"); - } - } - - #[test] - fn validate_proxy_config_rejects_connect_by_hostname_without_proxy() { - let cfg = PodmanComputeConfig { - proxy_connect_by_hostname: Some(true), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("no https_proxy"), "{err}"); - } - - #[test] - fn validate_proxy_config_rejects_acknowledgement_without_auth_file() { - for allow in [Some(true), Some(false)] { - let cfg = PodmanComputeConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - proxy_auth_allow_insecure: allow, - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!( - err.to_string().contains("no proxy_auth_file"), - "{allow:?}: {err}" - ); - } - } - - #[test] - fn validate_configuration_checks_nat64_prefixes() { - let mut config: PodmanComputeConfig = serde_json::from_str( - r#"{"policy_dns_ipv6_egress":"enabled","nat64_prefixes":["2001:db8:64::/96"]}"#, - ) - .expect("podman config parses"); - assert_eq!( - config.policy_dns_ipv6_egress, - Some(openshell_core::PolicyDnsIpv6Egress::Enabled) - ); - config.validate_configuration().unwrap(); - - config.nat64_prefixes = vec!["10.0.0.0/8".to_string()]; - assert!(config.validate_configuration().is_err()); - } - - #[test] - fn validate_proxy_config_rejects_auth_file_without_proxy() { - let cfg = PodmanComputeConfig { - proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_proxy_config().unwrap_err(); - assert!(err.to_string().contains("proxy_auth_file"), "{err}"); - } - - // ── TLS config validation ───────────────────────────────────────── - - #[test] - fn validate_tls_config_all_none_is_ok() { - let cfg = PodmanComputeConfig::default(); - assert!(cfg.validate_tls_config().is_ok()); - } - - #[test] - fn validate_tls_config_ca_only_is_ok() { - let cfg = PodmanComputeConfig { - guest_tls_ca: Some(PathBuf::from("/tls/ca.crt")), - ..PodmanComputeConfig::default() - }; - assert!(cfg.validate_tls_config().is_ok()); - assert!(cfg.tls_enabled()); - } - - #[test] - fn validate_tls_config_rejects_client_certificate() { - let cfg = PodmanComputeConfig { - guest_tls_cert: Some(PathBuf::from("/tls/tls.crt")), - ..PodmanComputeConfig::default() - }; - let err = cfg - .validate_tls_config() - .expect_err("sandbox client certificate should be rejected"); - let msg = err.to_string(); - assert!(msg.contains("OPENSHELL_PODMAN_TLS_CERT"), "{msg}"); - } - - #[test] - fn validate_tls_config_rejects_client_private_key() { - let cfg = PodmanComputeConfig { - guest_tls_key: Some(PathBuf::from("/tls/tls.key")), - ..PodmanComputeConfig::default() - }; - let err = cfg - .validate_tls_config() - .expect_err("sandbox client private key should be rejected"); - let msg = err.to_string(); - assert!(msg.contains("OPENSHELL_PODMAN_TLS_KEY"), "{msg}"); - } - - #[test] - fn canonicalize_userns_accepts_supported_modes() { - for mode in [ - "auto", - "host", - "keep-id", - "no-map", - "private", - "auto:size=65536", - "keep-id:uid=1000,gid=1000", - ] { - let mut cfg = PodmanComputeConfig { - userns: Some(mode.to_string()), - ..PodmanComputeConfig::default() - }; - cfg.canonicalize_userns() - .unwrap_or_else(|_| panic!("mode '{mode}' should be accepted")); - } - } - - #[test] - fn canonicalize_userns_normalizes_case_and_aliases() { - let cases = [ - ("Auto", "auto"), - ("HOST", "host"), - ("KEEP-ID:uid=1000", "keep-id:uid=1000"), - ("nomap", "no-map"), - ("no-map", "no-map"), - ("Private", "private"), - ("auto:SIZE=65536", "auto:SIZE=65536"), - ]; - for (input, expected) in cases { - let mut cfg = PodmanComputeConfig { - userns: Some(input.to_string()), - ..PodmanComputeConfig::default() - }; - cfg.canonicalize_userns() - .unwrap_or_else(|_| panic!("mode '{input}' should be accepted")); - assert_eq!( - cfg.userns.as_deref(), - Some(expected), - "input '{input}' should canonicalize to '{expected}'" - ); - } - } - - #[test] - fn canonicalize_userns_rejects_unsupported_modes() { - for mode in ["container:foo", "ns:/proc/1/ns/user", "4000:5000"] { - let mut cfg = PodmanComputeConfig { - userns: Some(mode.to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg - .canonicalize_userns() - .expect_err(&format!("mode '{mode}' should be rejected")); - let msg = err.to_string(); - assert!(msg.contains("unsupported userns mode"), "{msg}"); - } - } - - #[test] - fn canonicalize_userns_rejects_params_on_non_parameterizable_modes() { - for mode in ["host:foo", "no-map:x=1", "private:x=1"] { - let mut cfg = PodmanComputeConfig { - userns: Some(mode.to_string()), - ..PodmanComputeConfig::default() - }; - let err = cfg - .canonicalize_userns() - .expect_err(&format!("mode '{mode}' should be rejected")); - let msg = err.to_string(); - assert!(msg.contains("does not accept parameters"), "{msg}"); - } - } - - #[test] - fn canonicalize_userns_accepts_none() { - let mut cfg = PodmanComputeConfig::default(); - cfg.canonicalize_userns().expect("None should be accepted"); - } - - // ── Userns mapping validation ──────────────────────────────────── - - #[test] - fn validate_userns_mappings_accepts_private_with_maps() { - let cfg = PodmanComputeConfig { - userns: Some("private".to_string()), - uidmap: vec!["0:1000:1".to_string(), "1:100000:65536".to_string()], - gidmap: vec!["0:1000:1".to_string(), "1:100000:65536".to_string()], - ..PodmanComputeConfig::default() - }; - cfg.validate_userns_mappings() - .expect("private with mappings should be accepted"); - } - - #[test] - fn validate_userns_mappings_rejects_private_without_uidmap() { - let cfg = PodmanComputeConfig { - userns: Some("private".to_string()), - gidmap: vec!["0:1000:1".to_string()], - ..PodmanComputeConfig::default() - }; - let err = cfg - .validate_userns_mappings() - .expect_err("private without uidmap should be rejected"); - assert!(err.to_string().contains("uidmap"), "{err}"); - } - - #[test] - fn validate_userns_mappings_rejects_private_without_gidmap() { - let cfg = PodmanComputeConfig { - userns: Some("private".to_string()), - uidmap: vec!["0:1000:1".to_string()], - ..PodmanComputeConfig::default() - }; - let err = cfg - .validate_userns_mappings() - .expect_err("private without gidmap should be rejected"); - assert!(err.to_string().contains("gidmap"), "{err}"); - } - - #[test] - fn validate_userns_mappings_rejects_maps_without_private() { - for mode in [Some("auto"), Some("host"), Some("keep-id"), None] { - let cfg = PodmanComputeConfig { - userns: mode.map(ToString::to_string), - uidmap: vec!["0:1000:1".to_string()], - gidmap: vec!["0:1000:1".to_string()], - ..PodmanComputeConfig::default() - }; - let err = cfg.validate_userns_mappings().expect_err(&format!( - "mappings without private should be rejected (mode={mode:?})" - )); - assert!( - err.to_string().contains("only valid with"), - "{mode:?}: {err}" - ); - } - } - - #[test] - fn validate_userns_mappings_rejects_malformed_entries() { - let cases = [ - ("0:1000", "too few fields"), - ("0:1000:1:extra", "too many fields"), - ("abc:1000:1", "non-numeric container_id"), - ("0:abc:1", "non-numeric host_id"), - ("0:1000:abc", "non-numeric size"), - ("0:1000:0", "zero size"), - ]; - for (entry, desc) in cases { - let cfg = PodmanComputeConfig { - userns: Some("private".to_string()), - uidmap: vec![entry.to_string()], - gidmap: vec!["0:1000:1".to_string()], - ..PodmanComputeConfig::default() - }; - cfg.validate_userns_mappings() - .expect_err(&format!("{desc}: '{entry}' should be rejected")); - } - } - - #[test] - fn validate_userns_mappings_accepts_no_userns_no_maps() { - let cfg = PodmanComputeConfig::default(); - cfg.validate_userns_mappings() - .expect("no userns and no maps should be accepted"); - } -} diff --git a/crates/openshell-driver-podman/src/container.rs b/crates/openshell-driver-podman/src/container.rs deleted file mode 100644 index 38135d2eb4..0000000000 --- a/crates/openshell-driver-podman/src/container.rs +++ /dev/null @@ -1,4437 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Container spec construction for the Podman driver. - -use crate::client::ImageInspect; -use crate::config::PodmanComputeConfig; -use openshell_core::ComputeDriverError; -use openshell_core::driver_mounts::SelinuxLabel; -use openshell_core::gpu::validate_cdi_device_names; -#[cfg(test)] -use openshell_core::gpu::{driver_gpu_requirements, validate_cdi_gpu_device_request}; -use openshell_core::network_trust::{ - NETWORK_SUPERVISOR_TRUST_GENERATION_KEY, NETWORK_SUPERVISOR_TRUST_GENERATION_NONE, -}; -use openshell_core::proto::compute::v1::{DriverSandbox, DriverSandboxTemplate}; -use openshell_core::proto_struct::deserialize_optional_non_empty_string_list; -use openshell_core::{NetworkSupervisorTrustBundle, driver_mounts, proto_struct}; -use serde::Serialize; -use serde_json::Value; -use std::collections::{BTreeMap, HashSet}; -use std::path::Path; - -/// Returns `true` when `SELinux` is enabled (enforcing or permissive). -/// -/// Checks whether selinuxfs is mounted, matching Podman's own detection -/// logic. Bind-mount relabeling (the `z` mount option) is needed in both -/// enforcing and permissive modes: enforcing blocks access outright, while -/// permissive floods the audit log with AVC denials that mask real issues. -/// -/// On non-`SELinux` systems (Ubuntu, macOS, Alpine) the directory does not -/// exist and this returns `false`, leaving mount options unchanged. -#[cfg(target_os = "linux")] -fn is_selinux_enabled() -> bool { - Path::new("/sys/fs/selinux").is_dir() -} - -#[cfg(not(target_os = "linux"))] -fn is_selinux_enabled() -> bool { - false -} - -pub use openshell_core::driver_utils::{ - LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, LABEL_SANDBOX_NAMESPACE, LABEL_SANDBOX_WORKSPACE, -}; - -/// Label applied to all managed containers. -pub const LABEL_MANAGED: &str = "openshell.managed"; -/// Label filter string for list/event queries. -pub const LABEL_MANAGED_FILTER: &str = "openshell.managed=true"; - -/// Container name prefix to avoid collisions with user containers. -const CONTAINER_PREFIX: &str = "openshell-"; - -/// Volume name prefix. -const VOLUME_PREFIX: &str = "openshell-sandbox-"; -const PODMAN_WORKLOAD_CONTROL_PATHS: &[&str] = &[ - "/.openshell", - openshell_sandbox_backend::SUPERVISOR_CA_RUNTIME_ROOT, -]; - -/// Secret name prefix for per-sandbox gateway JWTs. -const TOKEN_SECRET_PREFIX: &str = "openshell-token-"; -const PROXY_AUTH_SECRET_PREFIX: &str = "openshell-proxy-auth-"; -const RESOLVER_SECRET_PREFIX: &str = "openshell-resolver-"; -const TLS_CA_SECRET_PREFIX: &str = "openshell-tls-ca-"; - -/// Container-side mount paths for client TLS materials and the sandbox token. -const TLS_CA_MOUNT_PATH: &str = openshell_core::driver_utils::TLS_CA_MOUNT_PATH; -const SANDBOX_TOKEN_MOUNT_PATH: &str = openshell_core::driver_utils::SANDBOX_TOKEN_MOUNT_PATH; -const UPSTREAM_PROXY_AUTH_MOUNT_PATH: &str = - openshell_core::driver_utils::UPSTREAM_PROXY_AUTH_MOUNT_PATH; -const RESOLV_CONF_PATH: &str = "/etc/resolv.conf"; -const PROXY_CA_MOUNT_PATH: &str = openshell_core::driver_utils::PROXY_CA_MOUNT_PATH; -const ADDITIONAL_CA_MOUNT_PATH: &str = openshell_core::driver_utils::ADDITIONAL_CA_MOUNT_PATH; -const PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR: &str = - openshell_core::driver_utils::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR; - -/// Directory inside sandbox containers where the supervisor binary is mounted. -const SUPERVISOR_MOUNT_DIR: &str = openshell_core::driver_utils::SUPERVISOR_CONTAINER_DIR; -/// Full path to the supervisor binary inside sandbox containers. -const SUPERVISOR_BINARY_PATH: &str = openshell_core::driver_utils::SUPERVISOR_CONTAINER_BINARY; - -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(default, deny_unknown_fields)] -pub struct PodmanSandboxDriverConfig { - #[serde( - default, - deserialize_with = "deserialize_optional_non_empty_string_list" - )] - pub cdi_devices: Option>, - mounts: Vec, -} - -impl PodmanSandboxDriverConfig { - pub(crate) fn admit_mount_types( - &self, - policy: &openshell_core::resource_admission::ResourceAdmissionConfig, - ) -> Result<(), ComputeDriverError> { - for mount in &self.mounts { - if matches!( - mount, - PodmanDriverMountConfig::Bind { .. } | PodmanDriverMountConfig::Image { .. } - ) { - policy - .reject_unlabelable("host bind or image mount") - .map_err(|error| ComputeDriverError::Precondition(error.message().into()))?; - } - } - Ok(()) - } - - pub fn from_sandbox(sandbox: &DriverSandbox) -> Result { - let Some(template) = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - else { - return Ok(Self::default()); - }; - - Self::from_template(template) - } - - pub fn from_template(template: &DriverSandboxTemplate) -> Result { - let Some(config) = template.driver_config.as_ref() else { - return Ok(Self::default()); - }; - - proto_struct::from_struct(config).map_err(|err| { - ComputeDriverError::InvalidArgument(format!("invalid podman driver_config: {err}")) - }) - } -} - -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] -enum PodmanDriverMountConfig { - Bind { - source: String, - target: String, - #[serde(default = "default_true")] - read_only: bool, - #[serde(default)] - selinux_label: Option, - }, - Volume { - source: String, - target: String, - #[serde(default = "default_true")] - read_only: bool, - #[serde(default)] - subpath: Option, - }, - Tmpfs { - target: String, - #[serde(default)] - options: Vec, - #[serde(default)] - size_bytes: Option, - #[serde(default)] - mode: Option, - }, - Image { - source: String, - target: String, - #[serde(default = "default_true")] - read_only: bool, - #[serde(default)] - subpath: Option, - }, -} - -fn default_true() -> bool { - true -} - -/// Build a Podman container name from the sandbox workspace, name, and ID. -/// -/// Format: `openshell-{workspace}--{name}-{id}` -#[must_use] -pub fn container_name(workspace: &str, name: &str, id: &str) -> String { - format!("{CONTAINER_PREFIX}{workspace}--{name}-{id}") -} - -/// Build the workspace volume name from the sandbox ID. -#[must_use] -pub fn volume_name(sandbox_id: &str) -> String { - format!("{VOLUME_PREFIX}{sandbox_id}-workspace") -} - -/// Build the per-sandbox Podman secret name for the gateway JWT. -#[must_use] -pub fn token_secret_name(sandbox_id: &str) -> String { - format!("{TOKEN_SECRET_PREFIX}{sandbox_id}") -} - -/// Build the per-sandbox Podman secret name for the corporate proxy credentials. -#[must_use] -pub fn proxy_auth_secret_name(sandbox_id: &str) -> String { - format!("{PROXY_AUTH_SECRET_PREFIX}{sandbox_id}") -} - -/// Build the per-sandbox Podman secret name for the mediated DNS resolver. -#[must_use] -pub fn resolver_secret_name(sandbox_id: &str) -> String { - format!("{RESOLVER_SECRET_PREFIX}{sandbox_id}") -} - -/// Build the per-sandbox Podman secret name for the gateway CA. -#[must_use] -pub fn tls_secret_names(sandbox_id: &str) -> [String; 1] { - [format!("{TLS_CA_SECRET_PREFIX}{sandbox_id}")] -} - -/// Truncate a container ID to 12 characters (standard short form). -#[must_use] -pub fn short_id(id: &str) -> String { - id.chars().take(12).collect() -} - -/// Immutable OCI image metadata normalized once for final launch. -#[derive(Debug, Clone)] -pub struct ResolvedPodmanImage { - /// Original reference for child metadata; launch always uses the immutable ID. - pub(crate) requested_image: String, - pub(crate) id: String, - pub(crate) oci_user: String, - pub(crate) environment: Vec, - pub(crate) workspace_root: String, -} - -impl ResolvedPodmanImage { - /// Resolve the image metadata and reject: - /// - a malformed or reserved working directory; - /// - for a custom working directory, an image volume with an invalid or - /// reserved target, or one covering the resolved workspace. - pub fn from_inspect( - requested_image: &str, - inspected: ImageInspect, - ) -> Result { - let config = inspected.config.unwrap_or_default(); - let workspace_root = driver_mounts::resolve_oci_workspace_root(&config.working_dir) - .map_err(ComputeDriverError::Precondition)?; - for control_path in PODMAN_WORKLOAD_CONTROL_PATHS { - driver_mounts::validate_workspace_control_path(&workspace_root, control_path) - .map_err(ComputeDriverError::Precondition)?; - } - if workspace_root != driver_mounts::DEFAULT_WORKSPACE_ROOT - && let Some(volumes) = config.volumes.as_ref() - { - for volume in volumes.keys() { - validate_container_mount_target(volume).map_err(|error| { - ComputeDriverError::Precondition(format!( - "invalid image-declared volume '{volume}': {error}" - )) - })?; - driver_mounts::validate_workspace_mount_target(volume, &workspace_root).map_err( - |_| { - ComputeDriverError::Precondition(format!( - "image-declared volume '{volume}' masks OCI WorkingDir '{workspace_root}' before workspace validation" - )) - }, - )?; - } - } - Ok(Self { - requested_image: requested_image.to_string(), - id: inspected.id, - oci_user: config.user, - environment: config.env, - workspace_root, - }) - } - - /// Test fixture without inspected metadata; uses the managed workspace. - #[cfg(test)] - fn new(image: &str) -> Self { - Self::from_inspect( - image, - ImageInspect { - id: image.to_string(), - config: None, - }, - ) - .expect("fixture image metadata should be valid") - } - - pub(crate) fn uses_managed_workspace(&self) -> bool { - self.workspace_root == driver_mounts::DEFAULT_WORKSPACE_ROOT - } - - fn managed_workspace_volume(&self, sandbox_id: &str) -> Option { - self.uses_managed_workspace().then(|| NamedVolume { - name: volume_name(sandbox_id), - dest: self.workspace_root.clone(), - options: vec!["rw".into()], - }) - } -} - -// --------------------------------------------------------------------------- -// Typed container spec structs for the Podman libpod create API. -// --------------------------------------------------------------------------- - -#[derive(Serialize)] -pub struct ContainerSpec { - name: String, - image: String, - labels: BTreeMap, - env: BTreeMap, - volumes: Vec, - image_volumes: Vec, - hostname: String, - /// Start trusted runtime binaries from `/` instead of the image - /// `WORKDIR`, so Podman neither creates a missing workdir nor fails to - /// `chdir` before `OpenShell` validates it. Children use the resolved - /// workspace. - work_dir: String, - /// Overrides the image's ENTRYPOINT. In Podman's libpod API, `command` - /// only overrides CMD (appended as args to the entrypoint). We must set - /// `entrypoint` explicitly so the supervisor binary runs directly, - /// regardless of what ENTRYPOINT the sandbox image defines. - entrypoint: Vec, - command: Vec, - user: String, - #[serde(skip_serializing_if = "Vec::is_empty")] - groups: Vec, - #[serde(skip_serializing_if = "Vec::is_empty")] - unsetenv: Vec, - cap_drop: Vec, - cap_add: Vec, - no_new_privileges: bool, - #[serde(skip_serializing_if = "Option::is_none")] - apparmor_profile: Option, - #[serde(skip_serializing_if = "String::is_empty")] - seccomp_profile_path: String, - #[serde(skip_serializing_if = "BTreeMap::is_empty")] - sysctl: BTreeMap, - image_pull_policy: String, - healthconfig: HealthConfig, - resource_limits: ResourceLimits, - /// Env-type secrets: map of `ENV_VAR_NAME → secret_name`. - /// Podman's libpod `SpecGenerator` uses `secret_env` (a flat map) for - /// environment-variable injection, distinct from `secrets` which only - /// handles file-mounted secrets under `/run/secrets/`. - secret_env: BTreeMap, - /// File-mounted Podman secrets. - secrets: Vec, - stop_timeout: u32, - /// Extra /etc/hosts entries for the networked supervisor container. - /// The isolated workload resolves host aliases through policy DNS. - /// Native restart stays disabled; the gateway owns sandbox restart policy. - restart_policy: String, - /// Extra /etc/hosts entries. Used to inject `host.containers.internal` - /// via Podman's `host-gateway` magic so sandbox containers can reach - /// the gateway server running on the host in rootless mode. - hostadd: Vec, - /// Search domains written to `/etc/resolv.conf` by Podman. - dns_search: Vec, - /// Resolver options written to `/etc/resolv.conf` by Podman. - dns_option: Vec, - /// Preserve the image resolver path so a driver-owned read-only resolver - /// file can be mounted there without Podman replacing it. - #[serde(skip_serializing_if = "Option::is_none")] - use_image_resolve_conf: Option, - netns: NetNS, - // Matches libpod's network spec format, which is `{name: {opts}}` where - // empty opts is a unit struct rather than `()`. Keep as a map so JSON - // serialization matches the API exactly. - #[allow(clippy::zero_sized_map_values)] - networks: BTreeMap, - #[serde(skip_serializing_if = "Option::is_none")] - devices: Option>, - /// Extra mounts for the libpod `SpecGenerator` (e.g. tmpfs entries). - mounts: Vec, - /// Port mappings from host to container. Using `host_port=0` requests an - /// ephemeral port, readable back from the inspect response. - portmappings: Vec, - /// User namespace mode override (e.g. `auto`). - #[serde(skip_serializing_if = "Option::is_none")] - userns: Option, - /// UID/GID mapping options. Required for `userns = "auto"` — the Podman - /// API needs `AutoUserNs: true` alongside the namespace mode. - #[serde(skip_serializing_if = "Option::is_none")] - idmappings: Option, -} - -/// A port mapping entry for the libpod `SpecGenerator`. -#[derive(Serialize)] -struct PortMapping { - host_port: u16, - container_port: u16, - protocol: String, -} - -/// A mount entry for the libpod container create API `mounts` field. -/// -/// Unlike `volumes` (named Podman volumes) or `image_volumes` (OCI image -/// mounts resolved at the libpod layer), these mounts are passed to the -/// libpod `SpecGenerator` and support arbitrary mount types (e.g. tmpfs). -/// Field names must be lowercase to match the libpod JSON schema. -#[derive(Serialize)] -struct Mount { - #[serde(rename = "type")] - kind: String, - source: String, - destination: String, - #[serde(skip_serializing_if = "Vec::is_empty")] - options: Vec, -} - -/// A Podman image volume for the libpod container create API. -/// -/// Image volumes mount an OCI image's filesystem into a container without -/// running it. Podman resolves these at the libpod layer before generating -/// the OCI runtime spec, unlike `mounts` which are passed directly to the -/// OCI runtime (crun/runc). -#[derive(Serialize)] -struct ImageVolume { - source: String, - destination: String, - rw: bool, -} - -#[derive(Serialize)] -struct NamedVolume { - name: String, - dest: String, - options: Vec, -} - -#[derive(Default)] -struct PodmanUserMounts { - volumes: Vec, - image_volumes: Vec, - mounts: Vec, -} - -impl PodmanUserMounts { - fn targets(&self) -> impl Iterator { - self.mounts - .iter() - .map(|mount| mount.destination.as_str()) - .chain(self.volumes.iter().map(|volume| volume.dest.as_str())) - .chain( - self.image_volumes - .iter() - .map(|volume| volume.destination.as_str()), - ) - } -} - -#[derive(Serialize)] -struct HealthConfig { - test: Vec, - #[serde(rename = "Interval")] - interval: u64, - #[serde(rename = "Timeout")] - timeout: u64, - #[serde(rename = "Retries")] - retries: u32, - #[serde(rename = "StartPeriod")] - start_period: u64, -} - -#[derive(Serialize)] -struct SecretMount { - source: String, - target: String, - uid: u32, - gid: u32, - mode: u32, -} - -#[derive(Serialize)] -struct ResourceLimits { - cpu: CpuLimits, - memory: MemoryLimits, - #[serde(skip_serializing_if = "Option::is_none")] - pids: Option, -} - -#[derive(Serialize)] -struct PidsLimits { - limit: i64, -} - -#[derive(Serialize)] -struct CpuLimits { - quota: u64, - period: u64, -} - -#[derive(Serialize)] -struct MemoryLimits { - limit: u64, -} - -#[derive(Serialize)] -struct NetNS { - nsmode: String, -} - -#[derive(Serialize)] -struct UserNS { - nsmode: String, - #[serde(skip_serializing_if = "Option::is_none")] - value: Option, -} - -#[derive(Serialize)] -struct IDMap { - container_id: u32, - host_id: u32, - size: u32, -} - -#[derive(Serialize)] -struct IDMappings { - #[serde(rename = "HostUIDMapping")] - host_uid_mapping: bool, - #[serde(rename = "HostGIDMapping")] - host_gid_mapping: bool, - #[serde(rename = "AutoUserNs")] - auto_user_ns: bool, - #[serde(rename = "UIDMap", skip_serializing_if = "Vec::is_empty")] - uid_map: Vec, - #[serde(rename = "GIDMap", skip_serializing_if = "Vec::is_empty")] - gid_map: Vec, -} - -fn parse_id_maps(entries: &[String]) -> Result, ComputeDriverError> { - entries - .iter() - .map(|entry| { - let (cid, hid, size) = crate::config::parse_id_map_entry("idmap", entry) - .map_err(|err| ComputeDriverError::Precondition(err.to_string()))?; - Ok(IDMap { - container_id: cid, - host_id: hid, - size, - }) - }) - .collect() -} - -#[derive(Serialize)] -struct NetworkAttachment {} - -#[derive(Serialize)] -struct LinuxDevice { - path: String, -} - -/// Default limits: 2 CPU cores (200000µs quota / 100000µs period), 4 GiB memory. -const DEFAULT_CPU_QUOTA: u64 = 200_000; -const DEFAULT_CPU_PERIOD: u64 = 100_000; -const DEFAULT_MEMORY_LIMIT: u64 = 4_294_967_296; // 4 GiB - -/// Resolve the OCI image reference for a sandbox, using the template image -/// if provided, otherwise the driver's default image. -#[must_use] -pub fn resolve_image<'a>(sandbox: &'a DriverSandbox, config: &'a PodmanComputeConfig) -> &'a str { - let spec = sandbox.spec.as_ref(); - let template = spec.and_then(|s| s.template.as_ref()); - template - .map(|t| t.image.as_str()) - .filter(|s| !s.is_empty()) - .unwrap_or(&config.default_image) -} - -/// Merge environment variables from user spec/template with required driver vars. -/// -/// User-supplied vars are inserted first so that the required driver -/// vars always win -- preventing spec/template overrides of security- -/// critical values like `OPENSHELL_ENDPOINT` or `OPENSHELL_SANDBOX_ID`. -/// Build the corporate upstream-proxy command-line arguments passed to the -/// supervisor. -/// -/// This operator-owned egress boundary travels on argv, which sandbox -/// spec/template environment and image `ENV` cannot influence. Credentials -/// are never on argv — only the root-only mount path is passed; the -/// supervisor reads the secret from the mount. -fn upstream_proxy_cli_args(config: &PodmanComputeConfig) -> Vec { - let mut args = Vec::new(); - if let Some(url) = &config.https_proxy { - args.push("--upstream-proxy".to_string()); - args.push(url.clone()); - } - if let Some(list) = &config.no_proxy { - args.push("--upstream-no-proxy".to_string()); - args.push(list.clone()); - } - if config.proxy_auth_file.is_some() { - args.push("--upstream-proxy-auth-file".to_string()); - args.push(UPSTREAM_PROXY_AUTH_MOUNT_PATH.to_string()); - } - // Config validation guarantees the acknowledgement is `true` whenever an - // auth file is configured; the supervisor independently refuses - // credentials without it. - if config.proxy_auth_allow_insecure == Some(true) { - args.push("--upstream-proxy-auth-allow-insecure".to_string()); - } - // Absent means the default validated-IP CONNECT binding; only the - // explicit hostname opt-in is passed through. - if config.proxy_connect_by_hostname == Some(true) { - args.push("--upstream-proxy-connect-by-hostname".to_string()); - } - // A CA certificate is not secret, so the host PEM is bind-mounted - // read-only and the container-side mount path is passed on argv. - if config.proxy_ca_bundle.is_some() { - args.push("--upstream-proxy-ca-bundle".to_string()); - args.push(PROXY_CA_MOUNT_PATH.to_string()); - } - args -} - -/// Build the destination-trust arguments for the trusted supervisor only. -/// -/// The source path stays out of argv; the digest pairs the mounted artifact -/// with the immutable generation recorded on the workload label. -fn network_trust_cli_args(network_trust: Option<&NetworkSupervisorTrustBundle>) -> Vec { - network_trust.map_or_else(Vec::new, |_bundle| { - vec![ - "--additional-ca-bundle".to_string(), - ADDITIONAL_CA_MOUNT_PATH.to_string(), - ] - }) -} - -fn network_trust_mount(bundle: &NetworkSupervisorTrustBundle) -> Result { - bundle.verify_artifact().map_err(|error| { - ComputeDriverError::Precondition(format!( - "verify gateway-owned network additional CA artifact: {error}" - )) - })?; - let path = bundle.artifact_path(); - let source = path.to_str().ok_or_else(|| { - ComputeDriverError::Precondition(format!( - "network additional CA artifact path is not valid UTF-8: {}", - path.display() - )) - })?; - driver_mounts::validate_absolute_mount_source(source, "network additional CA artifact") - .map_err(ComputeDriverError::Precondition)?; - - let mut options = vec!["ro".into(), "rbind".into()]; - if is_selinux_enabled() { - options.push("z".into()); - } - Ok(Mount { - kind: "bind".into(), - source: source.to_string(), - destination: ADDITIONAL_CA_MOUNT_PATH.into(), - options, - }) -} - -fn network_trust_generation(network_trust: Option<&NetworkSupervisorTrustBundle>) -> &str { - network_trust.map_or(NETWORK_SUPERVISOR_TRUST_GENERATION_NONE, |bundle| { - bundle.digest() - }) -} - -fn build_env( - sandbox: &DriverSandbox, - config: &PodmanComputeConfig, - image: &str, - oci_user: &str, -) -> Result, ComputeDriverError> { - let spec = sandbox.spec.as_ref(); - let template = spec.and_then(|s| s.template.as_ref()); - - let mut env: BTreeMap = BTreeMap::new(); - - // 1. User-supplied environment (lowest priority). - // Template vars first, then spec overwrites (spec is user-specified). - let mut user_env: BTreeMap = BTreeMap::new(); - if let Some(t) = template { - for (k, v) in &t.environment { - user_env.insert(k.clone(), v.clone()); - } - } - if let Some(s) = spec { - if !s.log_level.is_empty() { - env.insert( - openshell_core::sandbox_env::LOG_LEVEL.into(), - s.log_level.clone(), - ); - } - for (k, v) in &s.environment { - user_env.insert(k.clone(), v.clone()); - } - } - // User environment belongs exclusively to mediated workload children. In - // particular, never activate loader or policy overrides in the supervisor. - if !user_env.is_empty() { - let json = serde_json::to_string(&user_env) - .map_err(|error| ComputeDriverError::Precondition(error.to_string()))?; - env.insert(openshell_core::sandbox_env::USER_ENVIRONMENT.into(), json); - } - - // 2. Required driver vars (highest priority -- always overwrite). - - // The operator's corporate egress proxy settings are not environment - // variables: they travel on the supervisor's argv (see - // `upstream_proxy_cli_args`), which sandbox spec/template environment - // and image ENV cannot influence. - - env.insert( - openshell_core::sandbox_env::SANDBOX.into(), - sandbox.name.clone(), - ); - env.insert( - openshell_core::sandbox_env::SANDBOX_ID.into(), - sandbox.id.clone(), - ); - env.insert( - openshell_core::sandbox_env::ENDPOINT.into(), - config.grpc_endpoint.clone(), - ); - env.insert( - openshell_core::sandbox_env::SSH_SOCKET_PATH.into(), - config.ssh_socket_path.clone(), - ); - env.insert( - openshell_core::sandbox_env::CONTAINER_IMAGE.into(), - image.to_string(), - ); - let main_process = openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec(spec) - .map_err(|error| ComputeDriverError::Precondition(error.to_string()))?; - env.insert( - openshell_core::sandbox_env::MAIN_PROCESS_SPEC.into(), - main_process, - ); - env.insert( - openshell_core::sandbox_env::TELEMETRY_ENABLED.into(), - openshell_core::telemetry::enabled_env_value().into(), - ); - env.extend( - config - .supervisor_otlp - .environment() - .into_iter() - .map(|(name, value)| (name.to_string(), value)), - ); - if config.supervisor_otlp.traces.is_some() { - env.extend( - openshell_otel::current_trace_context_environment() - .into_iter() - .map(|(name, value)| (name.to_string(), value)), - ); - } - if let Some(name) = &config.supervisor_gateway_name { - env.insert( - openshell_core::sandbox_env::GATEWAY_NAME.into(), - name.clone(), - ); - } - // Runtime capabilities are driver-owned. Override image/user input with - // only the substrate that this driver configures for the supervisor. - env.insert( - openshell_core::sandbox_env::NETWORK_RUNTIME_CAPABILITIES.into(), - openshell_core::sandbox_env::POLICY_DNS_TRANSPARENT_TCP_CAPABILITY.into(), - ); - - // 3. Gateway CA path (when TLS is enabled). - if config.tls_enabled() { - env.insert( - openshell_core::sandbox_env::TLS_CA.into(), - TLS_CA_MOUNT_PATH.into(), - ); - } - - if let Some(socket_path) = provider_spiffe_workload_api_socket_env_value(config) { - env.insert( - openshell_core::sandbox_env::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET.into(), - socket_path, - ); - } - - env.remove(openshell_core::sandbox_env::SANDBOX_TOKEN); - env.remove(openshell_core::sandbox_env::SANDBOX_TOKEN_FILE); - // Prevent user-supplied environment from overriding the TLS server name - // the supervisor verifies — a sandbox user who can redirect the gateway - // hostname could otherwise present a certificate for a name they control - // and intercept the sandbox JWT. - env.remove(openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME); - if oci_user.is_empty() { - // The image declares no OCI USER (for example, a minimal base image). Assign a - // numeric non-root identity like the Kubernetes and VM drivers so the - // supervisor synthesizes the account instead of rejecting the image. - env.insert( - openshell_core::sandbox_env::OCI_IMAGE_USER.into(), - String::new(), - ); - env.insert( - openshell_core::sandbox_env::SANDBOX_UID.into(), - openshell_core::sandbox_env::DEFAULT_SANDBOX_UID.to_string(), - ); - env.insert( - openshell_core::sandbox_env::SANDBOX_GID.into(), - openshell_core::sandbox_env::DEFAULT_SANDBOX_GID.to_string(), - ); - } else { - // The image declares a USER; preserve the OCI resolution path. - env.insert( - openshell_core::sandbox_env::OCI_IMAGE_USER.into(), - oci_user.to_string(), - ); - env.insert( - openshell_core::sandbox_env::SANDBOX_UID.into(), - String::new(), - ); - env.insert( - openshell_core::sandbox_env::SANDBOX_GID.into(), - String::new(), - ); - } - - // 4. Gateway-minted sandbox JWT. Keep the raw bearer out of container - // metadata; the supervisor reads it from a driver-owned bind mount. - if let Some(s) = spec - && !s.sandbox_token.is_empty() - { - env.insert( - openshell_core::sandbox_env::SANDBOX_TOKEN_FILE.into(), - SANDBOX_TOKEN_MOUNT_PATH.into(), - ); - } - - Ok(env) -} - -/// Merge labels from the sandbox template with required managed labels. -/// -/// User-supplied labels are inserted first so that the managed labels -/// always win -- preventing template overrides of internal tracking labels. -fn build_labels(sandbox: &DriverSandbox) -> BTreeMap { - let template = sandbox.spec.as_ref().and_then(|s| s.template.as_ref()); - - let mut labels: BTreeMap = BTreeMap::new(); - if let Some(t) = template { - for (k, v) in &t.labels { - labels.insert(k.clone(), v.clone()); - } - } - // Managed labels (highest priority -- always overwrite). - labels.insert( - openshell_core::resource_admission::CONFIG_USED_LABEL.into(), - template - .and_then(|t| t.driver_config.as_ref()) - .is_some_and(|config| !config.fields.is_empty()) - .to_string(), - ); - labels.insert(LABEL_SANDBOX_ID.into(), sandbox.id.clone()); - labels.insert(LABEL_SANDBOX_NAME.into(), sandbox.name.clone()); - labels.insert(LABEL_SANDBOX_NAMESPACE.into(), sandbox.namespace.clone()); - labels.insert(LABEL_SANDBOX_WORKSPACE.into(), sandbox.workspace.clone()); - labels.insert(LABEL_MANAGED.into(), "true".into()); - - labels -} - -/// Parse resource limits from the sandbox template, falling back to defaults. -fn build_resource_limits(sandbox: &DriverSandbox, config: &PodmanComputeConfig) -> ResourceLimits { - let resources = sandbox - .spec - .as_ref() - .and_then(|s| s.template.as_ref()) - .and_then(|t| t.resources.as_ref()); - - let cpu_micros = resources - .filter(|r| !r.cpu_limit.is_empty()) - .and_then(|r| parse_cpu_to_microseconds(&r.cpu_limit)) - .unwrap_or(DEFAULT_CPU_QUOTA); - - let mem_bytes = resources - .filter(|r| !r.memory_limit.is_empty()) - .and_then(|r| parse_memory_to_bytes(&r.memory_limit)) - .unwrap_or(DEFAULT_MEMORY_LIMIT); - - ResourceLimits { - cpu: CpuLimits { - quota: cpu_micros, - period: DEFAULT_CPU_PERIOD, - }, - memory: MemoryLimits { limit: mem_bytes }, - pids: podman_pids_limit(config.sandbox_pids_limit).map(|limit| PidsLimits { limit }), - } -} - -fn podman_pids_limit(value: Option) -> Option { - value.map(std::num::NonZeroI64::get) -} - -pub fn podman_driver_volume_mount_sources( - sandbox: &DriverSandbox, - enable_bind_mounts: bool, -) -> Result, String> { - let template = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()); - let Some(template) = template else { - return Ok(Vec::new()); - }; - let config = podman_driver_config(template, enable_bind_mounts)?; - Ok(config - .mounts - .into_iter() - .filter_map(|mount| match mount { - PodmanDriverMountConfig::Volume { source, .. } => Some(source), - _ => None, - }) - .collect()) -} - -pub fn podman_driver_image_mount_sources( - sandbox: &DriverSandbox, - enable_bind_mounts: bool, -) -> Result, String> { - let template = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()); - let Some(template) = template else { - return Ok(Vec::new()); - }; - let config = podman_driver_config(template, enable_bind_mounts)?; - Ok(config - .mounts - .into_iter() - .filter_map(|mount| match mount { - PodmanDriverMountConfig::Image { source, .. } => Some(source), - _ => None, - }) - .collect()) -} - -fn podman_user_mounts( - sandbox: &DriverSandbox, - enable_bind_mounts: bool, -) -> Result { - let template = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()); - let Some(template) = template else { - return Ok(PodmanUserMounts::default()); - }; - let config = podman_driver_config(template, enable_bind_mounts)?; - let mut result = PodmanUserMounts::default(); - for mount in config.mounts { - match mount { - PodmanDriverMountConfig::Bind { - source, - target, - read_only, - selinux_label, - } => { - let mut options = vec![ - if read_only { "ro" } else { "rw" }.to_string(), - "rbind".to_string(), - ]; - match selinux_label { - Some(SelinuxLabel::Shared) => options.push("z".to_string()), - Some(SelinuxLabel::Private) => options.push("Z".to_string()), - None => {} - } - driver_mounts::validate_absolute_mount_source(&source, "bind source")?; - driver_mounts::validate_container_mount_target(&target)?; - result.mounts.push(Mount { - kind: "bind".into(), - source, - destination: driver_mounts::normalize_mount_target(&target), - options, - }); - } - PodmanDriverMountConfig::Volume { - source, - target, - read_only, - subpath, - } => { - reject_subpath(subpath.as_deref(), "podman volume mounts")?; - driver_mounts::validate_mount_source(&source, "volume source")?; - driver_mounts::validate_container_mount_target(&target)?; - result.volumes.push(NamedVolume { - name: source, - dest: target, - options: vec![if read_only { "ro" } else { "rw" }.to_string()], - }); - } - PodmanDriverMountConfig::Tmpfs { - target, - options, - size_bytes, - mode, - } => { - let mut options = validate_tmpfs_options(&options)?; - if options.is_empty() { - options.push("rw".to_string()); - } - if let Some(size_bytes) = - validate_optional_positive_integral_i64(size_bytes, "tmpfs size_bytes")? - { - options.push(format!("size={size_bytes}")); - } - if let Some(mode) = validate_optional_nonnegative_integral_i64(mode, "tmpfs mode")? - { - options.push(format!("mode={mode:o}")); - } - driver_mounts::validate_container_mount_target(&target)?; - result.mounts.push(Mount { - kind: "tmpfs".into(), - source: "tmpfs".into(), - destination: target, - options, - }); - } - PodmanDriverMountConfig::Image { - source, - target, - read_only, - subpath, - } => { - reject_subpath(subpath.as_deref(), "podman image mounts")?; - driver_mounts::validate_mount_source(&source, "image source")?; - driver_mounts::validate_container_mount_target(&target)?; - result.image_volumes.push(ImageVolume { - source, - destination: target, - rw: !read_only, - }); - } - } - } - Ok(result) -} - -fn podman_driver_config( - template: &DriverSandboxTemplate, - enable_bind_mounts: bool, -) -> Result { - let Some(config) = template.driver_config.as_ref() else { - return Ok(PodmanSandboxDriverConfig::default()); - }; - let config: PodmanSandboxDriverConfig = proto_struct::from_struct(config) - .map_err(|err| format!("invalid podman driver_config: {err}"))?; - validate_podman_driver_mounts(&config.mounts, enable_bind_mounts)?; - Ok(config) -} - -fn validate_container_mount_target(target: &str) -> Result<(), String> { - driver_mounts::validate_container_mount_target(target)?; - driver_mounts::validate_mount_control_path(target, "/.openshell") -} - -fn validate_podman_driver_mounts( - mounts: &[PodmanDriverMountConfig], - enable_bind_mounts: bool, -) -> Result<(), String> { - let mut targets = HashSet::new(); - for mount in mounts { - let target = match mount { - PodmanDriverMountConfig::Bind { source, target, .. } => { - if !enable_bind_mounts { - return Err( - "podman bind mounts require enable_bind_mounts = true in [openshell.drivers.podman]" - .to_string(), - ); - } - driver_mounts::validate_absolute_mount_source(source, "bind source")?; - target - } - PodmanDriverMountConfig::Volume { - source, - target, - subpath, - .. - } => { - driver_mounts::validate_mount_source(source, "volume source")?; - reject_subpath(subpath.as_deref(), "podman volume mounts")?; - target - } - PodmanDriverMountConfig::Tmpfs { - target, - options, - size_bytes, - mode, - } => { - validate_tmpfs_options(options)?; - validate_optional_positive_integral_i64(*size_bytes, "tmpfs size_bytes")?; - validate_optional_nonnegative_integral_i64(*mode, "tmpfs mode")?; - target - } - PodmanDriverMountConfig::Image { - source, - target, - subpath, - .. - } => { - driver_mounts::validate_mount_source(source, "image source")?; - reject_subpath(subpath.as_deref(), "podman image mounts")?; - target - } - }; - validate_container_mount_target(target)?; - let normalized_target = driver_mounts::normalize_mount_target(target); - if !targets.insert(normalized_target.clone()) { - return Err(format!( - "duplicate podman driver_config mount target '{normalized_target}'" - )); - } - } - Ok(()) -} - -fn reject_subpath(subpath: Option<&str>, mount_type: &str) -> Result<(), String> { - let Some(subpath) = subpath else { - return Ok(()); - }; - driver_mounts::validate_mount_subpath(subpath)?; - Err(format!("{mount_type} do not support subpath")) -} - -fn validate_optional_positive_integral_i64( - value: Option, - field: &str, -) -> Result, String> { - let Some(value) = validate_optional_integral_i64(value, field)? else { - return Ok(None); - }; - if value <= 0 { - return Err(format!("{field} must be positive")); - } - Ok(Some(value)) -} - -fn validate_optional_nonnegative_integral_i64( - value: Option, - field: &str, -) -> Result, String> { - let Some(value) = validate_optional_integral_i64(value, field)? else { - return Ok(None); - }; - if value < 0 { - return Err(format!("{field} must be zero or greater")); - } - Ok(Some(value)) -} - -fn validate_optional_integral_i64(value: Option, field: &str) -> Result, String> { - let Some(value) = value else { - return Ok(None); - }; - if !value.is_finite() || value.fract() != 0.0 { - return Err(format!("{field} must be an integer")); - } - value - .to_string() - .parse::() - .map(Some) - .map_err(|_| format!("{field} must be representable as an i64")) -} - -fn validate_tmpfs_options(options: &[String]) -> Result, String> { - options - .iter() - .map(|option| { - let option = option.trim(); - if option.is_empty() { - return Err("tmpfs options must not contain empty values".to_string()); - } - Ok(option.to_string()) - }) - .collect() -} - -/// Build the Podman container creation JSON spec. -#[cfg(test)] -#[must_use] -pub fn build_container_spec(sandbox: &DriverSandbox, config: &PodmanComputeConfig) -> Value { - try_build_container_spec_with_token(sandbox, config, None) - .expect("container spec should be valid") -} - -#[cfg(test)] -#[must_use] -pub fn build_container_spec_with_token( - sandbox: &DriverSandbox, - config: &PodmanComputeConfig, - token_secret_name: Option<&str>, -) -> Value { - try_build_container_spec_with_token(sandbox, config, token_secret_name) - .expect("container spec should be valid") -} - -#[cfg(test)] -pub fn try_build_container_spec_with_token( - sandbox: &DriverSandbox, - config: &PodmanComputeConfig, - token_secret_name: Option<&str>, -) -> Result { - let driver_config = PodmanSandboxDriverConfig::from_sandbox(sandbox)?; - let gpu_requirements = sandbox - .spec - .as_ref() - .and_then(|spec| driver_gpu_requirements(spec.resource_requirements.as_ref())); - let cdi_devices = if let Some(cdi_devices) = driver_config.cdi_devices.as_ref() { - validate_cdi_gpu_device_request(gpu_requirements, cdi_devices, "driver_config.cdi_devices") - .map_err(ComputeDriverError::InvalidArgument)?; - Some(cdi_devices.as_slice()) - } else { - None - }; - build_container_spec_with_token_and_gpu_devices(sandbox, config, token_secret_name, cdi_devices) -} - -#[cfg(test)] -pub fn build_container_spec_with_token_and_gpu_devices( - sandbox: &DriverSandbox, - config: &PodmanComputeConfig, - token_secret_name: Option<&str>, - gpu_device_ids: Option<&[String]>, -) -> Result { - let image = resolve_image(sandbox, config); - let resolved_image = ResolvedPodmanImage::new(image); - build_container_spec_for_image( - sandbox, - config, - token_secret_name, - gpu_device_ids, - &resolved_image, - None, - None, - ) -} - -#[cfg(test)] -pub fn build_container_spec_for_image( - sandbox: &DriverSandbox, - config: &PodmanComputeConfig, - token_secret_name: Option<&str>, - gpu_device_ids: Option<&[String]>, - image: &ResolvedPodmanImage, - supervisor_bin_path: Option<&Path>, - tls_secret_names: Option<&[String; 1]>, -) -> Result { - serde_json::to_value(build_base_spec( - sandbox, - config, - token_secret_name, - gpu_device_ids, - image, - supervisor_bin_path, - tls_secret_names, - )?) - .map_err(|error| ComputeDriverError::Message(format!("encode Podman spec: {error}"))) -} - -fn build_base_spec( - sandbox: &DriverSandbox, - config: &PodmanComputeConfig, - token_secret_name: Option<&str>, - gpu_device_ids: Option<&[String]>, - image: &ResolvedPodmanImage, - supervisor_bin_path: Option<&Path>, - tls_secret_names: Option<&[String; 1]>, -) -> Result { - if let Some(device_ids) = gpu_device_ids { - validate_cdi_device_names(device_ids, "driver_config.cdi_devices") - .map_err(ComputeDriverError::InvalidArgument)?; - } - let name = container_name(&sandbox.workspace, &sandbox.name, &sandbox.id); - - let env = build_env(sandbox, config, &image.requested_image, &image.oci_user)?; - let mut labels = build_labels(sandbox); - labels.insert( - "openshell.ai/runtime-binary-source".into(), - supervisor_bin_path - .map(|path| path.display().to_string()) - .unwrap_or_default(), - ); - let resource_limits = build_resource_limits(sandbox, config); - let user_mounts = podman_user_mounts(sandbox, config.enable_bind_mounts) - .map_err(ComputeDriverError::InvalidArgument)?; - driver_mounts::validate_workspace_mount_targets( - user_mounts.targets(), - &image.workspace_root, - &["/.openshell"], - ) - .map_err(ComputeDriverError::Precondition)?; - if sandbox - .spec - .as_ref() - .is_some_and(|spec| !spec.sandbox_token.is_empty()) - && token_secret_name.is_none() - { - return Err(ComputeDriverError::Precondition( - "podman sandbox token secret is required when sandbox token is set".to_string(), - )); - } - let devices = gpu_device_ids.map(|device_ids| { - device_ids - .iter() - .cloned() - .map(|path| LinuxDevice { path }) - .collect() - }); - - // The isolation roles override this base network configuration below. - #[allow(clippy::zero_sized_map_values)] - let mut networks = BTreeMap::new(); - networks.insert(config.network_name.clone(), NetworkAttachment {}); - - let mut volumes = image - .managed_workspace_volume(&sandbox.id) - .into_iter() - .collect::>(); - volumes.extend(user_mounts.volumes); - - let mut image_volumes = if supervisor_bin_path.is_some() { - Vec::new() - } else { - vec![ImageVolume { - source: config.sandbox_runtime_image.clone(), - destination: SUPERVISOR_MOUNT_DIR.into(), - rw: false, - }] - }; - image_volumes.extend(user_mounts.image_volumes); - let mut command = vec!["--workdir".to_string(), image.workspace_root.clone()]; - command.extend(upstream_proxy_cli_args(config)); - command.extend(config.ipv6_egress_config().supervisor_args()); - - let container_spec = ContainerSpec { - name, - image: image.id.clone(), - labels, - env, - volumes, - // Side-load the sandbox runtime binary from its standalone OCI image. - // Podman resolves image_volumes at the libpod layer, mounting the - // image's filesystem at the destination path without starting a - // container from it. The sandbox runtime image exposes the binary at - // /openshell-sandbox, so it appears at /opt/openshell/bin/openshell-sandbox. - image_volumes, - hostname: format!("sandbox-{}", sandbox.name), - // This is the runtime's cwd, not the agent's: Podman must not create - // or enter the image workspace before OpenShell validates it as the - // final identity. Agent commands receive that path via --workdir. - work_dir: "/".into(), - // Override the image's ENTRYPOINT so the supervisor binary runs - // directly. Workload images can set - // ENTRYPOINT ["/bin/bash"], and Podman's `command` field only - // overrides CMD — which gets appended as args to the entrypoint. - // Without this, the container would run the entrypoint binary with - // the supervisor path as an argument instead of executing it directly. - entrypoint: vec![SUPERVISOR_BINARY_PATH.into()], - // Pass the resolved workspace to the logical supervisor. Operator-owned - // corporate proxy flags follow it; the workload command comes from the - // reserved environment variable. - command, - // The paired builder supplies the immutable non-root identity. - user: String::new(), - groups: Vec::new(), - unsetenv: Vec::new(), - cap_drop: vec!["ALL".into()], - cap_add: Vec::new(), - no_new_privileges: true, - apparmor_profile: None, - // Omission selects the runtime default, never an unconfined profile. - seccomp_profile_path: String::new(), - sysctl: BTreeMap::new(), - image_pull_policy: "never".to_string(), - healthconfig: HealthConfig { - test: vec![ - "CMD-SHELL".into(), - format!( - "test -e /var/run/openshell-ssh-ready || test -S {} || ss -tlnp | grep -q :{}", - config.ssh_socket_path, - openshell_core::config::DEFAULT_SSH_PORT - ), - ], - interval: config - .health_check_interval_secs - .map_or(10, std::num::NonZeroU64::get) - * 1_000_000_000, - timeout: 2_000_000_000, - retries: 10, - start_period: 5_000_000_000, - }, - resource_limits, - secret_env: BTreeMap::new(), - secrets: { - let mut secrets = Vec::new(); - if let Some(source) = token_secret_name { - secrets.push(SecretMount { - source: source.to_string(), - target: SANDBOX_TOKEN_MOUNT_PATH.into(), - uid: 0, - gid: 0, - mode: 0o400, - }); - } - // Corporate proxy credentials, when configured, are mounted as a - // root-only secret. The driver creates a matching Podman secret - // (see `create_sandbox_proxy_auth_secret`) named deterministically - // from the sandbox id, so no name needs threading through here. - if config.proxy_auth_file.is_some() { - secrets.push(SecretMount { - source: proxy_auth_secret_name(&sandbox.id), - target: UPSTREAM_PROXY_AUTH_MOUNT_PATH.into(), - uid: 0, - gid: 0, - mode: 0o400, - }); - } - if let Some([ca]) = tls_secret_names { - secrets.push(SecretMount { - source: ca.clone(), - target: TLS_CA_MOUNT_PATH.into(), - uid: 0, - gid: 0, - mode: 0o400, - }); - } - secrets - }, - stop_timeout: config.stop_timeout_secs, - // Inject stable host aliases into the networked supervisor container. - // The workload clears these entries and resolves the driver-neutral - // alias through the policy-DNS relay instead. - restart_policy: "no".to_string(), - // Inject stable host aliases into /etc/hosts so sandbox containers can - // reach services on the host. `host.openshell.internal` is the driver- - // neutral alias used by policies and e2e tests. - hostadd: hostadd_entries(config), - // Preserve Podman's resolver defaults for both policy-DNS and ordinary - // sandboxes. Namespace-local capture supports UDP and TCP, so it must - // not depend on a libc-specific option or alter short-name searches. - dns_search: Vec::new(), - dns_option: Vec::new(), - use_image_resolve_conf: None, - netns: NetNS { - nsmode: "bridge".to_string(), - }, - networks, - devices, - // Mount a tmpfs at /run/netns so the sandbox supervisor can create - // named network namespaces via `ip netns add`. The `ip` command requires - // /run/netns to exist and be bind-mountable; in rootless Podman this - // directory does not exist on the host, so the mkdir inside the container - // fails with EPERM. A private tmpfs gives the supervisor its own writable - // /run/netns without needing host filesystem access. - mounts: { - let mut m = vec![Mount { - kind: "tmpfs".into(), - source: "tmpfs".into(), - destination: openshell_core::container_paths::NETNS_MOUNT_ROOT.into(), - options: vec!["rw".into(), "nosuid".into(), "nodev".into()], - }]; - // Deliver the gateway CA into the container when TLS is - // enabled. When userns remaps UIDs (auto, no-map), bind-mounted - // host files are unreadable because the container root maps to a - // different host UID. In that case TLS materials are delivered as - // Podman secrets (handled in the `secrets` block above); otherwise - // use bind mounts. - if tls_secret_names.is_none() - && let Some(ca) = &config.guest_tls_ca - { - let mut ro = vec!["ro".into(), "rbind".into()]; - if is_selinux_enabled() { - ro.push("z".into()); - } - m.push(Mount { - kind: "bind".into(), - source: ca.display().to_string(), - destination: TLS_CA_MOUNT_PATH.into(), - options: ro.clone(), - }); - } - // Bind-mount the corporate proxy CA bundle read-only when - // configured. A CA certificate is not secret, so unlike the proxy - // credential (a driver secret) a plain read-only bind mount is - // used. The supervisor reads it via the --upstream-proxy-ca-bundle - // argv path (see upstream_proxy_cli_args) to verify an https:// - // proxy and trust re-signed upstream certificates. - if let Some(ca_bundle) = &config.proxy_ca_bundle { - let mut ro = vec!["ro".into(), "rbind".into()]; - if is_selinux_enabled() { - ro.push("z".into()); - } - m.push(Mount { - kind: "bind".into(), - source: ca_bundle.clone(), - destination: PROXY_CA_MOUNT_PATH.into(), - options: ro, - }); - } - if let Some(bin_path) = supervisor_bin_path { - let mut opts = vec!["ro".into(), "rbind".into()]; - if is_selinux_enabled() { - opts.push("z".into()); - } - m.push(Mount { - kind: "bind".into(), - source: bin_path.display().to_string(), - destination: SUPERVISOR_BINARY_PATH.into(), - options: opts, - }); - } - if let Some(path) = provider_spiffe_workload_api_socket_mount_source(config) { - // No SELinux relabel - the SPIRE agent socket is shared host - // infrastructure and must keep its existing SELinux context. - let ro = vec!["ro".into(), "rbind".into()]; - m.push(Mount { - kind: "bind".into(), - source: path.display().to_string(), - destination: PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR.into(), - options: ro, - }); - } - m.extend(user_mounts.mounts); - m - }, - // Publish the SSH port with host_port=0 to get an ephemeral host port. - // In rootless Podman the bridge network (10.89.x.x) is not routable from - // the host, so we must use the published host port on 127.0.0.1 instead. - portmappings: vec![PortMapping { - host_port: 0, - container_port: openshell_core::config::DEFAULT_SSH_PORT, - protocol: "tcp".into(), - }], - userns: config.userns.as_deref().map(|raw| { - let (base, params) = raw - .split_once(':') - .map_or((raw, None), |(b, p)| (b, Some(p))); - UserNS { - nsmode: base.to_string(), - value: params.map(ToString::to_string), - } - }), - idmappings: match config - .userns - .as_deref() - .map(|m| m.split(':').next().unwrap_or(m)) - { - Some("auto") => Some(IDMappings { - host_uid_mapping: false, - host_gid_mapping: false, - auto_user_ns: true, - uid_map: Vec::new(), - gid_map: Vec::new(), - }), - Some("private") => Some(IDMappings { - host_uid_mapping: false, - host_gid_mapping: false, - auto_user_ns: false, - uid_map: parse_id_maps(&config.uidmap)?, - gid_map: parse_id_maps(&config.gidmap)?, - }), - _ => None, - }, - }; - - Ok(container_spec) -} - -/// Driver-owned inputs for the two independent runtime containers. -pub struct IsolationSpecInput<'a> { - pub sandbox: &'a DriverSandbox, - pub config: &'a PodmanComputeConfig, - pub token_secret: Option<&'a str>, - pub resolver_secret: &'a str, - pub gpu_devices: Option<&'a [String]>, - pub image: &'a ResolvedPodmanImage, - pub supervisor_bin: Option<&'a Path>, - pub tls_secrets: Option<&'a [String; 1]>, - /// Gateway-owned immutable destination-trust artifact. It is deliberately - /// mounted only into the trusted supervisor spec. - pub network_trust: Option<&'a NetworkSupervisorTrustBundle>, - pub identity: &'a openshell_isolation_interface::contract::ResolvedWorkloadIdentity, -} - -pub struct IsolationSpecs { - pub workload: ContainerSpec, - pub supervisor: ContainerSpec, -} - -impl IsolationSpecs { - pub(crate) fn record_resource_identities( - &mut self, - identities: &BTreeMap, - ) -> Result<(), ComputeDriverError> { - self.workload.labels.insert( - openshell_core::resource_admission::IDENTITIES_LABEL.into(), - serde_json::to_string(identities) - .map_err(|error| ComputeDriverError::Message(error.to_string()))?, - ); - Ok(()) - } -} - -pub fn build_isolation_specs( - input: IsolationSpecInput<'_>, -) -> Result { - let base = || { - build_base_spec( - input.sandbox, - input.config, - input.token_secret, - input.gpu_devices, - input.image, - input.supervisor_bin, - input.tls_secrets, - ) - }; - let mut workload = base()?; - let mut supervisor = base()?; - let user = format!("{}:{}", input.identity.uid, input.identity.gid); - let channel = crate::isolation::channel_volume_name(&input.sandbox.id); - - workload - .labels - .insert(crate::isolation::LABEL_ROLE.into(), "sandbox".into()); - workload.env = BTreeMap::new(); - workload.unsetenv = input - .image - .environment - .iter() - .filter_map(|entry| entry.split_once('=').map(|(key, _)| key.to_string())) - .collect(); - workload.command = vec![ - "--bootstrap".into(), - crate::isolation::BOOTSTRAP_PATH.into(), - ]; - workload.user.clone_from(&user); - workload.groups = input - .identity - .supplementary_gids - .iter() - .map(ToString::to_string) - .collect(); - workload.cap_drop = vec!["ALL".into()]; - workload.cap_add.clear(); - workload.apparmor_profile = input - .config - .app_armor_profile - .as_ref() - .and_then(openshell_core::config::AppArmorProfile::oci_security_opt) - .and_then(|option| option.strip_prefix("apparmor=").map(str::to_string)); - workload.seccomp_profile_path.clear(); - workload - .sysctl - .insert("net.ipv4.ip_unprivileged_port_start".into(), "0".into()); - workload.netns.nsmode = "none".into(); - workload.networks.clear(); - workload.portmappings.clear(); - workload.hostadd.clear(); - workload.secret_env.clear(); - workload.secrets.clear(); - workload.secrets.push(SecretMount { - source: input.resolver_secret.to_string(), - target: RESOLV_CONF_PATH.into(), - uid: 0, - gid: 0, - mode: 0o444, - }); - workload.use_image_resolve_conf = Some(true); - workload.healthconfig.test = vec!["NONE".into()]; - workload - .mounts - .retain(|mount| !trusted_mount(&mount.destination)); - workload.mounts.push(Mount { - kind: "tmpfs".into(), - source: "tmpfs".into(), - destination: openshell_sandbox_backend::SUPERVISOR_CA_RUNTIME_ROOT.into(), - options: vec![ - "rw".into(), - "noexec".into(), - "nosuid".into(), - "nodev".into(), - // Libpod's OCI `mounts` API rejects tmpfs uid/gid options. The - // unprivileged runtime creates the owned material subdirectory. - "mode=0777".into(), - "size=1m".into(), - ], - }); - workload.volumes.push(NamedVolume { - name: channel.clone(), - dest: crate::isolation::CHANNEL_ROOT.into(), - options: vec!["rw".into(), "z".into()], - }); - - workload.volumes.push(NamedVolume { - name: crate::isolation::control_volume_name(&input.sandbox.id), - dest: crate::isolation::CONTROL_ROOT.into(), - options: vec!["rw".into(), "z".into()], - }); - - supervisor.name = crate::isolation::supervisor_name(&input.sandbox.id); - supervisor - .labels - .insert(crate::isolation::LABEL_ROLE.into(), "supervisor".into()); - // The workload is never replaced when the destination-trust bundle - // changes; only this supervisor is. Record the generation it was created - // with so a later start can detect a stale supervisor and recreate it - // without touching the workload or its data. - supervisor.labels.insert( - NETWORK_SUPERVISOR_TRUST_GENERATION_KEY.into(), - network_trust_generation(input.network_trust).into(), - ); - supervisor.image.clone_from(&input.config.supervisor_image); - supervisor.env.insert( - openshell_core::sandbox_env::CONTAINER_IMAGE_UID.into(), - input.image.id.clone(), - ); - supervisor.entrypoint = vec!["/openshell-supervisor".into()]; - supervisor.command.extend([ - format!( - "--backend-descriptor-file={}", - crate::isolation::RUNTIME_DESCRIPTOR_PATH - ), - format!("--auth-bundle-file={}", crate::isolation::AUTH_BUNDLE_PATH), - "--health-socket-path=/run/openshell/supervisor-health.sock".into(), - ]); - supervisor - .command - .extend(network_trust_cli_args(input.network_trust)); - if let Some(network_trust) = input.network_trust { - supervisor.mounts.push(network_trust_mount(network_trust)?); - } - supervisor.env.insert( - openshell_core::sandbox_env::ADMITTED_ISOLATION_BACKEND.into(), - openshell_sandbox_backend::BACKEND_NAME.into(), - ); - // The supervisor runs as the resolved non-root workload identity. Keep - // generated interception CA material under its writable /run tmpfs rather - // than the root-owned default at /etc/openshell-tls. - supervisor.env.insert( - openshell_core::sandbox_env::PROXY_TLS_DIR.into(), - "/run/openshell/proxy-tls".into(), - ); - supervisor.user = user; - supervisor.groups = input - .identity - .supplementary_gids - .iter() - .map(ToString::to_string) - .collect(); - supervisor.cap_drop = vec!["ALL".into()]; - supervisor.cap_add.clear(); - supervisor.seccomp_profile_path.clear(); - // The trusted supervisor originates approved egress from the Podman host - // network. Keep it in the caller's user namespace as well: joining the - // workload's user namespace is incompatible with host networking under - // rootless Podman, and the authenticated channel does not require a shared - // user namespace. The workload remains fenced by network=none. - supervisor.userns = Some(UserNS { - nsmode: "host".into(), - value: None, - }); - supervisor.idmappings = None; - supervisor.netns.nsmode = "host".into(); - supervisor.networks.clear(); - supervisor.portmappings.clear(); - supervisor.devices = None; - supervisor.image_volumes.clear(); - supervisor.volumes = vec![NamedVolume { - name: channel, - dest: crate::isolation::CHANNEL_ROOT.into(), - options: vec!["ro".into(), "z".into()], - }]; - supervisor.volumes.push(NamedVolume { - name: crate::isolation::control_volume_name(&input.sandbox.id), - dest: crate::isolation::CONTROL_ROOT.into(), - options: vec!["rw".into(), "z".into()], - }); - supervisor.mounts.retain(|mount| { - trusted_mount(&mount.destination) - && mount.destination != openshell_core::container_paths::NETNS_MOUNT_ROOT - }); - for destination in ["/run", "/var/log", "/tmp"] { - supervisor.mounts.push(Mount { - kind: "tmpfs".into(), - source: "tmpfs".into(), - destination: destination.into(), - options: vec![ - "rw".into(), - "noexec".into(), - "nosuid".into(), - "nodev".into(), - "mode=0777".into(), - "size=64m".into(), - ], - }); - } - for secret in &mut supervisor.secrets { - secret.uid = input.identity.uid; - secret.gid = input.identity.gid; - } - if let Some(interval) = input.config.health_check_interval_secs { - supervisor.healthconfig.test = vec![ - "CMD".into(), - "/openshell-supervisor".into(), - "health".into(), - "--socket".into(), - "/run/openshell/supervisor-health.sock".into(), - ]; - supervisor.healthconfig.interval = interval.get() * 1_000_000_000; - } else { - supervisor.healthconfig.test = vec!["NONE".into()]; - } - Ok(IsolationSpecs { - workload, - supervisor, - }) -} - -fn trusted_mount(destination: &str) -> bool { - matches!( - destination, - TLS_CA_MOUNT_PATH - | PROXY_CA_MOUNT_PATH - | ADDITIONAL_CA_MOUNT_PATH - | PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR - ) || destination == openshell_core::container_paths::NETNS_MOUNT_ROOT -} - -fn provider_spiffe_workload_api_socket_env_value(config: &PodmanComputeConfig) -> Option { - let host_path = config.provider_spiffe_workload_api_socket.as_ref()?; - let raw = host_path.to_str()?; - if raw.starts_with("tcp:") { - return Some(raw.to_string()); - } - let host_path = raw - .strip_prefix("unix:") - .map_or(host_path.as_path(), Path::new); - let file_name = host_path.file_name()?.to_str()?; - Some(format!( - "{PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR}/{file_name}" - )) -} - -fn provider_spiffe_workload_api_socket_mount_source(config: &PodmanComputeConfig) -> Option<&Path> { - let host_path = config.provider_spiffe_workload_api_socket.as_ref()?; - let raw = host_path.to_str()?; - if raw.starts_with("tcp:") { - return None; - } - let host_path = raw - .strip_prefix("unix:") - .map_or(host_path.as_path(), Path::new); - host_path.parent() -} - -fn hostadd_entries(config: &PodmanComputeConfig) -> Vec { - let host_gateway_ip = config.host_gateway_ip.trim(); - if host_gateway_ip.is_empty() { - return vec![ - "host.containers.internal:host-gateway".into(), - "host.openshell.internal:host-gateway".into(), - ]; - } - - vec![ - format!("host.containers.internal:{host_gateway_ip}"), - format!("host.openshell.internal:{host_gateway_ip}"), - ] -} - -/// Parse a Kubernetes-style CPU quantity to cgroup quota microseconds -/// (for a 100ms period). -/// -/// Examples: `"500m"` → 50000, `"2"` → 200000, `"0.5"` → 50000. -fn parse_cpu_to_microseconds(quantity: &str) -> Option { - let micros = if let Some(millis_str) = quantity.strip_suffix('m') { - let millis: u64 = millis_str.parse().ok()?; - // quota = millis * period / 1000 - millis.checked_mul(100)? - } else { - let cores: f64 = quantity.parse().ok()?; - if cores <= 0.0 || cores.is_nan() || cores.is_infinite() { - return None; - } - #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] - let val = (cores * 100_000.0) as u64; - val - }; - // A quota of 0 microseconds is invalid — treat as no limit. - if micros == 0 { None } else { Some(micros) } -} - -/// Parse a Kubernetes-style memory quantity to bytes. -/// -/// Supports: `Ki`, `Mi`, `Gi`, `Ti` (binary) and `k`, `M`, `G`, `T` -/// (decimal), as well as plain byte values. -fn parse_memory_to_bytes(quantity: &str) -> Option { - let suffixes: &[(&str, u64)] = &[ - ("Ei", 1024 * 1024 * 1024 * 1024 * 1024 * 1024), - ("Pi", 1024 * 1024 * 1024 * 1024 * 1024), - ("Ti", 1024 * 1024 * 1024 * 1024), - ("Gi", 1024 * 1024 * 1024), - ("Mi", 1024 * 1024), - ("Ki", 1024), - ("E", 1_000_000_000_000_000_000), - ("P", 1_000_000_000_000_000), - ("T", 1_000_000_000_000), - ("G", 1_000_000_000), - ("M", 1_000_000), - ("K", 1_000), - ("k", 1_000), - ]; - - for (suffix, multiplier) in suffixes { - if let Some(num_str) = quantity.strip_suffix(suffix) { - let num: u64 = num_str.parse().ok()?; - return num.checked_mul(*multiplier); - } - } - - // Plain bytes. - quantity.parse().ok() -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::client::ImageConfig; - use openshell_core::proto::compute::v1::{GpuResourceRequirements, ResourceRequirements}; - - static ENV_LOCK: std::sync::LazyLock> = - std::sync::LazyLock::new(|| std::sync::Mutex::new(())); - - fn resolved_image( - requested_image: &str, - id: &str, - user: &str, - working_dir: &str, - ) -> ResolvedPodmanImage { - ResolvedPodmanImage::from_inspect( - requested_image, - ImageInspect { - id: id.to_string(), - config: Some(ImageConfig { - user: user.to_string(), - working_dir: working_dir.to_string(), - ..Default::default() - }), - }, - ) - .expect("fixture image metadata should be valid") - } - - #[test] - fn additional_destination_trust_is_delivered_only_to_supervisor_with_digest() { - let artifact = crate::test_utils::unique_socket_path("additional-ca").with_extension("crt"); - let pem = b"normalized additional CA fixture"; - std::fs::write(&artifact, pem).unwrap(); - #[cfg(unix)] - std::fs::set_permissions( - &artifact, - std::os::unix::fs::PermissionsExt::from_mode(0o444), - ) - .unwrap(); - let bundle = NetworkSupervisorTrustBundle::new( - pem.to_vec(), - 1, - "sha256:paired-digest", - artifact.clone(), - ); - let sandbox = DriverSandbox { - id: "trust-pair".into(), - name: "trust-pair".into(), - ..Default::default() - }; - let identity = openshell_isolation_interface::contract::ResolvedWorkloadIdentity::new( - 1000, - 1001, - Vec::new(), - "image".into(), - "sha256:image".into(), - ) - .unwrap(); - let image = resolved_image("image", "sha256:image", "1000:1001", "/workspace/project"); - let specs = build_isolation_specs(IsolationSpecInput { - sandbox: &sandbox, - config: &PodmanComputeConfig::default(), - token_secret: None, - resolver_secret: "resolver", - gpu_devices: None, - image: &image, - supervisor_bin: None, - tls_secrets: None, - network_trust: Some(&bundle), - identity: &identity, - }) - .unwrap(); - - assert_eq!( - specs - .supervisor - .labels - .get(NETWORK_SUPERVISOR_TRUST_GENERATION_KEY) - .map(String::as_str), - Some("sha256:paired-digest") - ); - assert!( - specs - .workload - .command - .iter() - .all(|argument| argument != "--additional-ca-bundle") - ); - assert!( - specs - .workload - .mounts - .iter() - .all(|mount| { mount.destination != ADDITIONAL_CA_MOUNT_PATH }) - ); - assert!(specs.supervisor.command.windows(2).any(|arguments| { - arguments == ["--additional-ca-bundle", ADDITIONAL_CA_MOUNT_PATH] - })); - assert!(specs.supervisor.mounts.iter().any(|mount| { - mount.destination == ADDITIONAL_CA_MOUNT_PATH - && mount.source == artifact.to_string_lossy() - && mount.options.iter().any(|option| option == "ro") - })); - let _ = std::fs::remove_file(artifact); - } - - #[test] - fn tampered_destination_trust_artifact_fails_closed_without_pem_contents() { - let artifact = - crate::test_utils::unique_socket_path("tampered-additional-ca").with_extension("crt"); - std::fs::write(&artifact, b"expected").unwrap(); - #[cfg(unix)] - std::fs::set_permissions( - &artifact, - std::os::unix::fs::PermissionsExt::from_mode(0o444), - ) - .unwrap(); - let bundle = NetworkSupervisorTrustBundle::new( - b"expected".to_vec(), - 1, - "sha256:expected", - artifact.clone(), - ); - std::fs::remove_file(&artifact).unwrap(); - std::fs::write(&artifact, b"BEGIN CERTIFICATE tampered contents").unwrap(); - #[cfg(unix)] - std::fs::set_permissions( - &artifact, - std::os::unix::fs::PermissionsExt::from_mode(0o444), - ) - .unwrap(); - - let Err(error) = network_trust_mount(&bundle) else { - panic!("tampering must fail closed"); - }; - assert!( - error - .to_string() - .contains("gateway-owned network additional CA artifact") - ); - assert!(!error.to_string().contains("tampered contents")); - let _ = std::fs::remove_file(artifact); - } - - #[test] - fn isolated_pair_keeps_privileges_network_and_secrets_out_of_workload() { - let sandbox = DriverSandbox { - id: "pair".into(), - name: "agent".into(), - ..Default::default() - }; - let mut config = PodmanComputeConfig::default(); - config.app_armor_profile = Some(openshell_core::config::AppArmorProfile::Localhost( - "openshell-sandbox".into(), - )); - config.userns = Some("auto".into()); - let identity = openshell_isolation_interface::contract::ResolvedWorkloadIdentity::new( - 1000, - 1001, - vec![2000], - "image".into(), - "sha256:image".into(), - ) - .unwrap(); - let mut image = resolved_image("image:latest", "sha256:image", "1000:1001", ""); - image.environment = vec![ - "LD_PRELOAD=/hostile.so".into(), - "HTTP_PROXY=http://bypass".into(), - ]; - let specs = build_isolation_specs(IsolationSpecInput { - sandbox: &sandbox, - config: &config, - token_secret: Some("jwt"), - resolver_secret: "resolver", - gpu_devices: None, - image: &image, - supervisor_bin: None, - tls_secrets: None, - network_trust: None, - identity: &identity, - }) - .unwrap(); - for spec in [&specs.workload, &specs.supervisor] { - assert_eq!(spec.cap_drop, vec!["ALL"]); - assert!(spec.seccomp_profile_path.is_empty()); - assert!(spec.no_new_privileges); - } - // The driver creates the managed workspace volume owned by the - // workload identity, so the workload never starts as root. - assert_eq!(specs.workload.user, "1000:1001"); - assert_eq!(specs.workload.groups, vec!["2000"]); - assert!(specs.workload.cap_add.is_empty()); - assert_eq!( - specs.workload.command, - vec!["--bootstrap", crate::isolation::BOOTSTRAP_PATH] - ); - assert_eq!(specs.supervisor.user, "1000:1001"); - assert_eq!( - specs - .supervisor - .env - .get(openshell_core::sandbox_env::CONTAINER_IMAGE_UID) - .map(String::as_str), - Some("sha256:image") - ); - assert_eq!( - specs - .supervisor - .env - .get(openshell_core::sandbox_env::CONTAINER_IMAGE) - .map(String::as_str), - Some("image:latest") - ); - assert!( - !specs - .workload - .env - .contains_key(openshell_core::sandbox_env::CONTAINER_IMAGE_UID) - ); - assert_eq!(specs.supervisor.groups, vec!["2000"]); - assert!(specs.supervisor.cap_add.is_empty()); - assert_eq!(specs.workload.netns.nsmode, "none"); - assert_eq!( - specs - .supervisor - .labels - .get(NETWORK_SUPERVISOR_TRUST_GENERATION_KEY) - .map(String::as_str), - Some(NETWORK_SUPERVISOR_TRUST_GENERATION_NONE) - ); - assert_eq!( - specs - .workload - .userns - .as_ref() - .map(|userns| userns.nsmode.as_str()), - Some("auto") - ); - assert_eq!( - specs.workload.apparmor_profile.as_deref(), - Some("openshell-sandbox") - ); - assert_eq!(specs.supervisor.apparmor_profile, None); - - let default_identity = - openshell_isolation_interface::contract::ResolvedWorkloadIdentity::new( - 1000, - 1000, - Vec::new(), - "default".into(), - "sha256:image".into(), - ) - .unwrap(); - let default_specs = build_isolation_specs(IsolationSpecInput { - sandbox: &sandbox, - config: &config, - token_secret: Some("jwt"), - resolver_secret: "resolver", - gpu_devices: None, - image: &ResolvedPodmanImage::new("sha256:image"), - supervisor_bin: None, - tls_secrets: None, - network_trust: None, - identity: &default_identity, - }) - .unwrap(); - assert_eq!(default_specs.workload.user, "1000:1000"); - assert!(default_specs.workload.cap_add.is_empty()); - assert_eq!( - default_specs.workload.command, - vec!["--bootstrap", crate::isolation::BOOTSTRAP_PATH] - ); - let workload_json = serde_json::to_string(&specs.workload).unwrap(); - assert!(workload_json.contains("\"apparmor_profile\":\"openshell-sandbox\"")); - assert_eq!(specs.supervisor.healthconfig.test, vec!["NONE"]); - assert!(specs.workload.networks.is_empty()); - assert!(specs.workload.portmappings.is_empty()); - assert_eq!(specs.supervisor.netns.nsmode, "host"); - assert_eq!( - specs - .supervisor - .userns - .as_ref() - .map(|userns| userns.nsmode.as_str()), - Some("host") - ); - assert!(specs.supervisor.idmappings.is_none()); - assert!(specs.supervisor.networks.is_empty()); - assert!(specs.supervisor.portmappings.is_empty()); - assert!(specs.workload.env.is_empty()); - assert_eq!(specs.workload.unsetenv, vec!["LD_PRELOAD", "HTTP_PROXY"]); - assert_eq!(specs.workload.secrets.len(), 1); - assert_eq!(specs.workload.secrets[0].source, "resolver"); - assert_eq!(specs.workload.secrets[0].target, RESOLV_CONF_PATH); - assert_eq!(specs.workload.secrets[0].uid, 0); - assert_eq!(specs.workload.secrets[0].gid, 0); - assert_eq!(specs.workload.secrets[0].mode, 0o444); - assert_eq!(specs.workload.use_image_resolve_conf, Some(true)); - assert_eq!(specs.supervisor.use_image_resolve_conf, None); - assert!( - specs - .workload - .mounts - .iter() - .all(|mount| !trusted_mount(&mount.destination)) - ); - let supervisor_ca_mount = specs - .workload - .mounts - .iter() - .find(|mount| { - mount.destination == openshell_sandbox_backend::SUPERVISOR_CA_RUNTIME_ROOT - }) - .expect("workload supervisor CA mount"); - assert_eq!(supervisor_ca_mount.kind, "tmpfs"); - assert_eq!(supervisor_ca_mount.source, "tmpfs"); - for option in ["rw", "noexec", "nosuid", "nodev", "mode=0777", "size=1m"] { - assert!(supervisor_ca_mount.options.contains(&option.to_string())); - } - assert!( - specs - .workload - .mounts - .iter() - .all(|mount| mount.destination != "/run") - ); - assert_eq!(specs.supervisor.secrets.len(), 1); - assert_eq!(specs.supervisor.secrets[0].source, "jwt"); - assert_eq!(specs.supervisor.secrets[0].uid, 1000); - assert_eq!(specs.supervisor.volumes.len(), 2); - assert!(specs.workload.volumes[0].options.contains(&"rw".into())); - assert!(!specs.workload.volumes[0].options.contains(&"nocopy".into())); - assert!(specs.supervisor.volumes[0].options.contains(&"ro".into())); - assert!(specs.supervisor.volumes[0].options.contains(&"z".into())); - assert!( - !specs.supervisor.volumes[0] - .options - .contains(&"nocopy".into()) - ); - assert_eq!(specs.supervisor.entrypoint, vec!["/openshell-supervisor"]); - assert_eq!( - specs - .supervisor - .env - .get(openshell_core::sandbox_env::PROXY_TLS_DIR) - .map(String::as_str), - Some("/run/openshell/proxy-tls") - ); - } - - #[test] - fn resolved_image_creates_workspace_volume_only_for_managed_fallback() { - let default = ResolvedPodmanImage::new("image:latest"); - assert_eq!(default.requested_image, "image:latest"); - assert_eq!(default.id, "image:latest"); - assert_eq!( - default.workspace_root, - driver_mounts::DEFAULT_WORKSPACE_ROOT - ); - - for workdir in ["", "/", "/sandbox", "/sandbox/", "/workspace/project"] { - let image = resolved_image("image:latest", "sha256:immutable", "1000:1000", workdir); - let volume = image.managed_workspace_volume("sandbox-id"); - assert_eq!(image.requested_image, "image:latest"); - assert_eq!(image.id, "sha256:immutable"); - if workdir == "/workspace/project" { - assert!(volume.is_none()); - } else { - let volume = volume.expect("managed fallback must have a workspace volume"); - assert_eq!(volume.name, volume_name("sandbox-id")); - assert_eq!(volume.dest, "/sandbox"); - assert_eq!(volume.options, vec!["rw"]); - } - } - } - - #[test] - fn resolved_image_rejects_volumes_covering_working_dir() { - let inspect = |volume: &str| ImageInspect { - id: "sha256:image".into(), - config: Some(ImageConfig { - working_dir: "/workspace/project".into(), - volumes: Some(std::collections::HashMap::from([( - volume.into(), - Value::Null, - )])), - ..Default::default() - }), - }; - - assert!(ResolvedPodmanImage::from_inspect("image:latest", inspect("/workspace")).is_err()); - let image = - ResolvedPodmanImage::from_inspect("image:latest", inspect("/workspace/project/cache")) - .expect("image volumes nested below the workspace remain valid"); - assert_eq!(image.workspace_root, "/workspace/project"); - - let mut fallback = inspect("/etc/openshell"); - fallback.config.as_mut().unwrap().working_dir = "/sandbox".into(); - ResolvedPodmanImage::from_inspect("image:latest", fallback) - .expect("existing /sandbox images keep their image-volume behavior"); - } - - fn json_struct(value: Value) -> prost_types::Struct { - let Value::Object(object) = value else { - panic!("expected JSON object"); - }; - proto_struct::json_object_to_struct(object) - .expect("test JSON must convert to a protobuf Struct") - } - - fn gpu_resources(count: Option) -> ResourceRequirements { - ResourceRequirements { - gpu: Some(GpuResourceRequirements { count }), - } - } - - #[test] - fn parse_cpu_millicore() { - assert_eq!(parse_cpu_to_microseconds("500m"), Some(50_000)); - assert_eq!(parse_cpu_to_microseconds("1000m"), Some(100_000)); - assert_eq!(parse_cpu_to_microseconds("250m"), Some(25_000)); - } - - #[test] - fn parse_cpu_whole_cores() { - assert_eq!(parse_cpu_to_microseconds("1"), Some(100_000)); - assert_eq!(parse_cpu_to_microseconds("2"), Some(200_000)); - assert_eq!(parse_cpu_to_microseconds("0.5"), Some(50_000)); - } - - #[test] - fn parse_memory_binary_suffixes() { - assert_eq!(parse_memory_to_bytes("256Mi"), Some(256 * 1024 * 1024)); - assert_eq!(parse_memory_to_bytes("4Gi"), Some(4 * 1024 * 1024 * 1024)); - assert_eq!(parse_memory_to_bytes("1Ki"), Some(1024)); - } - - #[test] - fn parse_memory_decimal_suffixes() { - assert_eq!(parse_memory_to_bytes("1G"), Some(1_000_000_000)); - assert_eq!(parse_memory_to_bytes("500M"), Some(500_000_000)); - assert_eq!(parse_memory_to_bytes("1K"), Some(1_000)); - } - - #[test] - fn parse_memory_plain_bytes() { - assert_eq!(parse_memory_to_bytes("1048576"), Some(1_048_576)); - } - - #[test] - fn container_spec_applies_cpu_and_memory_limits() { - use openshell_core::proto::compute::v1::{ - DriverResourceRequirements, DriverSandboxSpec, DriverSandboxTemplate, - }; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - resources: Some(DriverResourceRequirements { - cpu_limit: "500m".to_string(), - memory_limit: "2Gi".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - let limits = build_resource_limits(&sandbox, &config); - - assert_eq!(limits.cpu.quota, 50_000); - assert_eq!(limits.memory.limit, 2 * 1024 * 1024 * 1024); - assert_eq!( - limits.pids.as_ref().map(|pids| pids.limit), - openshell_core::config::default_sandbox_pids_limit().map(std::num::NonZeroI64::get) - ); - let serialized = serde_json::to_string(&limits).unwrap(); - assert!(serialized.contains("\"pids\":{\"limit\":2048}")); - assert!(!serialized.contains("PidsLimit")); - } - - #[test] - fn container_spec_can_inherit_runtime_pids_limit() { - let sandbox = test_sandbox("test-id", "test-name"); - let mut config = test_config(); - config.sandbox_pids_limit = None; - let limits = build_resource_limits(&sandbox, &config); - - assert!(limits.pids.is_none()); - } - - #[test] - fn container_name_is_workspace_qualified() { - assert_eq!( - container_name("default", "my-sandbox", "abc-123"), - "openshell-default--my-sandbox-abc-123" - ); - } - - #[test] - fn container_spec_pins_inspected_image_and_protects_oci_identity() { - let mut sandbox = test_sandbox("test-id", "test-name"); - let spec = sandbox.spec.get_or_insert_default(); - for (key, value) in [ - (openshell_core::sandbox_env::OCI_IMAGE_USER, "spoofed"), - (openshell_core::sandbox_env::SANDBOX_UID, "9999"), - (openshell_core::sandbox_env::SANDBOX_GID, "9999"), - ] { - spec.environment.insert(key.to_string(), value.to_string()); - } - - let image = resolved_image( - "registry.example/app:latest", - "sha256:immutable", - "app:staff", - "/workspace/project", - ); - let container = build_container_spec_for_image( - &sandbox, - &test_config(), - None, - None, - &image, - None, - None, - ) - .unwrap(); - - assert_eq!(container["image"].as_str(), Some("sha256:immutable")); - assert_eq!( - container["env"]["OPENSHELL_CONTAINER_IMAGE"].as_str(), - Some("registry.example/app:latest") - ); - // Only the paired builder materializes the immutable non-root user. - assert_eq!(container["user"].as_str(), Some("")); - assert_eq!(container["image_pull_policy"].as_str(), Some("never")); - assert_eq!(container["dns_search"], serde_json::json!([])); - assert_eq!(container["dns_option"], serde_json::json!([])); - assert_eq!(container["work_dir"].as_str(), Some("/")); - assert_eq!( - container["command"], - serde_json::json!(["--workdir", "/workspace/project"]) - ); - assert!(container["volumes"].as_array().is_some_and(Vec::is_empty)); - assert_eq!( - container["env"][openshell_core::sandbox_env::OCI_IMAGE_USER].as_str(), - Some("app:staff") - ); - assert_eq!( - container["env"][openshell_core::sandbox_env::SANDBOX_UID].as_str(), - Some("") - ); - assert_eq!( - container["env"][openshell_core::sandbox_env::SANDBOX_GID].as_str(), - Some("") - ); - } - - #[test] - fn build_env_strips_gateway_tls_server_name() { - let mut sandbox = test_sandbox("test-id", "test-name"); - let spec = sandbox.spec.get_or_insert_default(); - spec.environment.insert( - openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME.to_string(), - "evil.attacker.example.com".to_string(), - ); - - let container = build_container_spec(&sandbox, &test_config()); - - assert_eq!( - container["env"].get(openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME), - None, - "GATEWAY_TLS_SERVER_NAME must be stripped from the supervisor environment" - ); - } - - #[test] - fn volume_name_uses_id() { - assert_eq!( - volume_name("abc-123"), - "openshell-sandbox-abc-123-workspace" - ); - } - - #[test] - fn short_id_truncates() { - assert_eq!(short_id("abc123def456789"), "abc123def456"); - assert_eq!(short_id("short"), "short"); - } - - #[test] - fn container_spec_omits_devices_without_gpu_request() { - let sandbox = test_sandbox("test-id", "test-name"); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - assert!(spec.get("devices").is_none()); - } - - #[test] - fn container_spec_maps_empty_gpu_request_to_selected_default_cdi_device() { - use openshell_core::proto::compute::v1::DriverSandboxSpec; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }); - let config = test_config(); - let gpu_devices = vec!["nvidia.com/gpu=1".to_string()]; - let spec = build_container_spec_with_token_and_gpu_devices( - &sandbox, - &config, - None, - Some(&gpu_devices), - ) - .unwrap(); - - assert_eq!( - spec["devices"][0]["path"].as_str(), - Some("nvidia.com/gpu=1") - ); - } - - #[test] - fn container_spec_omits_devices_without_resolved_default_cdi_devices() { - use openshell_core::proto::compute::v1::DriverSandboxSpec; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }); - let config = test_config(); - - let spec = - build_container_spec_with_token_and_gpu_devices(&sandbox, &config, None, None).unwrap(); - - assert!(spec.get("devices").is_none()); - } - - #[test] - fn container_spec_accepts_non_nvidia_explicit_and_resolved_cdi_devices() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(DriverSandboxTemplate::default()), - ..Default::default() - }); - let config = test_config(); - for device in ["example.com/gpu=0", "intel.com/gpu=0", "amd.com/gpu=0"] { - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(cdi_devices_config(&[device])); - let explicit = try_build_container_spec_with_token(&sandbox, &config, None).unwrap(); - sandbox.spec.as_mut().unwrap().template = None; - let resolved = build_container_spec_with_token_and_gpu_devices( - &sandbox, - &config, - None, - Some(&[device.to_string()]), - ) - .unwrap(); - for spec in [explicit, resolved] { - assert_eq!(spec["devices"][0]["path"], device); - } - sandbox.spec.as_mut().unwrap().template = Some(DriverSandboxTemplate::default()); - } - } - - #[test] - fn container_spec_rejects_host_paths_in_explicit_and_resolved_cdi_devices() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(DriverSandboxTemplate::default()), - ..Default::default() - }); - let config = test_config(); - for device in [ - "/dev/sda", - "/dev", - "/dev/sda:/dev/sda:rwm", - "vendor/gpu=0/1", - ] { - sandbox - .spec - .as_mut() - .unwrap() - .template - .as_mut() - .unwrap() - .driver_config = Some(cdi_devices_config(&[device])); - let explicit_error = - try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - sandbox.spec.as_mut().unwrap().template = None; - let resolved_error = build_container_spec_with_token_and_gpu_devices( - &sandbox, - &config, - None, - Some(&[device.to_string()]), - ) - .unwrap_err(); - for error in [explicit_error, resolved_error] { - assert!(matches!(error, ComputeDriverError::InvalidArgument(_))); - assert!(error.to_string().contains("CDI qualified names")); - } - sandbox.spec.as_mut().unwrap().template = Some(DriverSandboxTemplate::default()); - } - } - - #[test] - fn container_spec_passes_explicit_cdi_device_id_through() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(DriverSandboxTemplate { - driver_config: Some(cdi_devices_config(&["nvidia.com/gpu=0"])), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - assert_eq!( - spec["devices"][0]["path"].as_str(), - Some("nvidia.com/gpu=0") - ); - } - - #[test] - fn container_spec_accepts_gpu_count_matching_cdi_devices() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(Some(2))), - template: Some(DriverSandboxTemplate { - driver_config: Some(cdi_devices_config(&[ - "nvidia.com/gpu=0", - "nvidia.com/gpu=1", - ])), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - assert_eq!(spec["devices"].as_array().map(Vec::len), Some(2)); - assert_eq!( - spec["devices"][0]["path"].as_str(), - Some("nvidia.com/gpu=0") - ); - assert_eq!( - spec["devices"][1]["path"].as_str(), - Some("nvidia.com/gpu=1") - ); - } - - #[test] - fn container_spec_rejects_gpu_count_mismatched_cdi_devices() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(Some(2))), - template: Some(DriverSandboxTemplate { - driver_config: Some(cdi_devices_config(&["nvidia.com/gpu=0"])), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let err = try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - assert!(matches!(err, ComputeDriverError::InvalidArgument(_))); - assert!( - err.to_string() - .contains("gpu count (2) must match driver_config.cdi_devices length (1)") - ); - } - - #[test] - fn container_spec_rejects_cdi_devices_without_gpu_request() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(cdi_devices_config(&["nvidia.com/gpu=0"])), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let err = try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - assert!(matches!(err, ComputeDriverError::InvalidArgument(_))); - assert!(err.to_string().contains("requires a gpu request")); - } - - #[test] - fn container_spec_rejects_empty_cdi_devices() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(DriverSandboxTemplate { - driver_config: Some(cdi_devices_config(&[])), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let err = try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - assert!(matches!(err, ComputeDriverError::InvalidArgument(_))); - assert!(err.to_string().contains("non-empty list")); - } - - #[test] - fn container_spec_rejects_unknown_driver_config_fields() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(DriverSandboxTemplate { - driver_config: Some(cdi_device_typo_config(&["nvidia.com/gpu=0"])), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let err = try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - assert!(matches!(err, ComputeDriverError::InvalidArgument(_))); - assert!(err.to_string().contains("unknown field")); - } - - #[test] - fn sandbox_driver_config_rejects_trusted_runtime_image_overrides() { - use openshell_core::proto::compute::v1::DriverSandboxTemplate; - - for field in ["sandbox_runtime_image", "supervisor_image"] { - let template = DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - (field): "registry.example.com/openshell/runtime:untrusted" - }))), - ..Default::default() - }; - - let error = PodmanSandboxDriverConfig::from_template(&template) - .expect_err("sandbox requests must not select trusted runtime images"); - assert!(error.to_string().contains("unknown field"), "{error}"); - assert!(error.to_string().contains(field), "{error}"); - } - } - - #[test] - fn container_spec_defaults_drop_capabilities_and_keep_runtime_seccomp() { - let sandbox = test_sandbox("test-id", "test-name"); - let config = test_config(); - let image = ResolvedPodmanImage::new("sha256:image"); - let spec = build_base_spec(&sandbox, &config, None, None, &image, None, None).unwrap(); - assert_eq!(spec.cap_drop, vec!["ALL"]); - assert!(spec.cap_add.is_empty()); - assert!(spec.seccomp_profile_path.is_empty()); - assert!(spec.no_new_privileges); - } - - #[test] - fn container_spec_sets_sandbox_name_in_env() { - let sandbox = test_sandbox("test-id", "my-sandbox"); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let env_map = spec["env"].as_object().expect("env should be an object"); - assert_eq!( - env_map - .get(openshell_core::sandbox_env::SANDBOX) - .and_then(|v| v.as_str()), - Some("my-sandbox"), - ); - } - - #[test] - fn container_spec_sets_ssh_socket_path_in_env() { - let sandbox = test_sandbox("test-id", "test-name"); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let env_map = spec["env"].as_object().expect("env should be an object"); - assert_eq!( - env_map - .get("OPENSHELL_SSH_SOCKET_PATH") - .and_then(|v| v.as_str()), - Some("/run/openshell/test-ssh.sock"), - ); - } - - #[test] - fn container_spec_healthcheck_accepts_supervisor_socket() { - let sandbox = test_sandbox("test-id", "test-name"); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let healthcheck = spec["healthconfig"]["test"] - .as_array() - .expect("healthcheck test should be an array"); - let command = healthcheck - .get(1) - .and_then(|v| v.as_str()) - .expect("healthcheck should include shell command"); - assert!( - command.contains("test -S /run/openshell/test-ssh.sock"), - "healthcheck should consider the supervisor Unix socket ready" - ); - } - - #[test] - fn container_spec_healthcheck_interval_from_config() { - let sandbox = test_sandbox("test-id", "test-name"); - let mut config = test_config(); - config.health_check_interval_secs = std::num::NonZeroU64::new(30); - let spec = build_container_spec(&sandbox, &config); - - let interval = spec["healthconfig"]["Interval"] - .as_u64() - .expect("healthcheck interval should be a u64"); - assert_eq!(interval, 30_000_000_000); - } - - #[test] - fn container_spec_required_vars_cannot_be_overridden() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "legit-name"); - let mut env_overrides = std::collections::HashMap::new(); - env_overrides.insert( - "OPENSHELL_ENDPOINT".to_string(), - "http://evil.example.com".to_string(), - ); - env_overrides.insert("OPENSHELL_SANDBOX_ID".to_string(), "spoofed-id".to_string()); - env_overrides.insert( - "OPENSHELL_SSH_SOCKET_PATH".to_string(), - "/tmp/evil.sock".to_string(), - ); - sandbox.spec = Some(DriverSandboxSpec { - environment: env_overrides, - template: Some(DriverSandboxTemplate::default()), - ..Default::default() - }); - - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let env_map = spec["env"].as_object().expect("env should be an object"); - - assert_eq!( - env_map.get("OPENSHELL_ENDPOINT").and_then(|v| v.as_str()), - Some("http://localhost:50051"), - "OPENSHELL_ENDPOINT must not be overridden by user env" - ); - assert_eq!( - env_map.get("OPENSHELL_SANDBOX_ID").and_then(|v| v.as_str()), - Some("test-id"), - "OPENSHELL_SANDBOX_ID must not be overridden by user env" - ); - assert_eq!( - env_map - .get("OPENSHELL_SSH_SOCKET_PATH") - .and_then(|v| v.as_str()), - Some("/run/openshell/test-ssh.sock"), - "OPENSHELL_SSH_SOCKET_PATH must not be overridden by user env" - ); - } - - #[test] - fn container_spec_passes_the_gateway_otlp_endpoint_to_the_supervisor() { - use openshell_core::sandbox_env::{ - OTLP_AGENT_ENDPOINT, OTLP_AGENT_PROTOCOL, OTLP_ENDPOINT, OTLP_OCSF_ENDPOINT, - OTLP_OCSF_PROTOCOL, OTLP_PROTOCOL, OtlpExport, OtlpProtocol, SupervisorOtlp, - }; - let sandbox = test_sandbox("test-id", "legit-name"); - let spec = build_container_spec(&sandbox, &test_config()); - assert!(spec["env"].get(OTLP_ENDPOINT).is_none()); - - let export = |endpoint: &str, protocol| { - Some(OtlpExport { - endpoint: endpoint.to_string(), - protocol, - }) - }; - let with_otlp = |supervisor_otlp| PodmanComputeConfig { - supervisor_otlp, - ..test_config() - }; - - let spec = build_container_spec( - &sandbox, - &with_otlp(SupervisorOtlp { - traces: export("http://127.0.0.1:4317", OtlpProtocol::Grpc), - ..SupervisorOtlp::default() - }), - ); - assert_eq!(spec["env"][OTLP_ENDPOINT], "http://127.0.0.1:4317"); - assert!(spec["env"].get(OTLP_PROTOCOL).is_none()); - assert!(spec["env"].get(OTLP_OCSF_ENDPOINT).is_none()); - - let spec = build_container_spec( - &sandbox, - &with_otlp(SupervisorOtlp { - traces: export("http://127.0.0.1:4318", OtlpProtocol::HttpProtobuf), - ..SupervisorOtlp::default() - }), - ); - assert_eq!(spec["env"][OTLP_PROTOCOL], "http/protobuf"); - - let spec = build_container_spec( - &sandbox, - &with_otlp(SupervisorOtlp { - ocsf: export("http://siem:4317", OtlpProtocol::Grpc), - ..SupervisorOtlp::default() - }), - ); - assert_eq!(spec["env"][OTLP_OCSF_ENDPOINT], "http://siem:4317"); - assert!(spec["env"].get(OTLP_OCSF_PROTOCOL).is_none()); - assert!( - spec["env"].get(OTLP_AGENT_ENDPOINT).is_none(), - "the agent trace relay stays off unless the gateway enables it" - ); - - let spec = build_container_spec( - &sandbox, - &with_otlp(SupervisorOtlp { - ocsf: export("http://siem:4318", OtlpProtocol::HttpProtobuf), - ..SupervisorOtlp::default() - }), - ); - assert_eq!(spec["env"][OTLP_OCSF_PROTOCOL], "http/protobuf"); - - let spec = build_container_spec( - &sandbox, - &with_otlp(SupervisorOtlp { - agent: export("http://agents:4317", OtlpProtocol::Grpc), - ..SupervisorOtlp::default() - }), - ); - assert_eq!(spec["env"][OTLP_AGENT_ENDPOINT], "http://agents:4317"); - assert!(spec["env"].get(OTLP_AGENT_PROTOCOL).is_none()); - - let spec = build_container_spec( - &sandbox, - &with_otlp(SupervisorOtlp { - agent: export("http://agents:4318", OtlpProtocol::HttpProtobuf), - ..SupervisorOtlp::default() - }), - ); - assert_eq!(spec["env"][OTLP_AGENT_PROTOCOL], "http/protobuf"); - - let config = PodmanComputeConfig { - supervisor_gateway_name: Some("prod-west".to_string()), - ..test_config() - }; - let spec = build_container_spec(&sandbox, &config); - assert_eq!( - spec["env"][openshell_core::sandbox_env::GATEWAY_NAME], - "prod-west" - ); - } - - #[test] - fn container_spec_telemetry_toggle_comes_from_driver_env() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let _guard = ENV_LOCK.lock().unwrap(); - temp_env::with_vars( - [( - openshell_core::sandbox_env::TELEMETRY_ENABLED, - Some("false"), - )], - || { - let mut sandbox = test_sandbox("test-id", "legit-name"); - sandbox.spec = Some(DriverSandboxSpec { - environment: std::collections::HashMap::from([( - openshell_core::sandbox_env::TELEMETRY_ENABLED.to_string(), - "true".to_string(), - )]), - template: Some(DriverSandboxTemplate::default()), - ..Default::default() - }); - - let spec = build_container_spec(&sandbox, &test_config()); - let env_map = spec["env"].as_object().expect("env should be an object"); - - assert_eq!( - env_map - .get(openshell_core::sandbox_env::TELEMETRY_ENABLED) - .and_then(|v| v.as_str()), - Some("false"), - "telemetry toggle must come from the deployment environment" - ); - }, - ); - } - - #[test] - fn container_spec_keeps_network_capabilities_driver_controlled() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "legit-name"); - sandbox.spec = Some(DriverSandboxSpec { - environment: std::collections::HashMap::from([( - openshell_core::sandbox_env::NETWORK_RUNTIME_CAPABILITIES.to_string(), - "spoofed".to_string(), - )]), - template: Some(DriverSandboxTemplate::default()), - ..Default::default() - }); - let spec = build_container_spec(&sandbox, &test_config()); - assert_eq!( - spec["env"][openshell_core::sandbox_env::NETWORK_RUNTIME_CAPABILITIES], - serde_json::json!(openshell_core::sandbox_env::POLICY_DNS_TRANSPARENT_TCP_CAPABILITY) - ); - } - - /// Extract the container spec's supervisor argv (`command`) as strings. - fn spec_command(spec: &Value) -> Vec { - spec["command"] - .as_array() - .expect("command should be an array") - .iter() - .map(|v| { - v.as_str() - .expect("command arg should be a string") - .to_string() - }) - .collect() - } - - #[test] - fn container_spec_passes_operator_proxy_on_supervisor_argv() { - let sandbox = test_sandbox("test-id", "test-name"); - let mut config = test_config(); - config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); - config.no_proxy = Some("*.svc.cluster.local,10.0.0.0/8".to_string()); - - let spec = build_container_spec(&sandbox, &config); - let command = spec_command(&spec); - - // Config travels on argv (the image cannot forge process arguments), - // as flag/value pairs. - let idx = command - .iter() - .position(|a| a == "--upstream-proxy") - .expect("proxy URL flag present"); - assert_eq!( - command.get(idx + 1).map(String::as_str), - Some("http://proxy.corp.com:8080") - ); - let idx = command - .iter() - .position(|a| a == "--upstream-no-proxy") - .expect("no_proxy flag present"); - assert_eq!( - command.get(idx + 1).map(String::as_str), - Some("*.svc.cluster.local,10.0.0.0/8") - ); - - // The proxy settings are argv-only; nothing about them lands in the - // environment, and the conventional proxy variables (which belong to - // the sandbox creator) are not touched by operator config. - let env_map = spec["env"].as_object().expect("env should be an object"); - for key in ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"] { - assert!( - !env_map.contains_key(key), - "{key} must not be populated from operator proxy config" - ); - } - } - - #[test] - fn container_spec_passes_ipv6_egress_settings_on_supervisor_argv() { - let sandbox = test_sandbox("test-id", "test-name"); - let mut config = test_config(); - let command = spec_command(&build_container_spec(&sandbox, &config)); - assert!( - !command - .iter() - .any(|a| a == "--policy-dns-ipv6-egress" || a == "--nat64-prefix"), - "no IPv6 egress flags without operator config: {command:?}" - ); - - config.policy_dns_ipv6_egress = Some(openshell_core::PolicyDnsIpv6Egress::Disabled); - config.nat64_prefixes = vec!["64:ff9b:1::/96".to_string()]; - let command = spec_command(&build_container_spec(&sandbox, &config)); - let idx = command - .iter() - .position(|a| a == "--policy-dns-ipv6-egress") - .expect("IPv6 egress flag present"); - assert_eq!(command.get(idx + 1).map(String::as_str), Some("disabled")); - let idx = command - .iter() - .position(|a| a == "--nat64-prefix") - .expect("NAT64 prefix flag present"); - assert_eq!( - command.get(idx + 1).map(String::as_str), - Some("64:ff9b:1::/96") - ); - } - - #[test] - fn container_spec_omits_proxy_argv_when_unconfigured() { - let sandbox = test_sandbox("test-id", "test-name"); - let spec = build_container_spec(&sandbox, &test_config()); - let command = spec_command(&spec); - - assert!( - !command.iter().any(|a| a.starts_with("--upstream-proxy")), - "no proxy flags without operator proxy config: {command:?}" - ); - } - - #[test] - fn container_spec_binds_proxy_ca_bundle_and_passes_argv() { - let sandbox = test_sandbox("ca-id", "ca-name"); - let mut config = test_config(); - config.https_proxy = Some("https://proxy.corp.com:3130".to_string()); - config.proxy_ca_bundle = Some("/host/proxy-ca.pem".to_string()); - - let spec = build_container_spec(&sandbox, &config); - let command = spec_command(&spec); - - // The container-side mount path travels on argv as a flag/value pair. - let idx = command - .iter() - .position(|a| a == "--upstream-proxy-ca-bundle") - .expect("CA bundle flag present"); - assert_eq!( - command.get(idx + 1).map(String::as_str), - Some("/etc/openshell/tls/proxy/ca-bundle.pem") - ); - - // The host PEM is bind-mounted read-only at that container path. - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - let ca_mount = mounts - .iter() - .find(|m| { - m["type"].as_str() == Some("bind") - && m["destination"].as_str() == Some("/etc/openshell/tls/proxy/ca-bundle.pem") - }) - .expect("CA bundle bind mount present"); - assert_eq!(ca_mount["source"].as_str(), Some("/host/proxy-ca.pem")); - assert!( - ca_mount["options"] - .as_array() - .expect("options array") - .iter() - .any(|o| o.as_str() == Some("ro")), - "CA bundle mount must be read-only" - ); - } - - #[test] - fn container_spec_omits_proxy_ca_bundle_when_unconfigured() { - let sandbox = test_sandbox("test-id", "test-name"); - let spec = build_container_spec(&sandbox, &test_config()); - let mounts = spec["mounts"].as_array().expect("mounts array"); - assert!( - !mounts.iter().any( - |m| m["destination"].as_str() == Some("/etc/openshell/tls/proxy/ca-bundle.pem") - ), - "no CA bundle mount without operator config" - ); - assert!( - !mounts - .iter() - .any(|m| { m["destination"].as_str() == Some(ADDITIONAL_CA_MOUNT_PATH) }), - "no destination CA mount without global config" - ); - assert!( - !spec_command(&spec) - .iter() - .any(|arg| arg == "--additional-ca-bundle"), - "no destination CA argument without global config" - ); - } - - #[test] - fn container_spec_sandbox_env_cannot_influence_proxy_argv() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - // A sandbox creator tries to steer the egress boundary through spec - // and template environment (image-baked ENV behaves the same at the - // runtime layer). The supervisor takes proxy config only from the - // argv the driver builds out of operator config, so none of it has - // any effect. - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - environment: std::collections::HashMap::from([ - ( - "HTTPS_PROXY".to_string(), - "http://attacker:9999".to_string(), - ), - ("NO_PROXY".to_string(), "*".to_string()), - ]), - template: Some(DriverSandboxTemplate { - environment: std::collections::HashMap::from([( - "NO_PROXY".to_string(), - "*".to_string(), - )]), - ..Default::default() - }), - ..Default::default() - }); - let mut config = test_config(); - config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); - - let spec = build_container_spec(&sandbox, &config); - let command = spec_command(&spec); - - // Only the operator's proxy is delivered, and only on argv. - let idx = command - .iter() - .position(|a| a == "--upstream-proxy") - .expect("operator proxy flag present"); - assert_eq!( - command.get(idx + 1).map(String::as_str), - Some("http://proxy.corp.com:8080") - ); - assert!( - !command.iter().any(|a| a == "--upstream-no-proxy"), - "sandbox environment must not add a NO_PROXY bypass: {command:?}" - ); - assert!( - !command.iter().any(|a| a.contains("attacker")), - "attacker proxy must not reach argv: {command:?}" - ); - } - - #[test] - fn container_spec_required_labels_cannot_be_overridden() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("real-id", "real-name"); - sandbox.namespace = "real-namespace".to_string(); - let mut label_overrides = std::collections::HashMap::new(); - label_overrides.insert( - "openshell.ai/sandbox-id".to_string(), - "spoofed-id".to_string(), - ); - label_overrides.insert( - "openshell.ai/sandbox-name".to_string(), - "spoofed-name".to_string(), - ); - label_overrides.insert( - "openshell.ai/sandbox-namespace".to_string(), - "spoofed-namespace".to_string(), - ); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - labels: label_overrides, - ..Default::default() - }), - ..Default::default() - }); - - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let labels = spec["labels"] - .as_object() - .expect("labels should be an object"); - assert_eq!( - labels - .get("openshell.ai/sandbox-id") - .and_then(|v| v.as_str()), - Some("real-id"), - "openshell.sandbox-id must not be overridden by template labels" - ); - assert_eq!( - labels - .get("openshell.ai/sandbox-name") - .and_then(|v| v.as_str()), - Some("real-name"), - "openshell.sandbox-name must not be overridden by template labels" - ); - assert_eq!( - labels - .get("openshell.ai/sandbox-namespace") - .and_then(|v| v.as_str()), - Some("real-namespace"), - "openshell.sandbox-namespace must not be overridden by template labels" - ); - } - - #[test] - fn container_spec_injects_host_aliases() { - let sandbox = test_sandbox("test-id", "test-name"); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let hostadd: Vec<&str> = spec["hostadd"] - .as_array() - .expect("hostadd should be an array") - .iter() - .filter_map(|v| v.as_str()) - .collect(); - - assert!( - hostadd.contains(&"host.containers.internal:host-gateway"), - "missing Podman host alias" - ); - assert!( - hostadd.contains(&"host.openshell.internal:host-gateway"), - "missing OpenShell stable host alias" - ); - assert!( - !hostadd.contains(&"host.docker.internal:host-gateway"), - "Podman should not inject Docker's host alias" - ); - } - - #[test] - fn parse_cpu_negative_returns_none() { - assert_eq!(parse_cpu_to_microseconds("-1"), None); - assert_eq!(parse_cpu_to_microseconds("-500m"), None); - } - - #[test] - fn parse_cpu_zero_returns_none() { - assert_eq!(parse_cpu_to_microseconds("0m"), None); - assert_eq!(parse_cpu_to_microseconds("0"), None); - } - - fn test_sandbox(id: &str, name: &str) -> DriverSandbox { - DriverSandbox { - id: id.to_string(), - name: name.to_string(), - namespace: String::new(), - spec: None, - status: None, - workspace: String::new(), - } - } - - fn cdi_devices_config(device_ids: &[&str]) -> prost_types::Struct { - list_string_driver_config("cdi_devices", device_ids) - } - - fn cdi_device_typo_config(device_ids: &[&str]) -> prost_types::Struct { - list_string_driver_config("cdi_device", device_ids) - } - - fn list_string_driver_config(field: &str, values: &[&str]) -> prost_types::Struct { - prost_types::Struct { - fields: std::iter::once(( - field.to_string(), - prost_types::Value { - kind: Some(prost_types::value::Kind::ListValue( - prost_types::ListValue { - values: values - .iter() - .map(|device_id| prost_types::Value { - kind: Some(prost_types::value::Kind::StringValue( - (*device_id).to_string(), - )), - }) - .collect(), - }, - )), - }, - )) - .collect(), - } - } - - fn test_config() -> PodmanComputeConfig { - PodmanComputeConfig { - socket_path: Some(std::path::PathBuf::from("/tmp/test.sock")), - default_image: "test-image:latest".to_string(), - grpc_endpoint: "http://localhost:50051".to_string(), - host_gateway_ip: String::new(), - ssh_socket_path: "/run/openshell/test-ssh.sock".to_string(), - ..PodmanComputeConfig::default() - } - } - - #[test] - fn container_spec_includes_sandbox_runtime_image_volume() { - let sandbox = test_sandbox("test-id", "test-name"); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let image_volumes = spec["image_volumes"] - .as_array() - .expect("image_volumes should be an array"); - assert_eq!( - image_volumes.len(), - 1, - "should have exactly one image volume" - ); - - let vol = &image_volumes[0]; - assert_eq!( - vol["source"].as_str(), - Some(openshell_core::config::default_sandbox_runtime_image().as_str()), - "image volume source should be the sandbox runtime image" - ); - assert_eq!( - vol["destination"].as_str(), - Some(SUPERVISOR_MOUNT_DIR), - "image volume destination should be /opt/openshell/bin" - ); - assert_eq!( - vol["rw"].as_bool(), - Some(false), - "image volume should be read-only" - ); - } - - #[test] - fn container_spec_includes_driver_config_mounts() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [ - { - "type": "volume", - "source": "work-nfs", - "target": "/sandbox/work", - "read_only": true - }, - { - "type": "tmpfs", - "target": "/sandbox/cache", - "options": ["nosuid", "nodev"], - "size_bytes": 1_048_576, - "mode": 511 - }, - { - "type": "image", - "source": "ghcr.io/acme/tools:latest", - "target": "/opt/tools", - "read_only": true - } - ] - }))), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let volumes = spec["volumes"] - .as_array() - .expect("volumes should be an array"); - assert!(volumes.iter().any(|volume| { - volume["name"].as_str() == Some("openshell-sandbox-test-id-workspace") - && volume["dest"].as_str() == Some("/sandbox") - })); - assert!(volumes.iter().any(|volume| { - volume["name"].as_str() == Some("work-nfs") - && volume["dest"].as_str() == Some("/sandbox/work") - && volume["options"].as_array().is_some_and(|options| { - options.iter().any(|option| option.as_str() == Some("ro")) - }) - })); - - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - assert!(mounts.iter().any(|mount| { - mount["type"].as_str() == Some("tmpfs") - && mount["destination"].as_str() == Some("/sandbox/cache") - && mount["options"].as_array().is_some_and(|options| { - options - .iter() - .any(|option| option.as_str() == Some("size=1048576")) - && options - .iter() - .any(|option| option.as_str() == Some("mode=777")) - }) - })); - - let image_volumes = spec["image_volumes"] - .as_array() - .expect("image_volumes should be an array"); - let expected_sandbox_runtime = openshell_core::config::default_sandbox_runtime_image(); - assert!(image_volumes.iter().any(|volume| { - volume["source"].as_str() == Some(expected_sandbox_runtime.as_str()) - && volume["destination"].as_str() == Some("/opt/openshell/bin") - })); - assert!(image_volumes.iter().any(|volume| { - volume["source"].as_str() == Some("ghcr.io/acme/tools:latest") - && volume["destination"].as_str() == Some("/opt/tools") - && volume["rw"].as_bool() == Some(false) - })); - } - - #[test] - fn container_spec_defaults_volume_mounts_to_read_only() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "volume", - "source": "work-nfs", - "target": "/sandbox/work" - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let spec = build_container_spec(&sandbox, &config); - let volumes = spec["volumes"] - .as_array() - .expect("volumes should be an array"); - - assert!(volumes.iter().any(|volume| { - volume["name"].as_str() == Some("work-nfs") - && volume["dest"].as_str() == Some("/sandbox/work") - && volume["options"].as_array().is_some_and(|options| { - options.iter().any(|option| option.as_str() == Some("ro")) - }) - })); - } - - #[test] - fn container_spec_allows_explicit_writable_volume_mounts() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "volume", - "source": "work-nfs", - "target": "/sandbox/work", - "read_only": false - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let spec = build_container_spec(&sandbox, &config); - let volumes = spec["volumes"] - .as_array() - .expect("volumes should be an array"); - - assert!(volumes.iter().any(|volume| { - volume["name"].as_str() == Some("work-nfs") - && volume["dest"].as_str() == Some("/sandbox/work") - && volume["options"].as_array().is_some_and(|options| { - options.iter().any(|option| option.as_str() == Some("rw")) - }) - })); - } - - #[test] - fn driver_config_rejects_duplicate_mount_targets() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [ - { - "type": "volume", - "source": "work-nfs", - "target": "/sandbox/work" - }, - { - "type": "tmpfs", - "target": "/sandbox/work" - } - ] - }))), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let err = try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - - assert!( - err.to_string() - .contains("duplicate podman driver_config mount target") - ); - } - - #[test] - fn resolved_workspace_checks_all_driver_mount_types() { - let image = resolved_image( - "image:latest", - "sha256:immutable", - "1000:1000", - "/workspace/project", - ); - let mut config = test_config(); - config.enable_bind_mounts = true; - for mut mount in [ - serde_json::json!({"type": "bind", "source": "/host/workspace"}), - serde_json::json!({"type": "volume", "source": "data"}), - serde_json::json!({"type": "tmpfs"}), - serde_json::json!({"type": "image", "source": "image:mounted"}), - ] { - for target in [ - "/workspace", - "/workspace/project", - "/workspace/project/cache", - ] { - mount["target"] = target.into(); - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox - .spec - .get_or_insert_default() - .template - .get_or_insert_default() - .driver_config = - Some(json_struct(serde_json::json!({"mounts": [mount.clone()]}))); - let result = build_container_spec_for_image( - &sandbox, &config, None, None, &image, None, None, - ); - if target == "/workspace/project/cache" { - result.expect("mounts nested below the workspace remain valid"); - } else { - assert!( - result - .unwrap_err() - .to_string() - .contains("reserved for the OpenShell workspace") - ); - } - } - } - } - - #[test] - fn driver_config_rejects_bind_mounts_unless_enabled() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "/host/path", - "target": "/sandbox/host" - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let err = try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - - assert!(err.to_string().contains("enable_bind_mounts = true")); - } - - #[test] - fn container_spec_includes_bind_mounts_when_enabled() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "/host/path", - "target": "/sandbox/host", - "read_only": true - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let mut config = test_config(); - config.enable_bind_mounts = true; - - let spec = build_container_spec(&sandbox, &config); - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - - assert!(mounts.iter().any(|mount| { - mount["type"].as_str() == Some("bind") - && mount["source"].as_str() == Some("/host/path") - && mount["destination"].as_str() == Some("/sandbox/host") - && mount["options"].as_array().is_some_and(|options| { - options.iter().any(|option| option.as_str() == Some("ro")) - && options - .iter() - .any(|option| option.as_str() == Some("rbind")) - }) - })); - } - - #[test] - fn container_spec_defaults_enabled_bind_mounts_to_read_only() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "/host/path", - "target": "/sandbox/host" - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let mut config = test_config(); - config.enable_bind_mounts = true; - - let spec = build_container_spec(&sandbox, &config); - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - - assert!(mounts.iter().any(|mount| { - mount["type"].as_str() == Some("bind") - && mount["source"].as_str() == Some("/host/path") - && mount["destination"].as_str() == Some("/sandbox/host") - && mount["options"].as_array().is_some_and(|options| { - options.iter().any(|option| option.as_str() == Some("ro")) - && options - .iter() - .any(|option| option.as_str() == Some("rbind")) - }) - })); - } - - #[test] - fn driver_config_rejects_relative_bind_sources_when_enabled() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "relative/path", - "target": "/sandbox/host" - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let mut config = test_config(); - config.enable_bind_mounts = true; - - let err = try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - - assert!( - err.to_string() - .contains("bind source must be an absolute host path") - ); - } - - #[test] - fn container_spec_bind_mount_selinux_shared_label() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "/data/shared", - "target": "/sandbox/data", - "read_only": true, - "selinux_label": "shared" - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let mut config = test_config(); - config.enable_bind_mounts = true; - - let spec = build_container_spec(&sandbox, &config); - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - - assert!(mounts.iter().any(|mount| { - mount["type"].as_str() == Some("bind") - && mount["source"].as_str() == Some("/data/shared") - && mount["destination"].as_str() == Some("/sandbox/data") - && mount["options"].as_array().is_some_and(|options| { - options.iter().any(|o| o.as_str() == Some("ro")) - && options.iter().any(|o| o.as_str() == Some("z")) - }) - })); - } - - #[test] - fn container_spec_bind_mount_selinux_private_label() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "bind", - "source": "/data/exclusive", - "target": "/sandbox/data", - "read_only": false, - "selinux_label": "private" - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let mut config = test_config(); - config.enable_bind_mounts = true; - - let spec = build_container_spec(&sandbox, &config); - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - - assert!(mounts.iter().any(|mount| { - mount["type"].as_str() == Some("bind") - && mount["source"].as_str() == Some("/data/exclusive") - && mount["destination"].as_str() == Some("/sandbox/data") - && mount["options"].as_array().is_some_and(|options| { - options.iter().any(|o| o.as_str() == Some("rw")) - && options.iter().any(|o| o.as_str() == Some("Z")) - }) - })); - } - - #[test] - fn driver_config_rejects_reserved_mount_targets() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - for target in ["/etc/openshell/tls/client", ADDITIONAL_CA_MOUNT_PATH] { - let mut sandbox = test_sandbox("test-id", "test-name"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "volume", - "source": "work-nfs", - "target": target - }] - }))), - ..Default::default() - }), - ..Default::default() - }); - let config = test_config(); - - let err = try_build_container_spec_with_token(&sandbox, &config, None).unwrap_err(); - - assert!( - err.to_string().contains("reserved OpenShell path"), - "target {target}: {err}" - ); - } - } - - #[test] - fn user_mounts_cannot_replace_private_channel_hierarchy() { - for target in [ - "/.openshell", - "/.openshell/channel", - "/.openshell/channel/sandbox", - "/.openshell/supervisor", - ] { - let mount = PodmanDriverMountConfig::Volume { - source: "user-owned".into(), - target: target.into(), - read_only: false, - subpath: None, - }; - assert!( - validate_podman_driver_mounts(&[mount], false).is_err(), - "{target}" - ); - } - } - - #[test] - fn container_spec_uses_configured_host_gateway_ip() { - let sandbox = test_sandbox("test-id", "test-name"); - let mut config = test_config(); - config.host_gateway_ip = "192.168.127.254".to_string(); - let spec = build_container_spec(&sandbox, &config); - - assert_eq!( - spec["restart_policy"].as_str(), - Some("no"), - "the gateway owns sandbox restart policy" - ); - - let hostadd: Vec<&str> = spec["hostadd"] - .as_array() - .expect("hostadd should be an array") - .iter() - .filter_map(|v| v.as_str()) - .collect(); - - assert!( - hostadd.contains(&"host.containers.internal:192.168.127.254"), - "missing Podman host alias with configured host gateway IP" - ); - assert!( - hostadd.contains(&"host.openshell.internal:192.168.127.254"), - "missing OpenShell host alias with configured host gateway IP" - ); - assert!( - !hostadd.contains(&"host.containers.internal:host-gateway"), - "configured host gateway IP should avoid Podman's host-gateway resolver" - ); - } - - #[test] - fn container_spec_includes_only_tls_ca_when_configured() { - let sandbox = test_sandbox("tls-id", "tls-name"); - let mut config = test_config(); - config.guest_tls_ca = Some(std::path::PathBuf::from("/host/ca.crt")); - - let spec = build_container_spec(&sandbox, &config); - - // Verify TLS env vars are set. - let env_map = spec["env"].as_object().expect("env should be an object"); - assert_eq!( - env_map.get("OPENSHELL_TLS_CA").and_then(|v| v.as_str()), - Some("/etc/openshell/tls/client/ca.crt"), - ); - assert!(env_map.get("OPENSHELL_TLS_CERT").is_none()); - assert!(env_map.get("OPENSHELL_TLS_KEY").is_none()); - - // Verify only the CA bind mount exists. - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - let bind_dests: Vec<&str> = mounts - .iter() - .filter(|m| m["type"].as_str() == Some("bind")) - .filter_map(|m| m["destination"].as_str()) - .collect(); - assert!( - bind_dests.contains(&"/etc/openshell/tls/client/ca.crt"), - "should bind-mount CA cert" - ); - assert_eq!(bind_dests.len(), 1); - - // Verify SELinux relabel option is present iff SELinux is enabled. - let tls_binds: Vec<&Value> = mounts - .iter() - .filter(|m| m["type"].as_str() == Some("bind")) - .collect(); - let has_z = tls_binds.iter().all(|m| { - m["options"] - .as_array() - .is_some_and(|opts| opts.iter().any(|o| o.as_str() == Some("z"))) - }); - assert_eq!( - has_z, - is_selinux_enabled(), - "TLS bind mounts should include 'z' option iff SELinux is enabled" - ); - } - - #[test] - fn container_spec_uses_token_secret_mount_without_raw_token_env() { - use openshell_core::proto::compute::v1::DriverSandboxSpec; - - let mut sandbox = test_sandbox("token-id", "token-name"); - sandbox.spec = Some(DriverSandboxSpec { - sandbox_token: "secret.jwt.value".to_string(), - ..Default::default() - }); - let config = test_config(); - let secret_name = token_secret_name(&sandbox.id); - - let spec = build_container_spec_with_token(&sandbox, &config, Some(&secret_name)); - - let env_map = spec["env"].as_object().expect("env should be an object"); - assert_eq!( - env_map - .get(openshell_core::sandbox_env::SANDBOX_TOKEN) - .and_then(|v| v.as_str()), - None - ); - assert_eq!( - env_map - .get(openshell_core::sandbox_env::SANDBOX_TOKEN_FILE) - .and_then(|v| v.as_str()), - Some("/etc/openshell/auth/sandbox.jwt") - ); - let secrets = spec["secrets"] - .as_array() - .expect("secrets should be an array"); - assert!(secrets.iter().any(|secret| { - secret["source"].as_str() == Some(secret_name.as_str()) - && secret["target"].as_str() == Some("/etc/openshell/auth/sandbox.jwt") - && secret["mode"].as_u64() == Some(0o400) - })); - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - assert!( - !mounts - .iter() - .any(|m| { m["destination"].as_str() == Some("/etc/openshell/auth/sandbox.jwt") }) - ); - } - - #[test] - fn container_spec_proxy_auth_file_mounts_secret_and_sets_path_only() { - let sandbox = test_sandbox("proxy-id", "proxy-name"); - let mut config = test_config(); - config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); - config.proxy_auth_file = Some("/etc/openshell/secrets/proxy-auth".to_string()); - config.proxy_auth_allow_insecure = Some(true); - - let spec = build_container_spec(&sandbox, &config); - let command = spec_command(&spec); - - // The supervisor gets only the mount *path* on argv, never the - // credential itself. - let idx = command - .iter() - .position(|a| a == "--upstream-proxy-auth-file") - .expect("auth-file flag present"); - assert_eq!( - command.get(idx + 1).map(String::as_str), - Some(UPSTREAM_PROXY_AUTH_MOUNT_PATH) - ); - // The cleartext-credential acknowledgement travels with the auth - // file so the supervisor's fail-closed pairing check passes. - assert!( - command - .iter() - .any(|a| a == "--upstream-proxy-auth-allow-insecure"), - "acknowledgement flag present: {command:?}" - ); - // The raw credential path from config never appears anywhere in the - // spec (only the fixed mount path does). - assert!( - !command - .iter() - .any(|a| a == "/etc/openshell/secrets/proxy-auth"), - "host-side credential path must not reach the container: {command:?}" - ); - - let secrets = spec["secrets"] - .as_array() - .expect("secrets should be an array"); - assert!( - secrets.iter().any(|secret| { - secret["source"].as_str() == Some(proxy_auth_secret_name(&sandbox.id).as_str()) - && secret["target"].as_str() == Some(UPSTREAM_PROXY_AUTH_MOUNT_PATH) - && secret["mode"].as_u64() == Some(0o400) - }), - "proxy credentials must be delivered through a root-only secret mount" - ); - } - - #[test] - fn container_spec_omits_proxy_auth_mount_when_unconfigured() { - let sandbox = test_sandbox("proxy-id", "proxy-name"); - let mut config = test_config(); - config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); - - let spec = build_container_spec(&sandbox, &config); - let command = spec_command(&spec); - assert!( - !command.iter().any(|a| a == "--upstream-proxy-auth-file"), - "auth-file flag must be absent when no proxy_auth_file is configured: {command:?}" - ); - assert!( - !command - .iter() - .any(|a| a == "--upstream-proxy-auth-allow-insecure"), - "acknowledgement flag must be absent when no proxy_auth_file is configured: {command:?}" - ); - } - - #[test] - fn container_spec_connect_by_hostname_passed_only_on_opt_in() { - let sandbox = test_sandbox("proxy-id", "proxy-name"); - let mut config = test_config(); - config.https_proxy = Some("http://proxy.corp.com:8080".to_string()); - - // Default: no flag, the supervisor uses validated-IP CONNECT binding. - let spec = build_container_spec(&sandbox, &config); - let command = spec_command(&spec); - assert!( - !command - .iter() - .any(|a| a == "--upstream-proxy-connect-by-hostname"), - "hostname CONNECT must be absent without the operator opt-in: {command:?}" - ); - - config.proxy_connect_by_hostname = Some(true); - let spec = build_container_spec(&sandbox, &config); - let command = spec_command(&spec); - assert!( - command - .iter() - .any(|a| a == "--upstream-proxy-connect-by-hostname"), - "hostname CONNECT flag present on opt-in: {command:?}" - ); - } - - #[test] - fn container_spec_includes_provider_spiffe_socket_when_configured() { - let sandbox = test_sandbox("spiffe-id", "spiffe-name"); - let mut config = test_config(); - config.provider_spiffe_workload_api_socket = - Some(std::path::PathBuf::from("/host/spire-agent.sock")); - - let spec = build_container_spec(&sandbox, &config); - - let env_map = spec["env"].as_object().expect("env should be an object"); - assert_eq!( - env_map - .get(openshell_core::sandbox_env::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET) - .and_then(|v| v.as_str()), - Some("/spiffe-workload-api/spire-agent.sock"), - ); - - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - assert!(mounts.iter().any(|m| { - m["type"].as_str() == Some("bind") - && m["source"].as_str() == Some("/host") - && m["destination"].as_str() == Some(PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR) - })); - } - - #[test] - fn container_spec_omits_tls_without_config() { - let sandbox = test_sandbox("notls-id", "notls-name"); - let config = test_config(); - - let spec = build_container_spec(&sandbox, &config); - - let env_map = spec["env"].as_object().expect("env should be an object"); - assert!( - env_map.get("OPENSHELL_TLS_CA").is_none(), - "TLS env vars should not be set without TLS config" - ); - - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - let bind_count = mounts - .iter() - .filter(|m| m["type"].as_str() == Some("bind")) - .count(); - assert_eq!(bind_count, 0, "no bind mounts without TLS config"); - } - - #[test] - fn container_spec_includes_userns_when_configured() { - let sandbox = test_sandbox("userns-id", "userns-name"); - let mut config = test_config(); - config.userns = Some("auto".to_string()); - let spec = build_container_spec(&sandbox, &config); - - let userns = &spec["userns"]; - assert_eq!(userns["nsmode"].as_str(), Some("auto")); - assert!(userns.get("value").is_none(), "bare auto should omit value"); - - let idmappings = &spec["idmappings"]; - assert_eq!( - idmappings["AutoUserNs"].as_bool(), - Some(true), - "idmappings.AutoUserNs must be true for userns=auto" - ); - } - - #[test] - fn container_spec_auto_with_params() { - let sandbox = test_sandbox("userns-auto-params-id", "userns-auto-params-name"); - let mut config = test_config(); - config.userns = Some("auto:size=65536".to_string()); - let spec = build_container_spec(&sandbox, &config); - - let userns = &spec["userns"]; - assert_eq!(userns["nsmode"].as_str(), Some("auto")); - assert_eq!(userns["value"].as_str(), Some("size=65536")); - - assert_eq!( - spec["idmappings"]["AutoUserNs"].as_bool(), - Some(true), - "idmappings.AutoUserNs must be true for auto:size=65536" - ); - } - - #[test] - fn container_spec_keep_id_with_params() { - let sandbox = test_sandbox("userns-keepid-id", "userns-keepid-name"); - let mut config = test_config(); - config.userns = Some("keep-id:uid=1000,gid=1000".to_string()); - let spec = build_container_spec(&sandbox, &config); - - let userns = &spec["userns"]; - assert_eq!(userns["nsmode"].as_str(), Some("keep-id")); - assert_eq!(userns["value"].as_str(), Some("uid=1000,gid=1000")); - - assert!( - spec.get("idmappings").is_none(), - "idmappings should not be set for keep-id" - ); - } - - #[test] - fn container_spec_nomap_mode() { - let sandbox = test_sandbox("userns-nomap-id", "userns-nomap-name"); - let mut config = test_config(); - config.userns = Some("no-map".to_string()); - let spec = build_container_spec(&sandbox, &config); - - let userns = &spec["userns"]; - assert_eq!(userns["nsmode"].as_str(), Some("no-map")); - assert!(userns.get("value").is_none(), "no-map should omit value"); - - assert!( - spec.get("idmappings").is_none(), - "idmappings should not be set for no-map" - ); - } - - #[test] - fn container_spec_private_with_mappings() { - let sandbox = test_sandbox("userns-private-id", "userns-private-name"); - let mut config = test_config(); - config.userns = Some("private".to_string()); - config.uidmap = vec!["0:1000:1".to_string(), "1:100000:65536".to_string()]; - config.gidmap = vec!["0:1000:1".to_string(), "1:100000:65536".to_string()]; - let spec = build_container_spec(&sandbox, &config); - - let userns = &spec["userns"]; - assert_eq!(userns["nsmode"].as_str(), Some("private")); - assert!(userns.get("value").is_none(), "private should omit value"); - - let idmappings = &spec["idmappings"]; - assert_eq!( - idmappings["AutoUserNs"].as_bool(), - Some(false), - "AutoUserNs must be false for private mode" - ); - - let uid_map = idmappings["UIDMap"] - .as_array() - .expect("UIDMap should be an array"); - assert_eq!(uid_map.len(), 2); - assert_eq!(uid_map[0]["container_id"].as_u64(), Some(0)); - assert_eq!(uid_map[0]["host_id"].as_u64(), Some(1000)); - assert_eq!(uid_map[0]["size"].as_u64(), Some(1)); - assert_eq!(uid_map[1]["container_id"].as_u64(), Some(1)); - assert_eq!(uid_map[1]["host_id"].as_u64(), Some(100_000)); - assert_eq!(uid_map[1]["size"].as_u64(), Some(65536)); - - let gid_map = idmappings["GIDMap"] - .as_array() - .expect("GIDMap should be an array"); - assert_eq!(gid_map.len(), 2); - assert_eq!(gid_map[0]["container_id"].as_u64(), Some(0)); - assert_eq!(gid_map[0]["host_id"].as_u64(), Some(1000)); - assert_eq!(gid_map[0]["size"].as_u64(), Some(1)); - } - - #[test] - fn container_spec_omits_userns_when_unset() { - let sandbox = test_sandbox("no-userns-id", "no-userns-name"); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - assert!( - spec.get("userns").is_none(), - "userns should not be set when unconfigured" - ); - assert!( - spec.get("idmappings").is_none(), - "idmappings should not be set when userns is unconfigured" - ); - } - - #[test] - fn container_spec_uses_bind_mount_for_supervisor_when_path_provided() { - let sandbox = test_sandbox("bind-sv-id", "bind-sv-name"); - let config = test_config(); - let image = resolve_image(&sandbox, &config); - let resolved = ResolvedPodmanImage::new(image); - let spec = build_container_spec_for_image( - &sandbox, - &config, - None, - None, - &resolved, - Some(Path::new("/host/cache/openshell-sandbox")), - None, - ) - .unwrap(); - - let image_volumes = spec["image_volumes"] - .as_array() - .expect("image_volumes should be an array"); - assert!( - !image_volumes - .iter() - .any(|v| v["destination"].as_str() == Some(SUPERVISOR_MOUNT_DIR)), - "sandbox runtime image volume should not be present when bind path is provided" - ); - - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - let sv_bind = mounts - .iter() - .find(|m| m["destination"].as_str() == Some(SUPERVISOR_BINARY_PATH)); - assert!( - sv_bind.is_some(), - "supervisor bind mount should be present at {SUPERVISOR_BINARY_PATH}" - ); - let sv_bind = sv_bind.unwrap(); - assert_eq!( - sv_bind["source"].as_str(), - Some("/host/cache/openshell-sandbox") - ); - assert_eq!(sv_bind["type"].as_str(), Some("bind")); - } - - #[test] - fn container_spec_uses_image_volume_when_no_bind_path() { - let sandbox = test_sandbox("imgvol-id", "imgvol-name"); - let config = test_config(); - let spec = build_container_spec(&sandbox, &config); - - let image_volumes = spec["image_volumes"] - .as_array() - .expect("image_volumes should be an array"); - assert!( - image_volumes - .iter() - .any(|v| v["destination"].as_str() == Some(SUPERVISOR_MOUNT_DIR)), - "sandbox runtime image volume should be present by default" - ); - - let mounts = spec["mounts"] - .as_array() - .expect("mounts should be an array"); - assert!( - !mounts.iter().any( - |m| m["destination"].as_str() == Some(SUPERVISOR_BINARY_PATH) - && m["type"].as_str() == Some("bind") - ), - "supervisor bind mount should not be present by default" - ); - } -} diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs deleted file mode 100644 index a263bcf7d2..0000000000 --- a/crates/openshell-driver-podman/src/driver.rs +++ /dev/null @@ -1,5127 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Podman compute driver. - -use crate::client::{ContainerListEntry, PodmanApiError, PodmanClient, VolumeInspect}; -use crate::config::{PodmanComputeConfig, podman_image_pull_policy}; -use crate::container::{self, LABEL_MANAGED_FILTER, LABEL_SANDBOX_ID, PodmanSandboxDriverConfig}; -use crate::watcher::{ - self, LifecycleEventFences, WatchStream, driver_sandbox_from_inspect, - driver_sandbox_from_list_entry, -}; -use openshell_core::config::CDI_GPU_DEVICE_ALL; -use openshell_core::driver_utils::{ - SANDBOX_RUNTIME_IMAGE_BINARY_PATH, extract_first_tar_entry, supervisor_image_should_refresh, - temp_extract_container_name, validate_linux_elf_binary, write_cache_binary_atomic, -}; -use openshell_core::gpu::{ - CdiGpuDefaultSelector, CdiGpuInventory, CdiGpuSelectionError, driver_gpu_requirements, - effective_driver_gpu_count, validate_cdi_gpu_device_request, -}; -use openshell_core::network_trust::{ - NETWORK_SUPERVISOR_TRUST_GENERATION_KEY, NETWORK_SUPERVISOR_TRUST_GENERATION_NONE, -}; -use openshell_core::proto::compute::v1::{ - CpuResourceCapabilities, DriverSandbox, GetCapabilitiesResponse, GpuResourceCapabilities, - GpuResourceRequirements, MemoryResourceCapabilities, ResourceCapabilities, -}; -use openshell_core::{ComputeDriverError, NetworkSupervisorTrustBundle}; -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Duration; - -use sha2::Digest; -use tracing::{Instrument as _, debug, info, warn}; - -const STOP_COMPLETION_POLL_INTERVAL: Duration = Duration::from_millis(50); -const STOP_COMPLETION_TIMEOUT_HEADROOM: Duration = Duration::from_secs(5); -const POLICY_DNS_RESOLV_CONF: &[u8] = b"nameserver 127.0.0.53\n"; - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum PodmanEndpointEnvironment { - LinuxHost, - PodmanMachine, -} - -impl PodmanEndpointEnvironment { - const fn current() -> Self { - if cfg!(target_os = "linux") { - Self::LinuxHost - } else { - Self::PodmanMachine - } - } - - const fn gateway_host(self) -> &'static str { - match self { - Self::LinuxHost => "127.0.0.1", - Self::PodmanMachine => "host.containers.internal", - } - } -} - -fn select_grpc_endpoint( - config: &PodmanComputeConfig, - environment: PodmanEndpointEnvironment, -) -> String { - if !config.grpc_endpoint.is_empty() { - return config.grpc_endpoint.clone(); - } - - let scheme = if config.tls_enabled() { - "https" - } else { - "http" - }; - format!( - "{scheme}://{}:{}", - environment.gateway_host(), - config.gateway_port - ) -} - -fn select_supervisor_otlp( - otlp: openshell_core::sandbox_env::SupervisorOtlp, - environment: PodmanEndpointEnvironment, -) -> openshell_core::sandbox_env::SupervisorOtlp { - otlp.map_endpoints(|endpoint| supervisor_collector_endpoint(&endpoint, environment)) -} - -/// Point a loopback collector endpoint at the desktop host on Podman Machine, -/// where supervisor loopback is the VM's. -fn supervisor_collector_endpoint(endpoint: &str, environment: PodmanEndpointEnvironment) -> String { - if environment == PodmanEndpointEnvironment::LinuxHost { - return endpoint.to_string(); - } - let Ok(mut url) = url::Url::parse(endpoint) else { - return endpoint.to_string(); - }; - let loopback = match url.host() { - Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"), - Some(url::Host::Ipv4(ip)) => ip.is_loopback(), - Some(url::Host::Ipv6(ip)) => ip.is_loopback(), - None => false, - }; - if !loopback || url.set_host(Some(environment.gateway_host())).is_err() { - return endpoint.to_string(); - } - let rewritten = String::from(url); - if endpoint.ends_with('/') { - rewritten - } else { - rewritten.trim_end_matches('/').to_string() - } -} - -fn decode_launch_authentication( - encoded: &[u8], -) -> Result { - let authentication = - serde_json::from_slice::(encoded) - .map_err(|error| { - ComputeDriverError::Precondition(format!( - "decode Podman sandbox launch authentication: {error}" - )) - })?; - authentication.validate().map_err(|error| { - ComputeDriverError::Precondition(format!( - "validate Podman sandbox launch authentication: {error}" - )) - })?; - Ok(authentication) -} - -impl From for ComputeDriverError { - fn from(value: PodmanApiError) -> Self { - match value { - PodmanApiError::Conflict(_) => Self::AlreadyExists, - PodmanApiError::NotFound(_) => Self::NotFound, - other => Self::Message(other.to_string()), - } - } -} - -/// Podman compute driver managing sandbox containers via the Podman REST API. -#[derive(Clone)] -pub struct PodmanComputeDriver { - client: PodmanClient, - config: PodmanComputeConfig, - gpu_selector: Arc, - gpu_inventory_refresh: Arc (CdiGpuInventory, bool) + Send + Sync>, - lifecycle_event_fences: LifecycleEventFences, - /// Gateway-normalized destination trust held outside untrusted sandbox - /// specs. Gateway-managed drivers receive the staged bundle from the - /// gateway; standalone drivers self-source one from the - /// `--sandbox-additional-ca-bundle` operator path. - network_trust: Option, - /// Keeps the driver-owned staging directory for an operator-supplied - /// additional CA bundle alive for the driver process lifetime. The - /// artifact inside it is bind-mounted into supervisors and re-verified - /// on every create/start. - network_trust_staging: Option>, -} - -impl std::fmt::Debug for PodmanComputeDriver { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("PodmanComputeDriver") - .field("socket_path", &self.config.socket_path) - .field("default_image", &self.config.default_image) - .field("network_name", &self.config.network_name) - .field("gpu_inventory", &self.gpu_selector.device_ids()) - .field( - "network_trust_staged", - &self.network_trust_staging.is_some(), - ) - .finish() - } -} - -struct ValidatedPodmanSandbox<'a> { - driver_config: PodmanSandboxDriverConfig, - gpu_requirements: Option<&'a GpuResourceRequirements>, -} - -/// Construct and validate a container name from a sandbox. -/// -/// Combines the prefix with workspace, name, and ID, then validates the -/// result against Podman's naming rules before any resources are created. -fn validated_container_name(sandbox: &DriverSandbox) -> Result { - let name = container::container_name(&sandbox.workspace, &sandbox.name, &sandbox.id); - crate::client::validate_name(&name) - .map_err(|e| ComputeDriverError::Precondition(e.to_string()))?; - Ok(name) -} - -/// Parse a numeric `uid:gid` container user. -fn numeric_user(user: &str) -> Option<(u32, u32)> { - let (uid, gid) = user.split_once(':')?; - Some((uid.parse().ok()?, gid.parse().ok()?)) -} - -fn podman_volume_is_bind_backed(volume: &VolumeInspect) -> bool { - (volume.driver.is_empty() || volume.driver == "local") - && volume.options.get("o").is_some_and(|options| { - options.split(',').any(|option| { - let option = option.trim(); - option.eq_ignore_ascii_case("bind") || option.eq_ignore_ascii_case("rbind") - }) - }) -} - -async fn create_sandbox_token_secret( - client: &PodmanClient, - sandbox: &DriverSandbox, -) -> Result, ComputeDriverError> { - let Some(token) = sandbox - .spec - .as_ref() - .map(|spec| spec.sandbox_token.trim()) - .filter(|token| !token.is_empty()) - else { - return Ok(None); - }; - - let secret_name = container::token_secret_name(&sandbox.id); - client - .create_secret(&secret_name, format!("{token}\n").as_bytes()) - .await - .map_err(ComputeDriverError::from)?; - Ok(Some(secret_name)) -} - -async fn cleanup_sandbox_token_secret(client: &PodmanClient, secret_name: &str) { - if let Err(err) = client.remove_secret(secret_name).await { - warn!( - secret = %secret_name, - error = %err, - "Failed to remove Podman sandbox token secret" - ); - } -} - -async fn create_sandbox_resolver_secret( - client: &PodmanClient, - sandbox_id: &str, -) -> Result { - let secret_name = container::resolver_secret_name(sandbox_id); - client - .create_secret(&secret_name, POLICY_DNS_RESOLV_CONF) - .await - .map_err(ComputeDriverError::from)?; - Ok(secret_name) -} - -async fn cleanup_sandbox_resolver_secret(client: &PodmanClient, secret_name: &str) { - if let Err(err) = client.remove_secret(secret_name).await { - warn!( - secret = %secret_name, - error = %err, - "Failed to remove Podman sandbox resolver secret" - ); - } -} - -/// Read the operator's proxy credentials file and stage it as a per-sandbox -/// Podman secret, so the credentials reach the supervisor through a root-only -/// mount rather than the container environment. -/// -/// Fails closed: when `proxy_auth_file` is configured but cannot be read or -/// does not hold a valid `user:pass` credential, the sandbox is not created. -/// Credential validation is shared with the in-container supervisor through -/// [`openshell_core::driver_utils::parse_upstream_proxy_credential`], so a -/// credential staged here can never be rejected at supervisor startup. -async fn create_sandbox_proxy_auth_secret( - client: &PodmanClient, - config: &PodmanComputeConfig, - sandbox: &DriverSandbox, -) -> Result, ComputeDriverError> { - let Some(path) = config.proxy_auth_file.as_deref() else { - return Ok(None); - }; - - // Bounded, blocking read shared with the supervisor: rejects non-regular - // files (e.g. /dev/zero) and caps the size so a hostile path cannot - // exhaust gateway memory. - let path_owned = path.to_string(); - let raw = tokio::task::spawn_blocking(move || { - openshell_core::driver_utils::read_upstream_proxy_credential_file(&path_owned) - }) - .await - .map_err(|e| ComputeDriverError::Message(format!("proxy_auth_file read task failed: {e}")))? - .map_err(ComputeDriverError::Message)?; - let credential = - openshell_core::driver_utils::parse_upstream_proxy_credential(&raw).map_err(|err| { - ComputeDriverError::InvalidArgument(format!("proxy_auth_file '{path}': {err}")) - })?; - - let secret_name = container::proxy_auth_secret_name(&sandbox.id); - client - .create_secret(&secret_name, format!("{credential}\n").as_bytes()) - .await - .map_err(ComputeDriverError::from)?; - Ok(Some(secret_name)) -} - -/// Fail-closed readability check for the corporate proxy CA bundle. -/// -/// When `proxy_ca_bundle` is configured the host PEM is bind-mounted read-only -/// into the sandbox; verifying up front that it exists and is a non-empty -/// regular file turns a missing path into a clear `proxy_ca_bundle` error at -/// sandbox-create time instead of an opaque bind-mount failure. The supervisor -/// independently validates the certificate content (fail-closed) at startup. -async fn validate_sandbox_proxy_ca_bundle( - config: &PodmanComputeConfig, -) -> Result<(), ComputeDriverError> { - let Some(path) = config.proxy_ca_bundle.as_deref() else { - return Ok(()); - }; - let path_owned = path.to_string(); - let metadata = tokio::task::spawn_blocking(move || std::fs::metadata(&path_owned)) - .await - .map_err(|e| ComputeDriverError::Message(format!("proxy_ca_bundle stat task failed: {e}")))? - .map_err(|err| { - ComputeDriverError::InvalidArgument(format!( - "proxy_ca_bundle '{path}' could not be read: {err}" - )) - })?; - if !metadata.is_file() { - return Err(ComputeDriverError::InvalidArgument(format!( - "proxy_ca_bundle '{path}' is not a regular file" - ))); - } - if metadata.len() == 0 { - return Err(ComputeDriverError::InvalidArgument(format!( - "proxy_ca_bundle '{path}' is empty" - ))); - } - Ok(()) -} - -async fn cleanup_sandbox_proxy_auth_secret(client: &PodmanClient, secret_name: &str) { - if let Err(err) = client.remove_secret(secret_name).await { - warn!( - secret = %secret_name, - error = %err, - "Failed to remove Podman sandbox proxy-auth secret" - ); - } -} - -async fn create_tls_secrets( - client: &PodmanClient, - config: &PodmanComputeConfig, - names: &[String; 1], -) -> Result<(), ComputeDriverError> { - let paths = [config.guest_tls_ca.as_deref()]; - let mut created = 0usize; - for (name, path) in names.iter().zip(paths.iter()) { - let Some(p) = path else { continue }; - let result = async { - let data = std::fs::read(p).map_err(|e| { - ComputeDriverError::Message(format!("read TLS file '{}': {e}", p.display())) - })?; - client - .create_secret(name, &data) - .await - .map_err(ComputeDriverError::from) - } - .await; - if let Err(e) = result { - for prev in &names[..created] { - let _ = client.remove_secret(prev).await; - } - return Err(e); - } - created += 1; - } - Ok(()) -} - -async fn cleanup_tls_secrets(client: &PodmanClient, names: &[String]) { - for name in names { - if let Err(err) = client.remove_secret(name).await { - warn!( - secret = %name, - error = %err, - "Failed to remove TLS secret" - ); - } - } -} - -fn local_podman_cdi_gpu_inventory_from(dev_root: &Path) -> CdiGpuInventory { - let mut device_ids = std::fs::read_dir(dev_root) - .ok() - .into_iter() - .flat_map(|entries| entries.filter_map(Result::ok)) - .filter_map(|entry| { - let name = entry.file_name(); - let name = name.to_str()?; - let index = name.strip_prefix("nvidia")?; - (!index.is_empty() && index.chars().all(|ch| ch.is_ascii_digit())) - .then(|| format!("nvidia.com/gpu={index}")) - }) - .collect::>(); - if local_podman_all_gpu_default_supported_from(dev_root) { - device_ids.push(CDI_GPU_DEVICE_ALL.to_string()); - } - - CdiGpuInventory::new(device_ids) -} - -fn local_podman_cdi_gpu_inventory() -> CdiGpuInventory { - local_podman_cdi_gpu_inventory_from(Path::new("/dev")) -} - -fn local_podman_all_gpu_default_supported_from(dev_root: &Path) -> bool { - dev_root.join("dxg").exists() -} - -fn local_podman_all_gpu_default_supported() -> bool { - local_podman_all_gpu_default_supported_from(Path::new("/dev")) -} - -fn local_podman_gpu_selector_state() -> (CdiGpuInventory, bool) { - ( - local_podman_cdi_gpu_inventory(), - local_podman_all_gpu_default_supported(), - ) -} - -fn podman_gpu_selection_error(err: CdiGpuSelectionError) -> ComputeDriverError { - ComputeDriverError::Precondition(err.to_string()) -} - -/// Return the first responsive local Podman API socket. -#[must_use] -pub fn detect_socket() -> Option { - openshell_container_runtime::podman_socket::detect_socket() -} - -#[must_use] -pub fn is_available() -> bool { - detect_socket().is_some() -} - -/// Check that Podman is reachable with `config`: resolve the socket, honouring -/// `socket_path` and `OPENSHELL_PODMAN_SOCKET`, and ping it. Creates nothing. -pub async fn check_backend(config: &PodmanComputeConfig) -> Result<(), PodmanApiError> { - let socket_path = resolve_socket_path(config.socket_path.clone(), detect_socket)?; - PodmanClient::new(socket_path).ping().await -} - -/// Resolve the socket to connect to: explicit configuration wins, otherwise -/// fall back to `detect`. Returns an error if neither resolves. -/// -/// Takes `detect` as a parameter so tests can -/// exercise the precedence deterministically, without touching real -/// environment variables or the filesystem. -fn resolve_socket_path( - configured: Option, - detect: impl FnOnce() -> Option, -) -> Result { - configured.or_else(detect).ok_or_else(|| { - PodmanApiError::InvalidInput( - "no responsive Podman API socket found; set OPENSHELL_PODMAN_SOCKET \ - or configure socket_path" - .to_string(), - ) - }) -} - -/// Build destination trust from an operator-supplied standalone bundle path. -/// -/// Standalone (non-gateway) drivers accept `--sandbox-additional-ca-bundle` -/// directly. The file is read with the same bounded, no-symlink validation -/// the gateway applies to its own configured bundle, and a SHA-256 digest of -/// the material becomes the trust generation so stop/start reconciliation -/// behaves identically to gateway-managed deployments. The operator-owned -/// source keeps its own permissions; the normalized material is staged into -/// a driver-owned `0444` artifact so the immutable-artifact verification -/// every later create/start performs accepts it. -fn operator_network_trust( - path: &str, -) -> Result<(NetworkSupervisorTrustBundle, tempfile::TempDir), PodmanApiError> { - let pem = openshell_core::driver_utils::read_upstream_proxy_ca_bundle_file( - path, - "additional_ca_bundle", - ) - .map_err(PodmanApiError::InvalidInput)?; - let certificate_count = pem.matches("-----BEGIN CERTIFICATE-----").count(); - // Deterministic destination-trust generation label, not an authenticity - // proof: trust comes from the bounded validation above, the immutable - // staged artifact, and TLS verification. Classified as a non-security - // identity hash in openshell-crypto/README.md. - let digest = format!("sha256:{:x}", sha2::Sha256::digest(pem.as_bytes())); - - let staging = tempfile::tempdir().map_err(|error| { - PodmanApiError::InvalidInput(format!("create additional CA staging directory: {error}")) - })?; - let artifact_path = staging.path().join("additional-ca.crt"); - stage_operator_network_trust_artifact(&artifact_path, pem.as_bytes())?; - Ok(( - NetworkSupervisorTrustBundle::new( - pem.into_bytes(), - certificate_count, - digest, - artifact_path, - ), - staging, - )) -} - -/// Write the normalized operator material as a read-only, regular artifact. -/// -/// The file is created writable-private and only then made immutable so no -/// observer ever sees a world-writable artifact; the staging directory itself -/// is process-private (`0700`). -fn stage_operator_network_trust_artifact( - artifact_path: &Path, - normalized: &[u8], -) -> Result<(), PodmanApiError> { - use std::io::Write as _; - let mut options = std::fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt as _; - options.mode(0o600); - } - let mut file = options.open(artifact_path).map_err(|error| { - PodmanApiError::InvalidInput(format!( - "create additional CA artifact '{}': {error}", - artifact_path.display() - )) - })?; - file.write_all(normalized) - .and_then(|()| file.sync_all()) - .map_err(|error| { - PodmanApiError::InvalidInput(format!( - "write additional CA artifact '{}': {error}", - artifact_path.display() - )) - })?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - std::fs::set_permissions(artifact_path, std::fs::Permissions::from_mode(0o444)).map_err( - |error| { - PodmanApiError::InvalidInput(format!( - "restrict additional CA artifact '{}': {error}", - artifact_path.display() - )) - }, - )?; - } - Ok(()) -} - -impl PodmanComputeDriver { - /// Create a new driver, verifying the Podman socket is reachable. - pub async fn new( - mut config: PodmanComputeConfig, - network_trust: Option, - ) -> Result { - const MAX_PING_RETRIES: u32 = 5; - const PING_RETRY_DELAY: Duration = Duration::from_secs(2); - - let socket_path = resolve_socket_path(config.socket_path.clone(), detect_socket)?; - config.socket_path = Some(socket_path.clone()); - - let (network_trust, network_trust_staging) = - match (network_trust, config.additional_ca_bundle.as_deref()) { - (Some(_), Some(path)) => { - return Err(PodmanApiError::InvalidInput(format!( - "destination CA trust was supplied both by the gateway and through \ - --sandbox-additional-ca-bundle ('{path}'); configure exactly one source" - ))); - } - (Some(bundle), None) => (Some(bundle), None), - (None, Some(path)) => { - let (bundle, staging) = operator_network_trust(path)?; - (Some(bundle), Some(Arc::new(staging))) - } - (None, None) => (None, None), - }; - - if !socket_path.exists() { - if cfg!(target_os = "macos") { - warn!( - path = %socket_path.display(), - "Podman socket not found; is podman machine running? \ - Try `podman machine start` or set OPENSHELL_PODMAN_SOCKET to override." - ); - } else { - warn!( - path = %socket_path.display(), - "Podman socket not found; is the Podman service running? \ - Set OPENSHELL_PODMAN_SOCKET or XDG_RUNTIME_DIR to override." - ); - } - } - - // Validate and normalize configuration before connecting. Partial TLS - // and invalid resource, proxy, SPIFFE, AppArmor, or userns settings - // fail before the runtime is contacted. - config.validate_configuration()?; - - let client = PodmanClient::new(socket_path); - - // Verify connectivity, retrying briefly to tolerate transient socket - // unavailability (e.g. podman.socket restarting after a package - // upgrade). The systemd unit uses Wants=podman.socket (not Requires), - // so the gateway may start while the socket is briefly re-activating. - let mut attempts = 0; - loop { - match client.ping().await { - Ok(()) => break, - Err(e) if attempts < MAX_PING_RETRIES => { - attempts += 1; - warn!( - attempt = attempts, - max_retries = MAX_PING_RETRIES, - error = %e, - "Podman socket not ready, retrying" - ); - tokio::time::sleep(PING_RETRY_DELAY).await; - } - Err(e) => return Err(e), - } - } - - // Verify cgroups v2, detect rootless mode, and log system info. - match client.system_info().await { - Ok(info) => { - if info.host.cgroup_version != "v2" { - return Err(PodmanApiError::Connection(format!( - "cgroups v2 is required; detected cgroups '{}'. \ - Ensure your host uses a unified cgroup hierarchy \ - (systemd.unified_cgroup_hierarchy=1).", - info.host.cgroup_version - ))); - } - validate_apparmor_support( - config.app_armor_profile.as_ref(), - info.host.security.apparmor_enabled, - )?; - info!( - cgroup_version = %info.host.cgroup_version, - network_backend = %info.host.network_backend, - rootless = info.host.security.rootless, - rootless_network_cmd = %info.host.rootless_network_cmd, - apparmor_enabled = info.host.security.apparmor_enabled, - "Connected to Podman" - ); - } - Err(e) => { - return Err(PodmanApiError::Connection(format!( - "failed to query Podman system info: {e}" - ))); - } - } - - // Rootless pre-flight: warn if subuid/subgid ranges look missing. - // Not a hard error because some systems configure these via LDAP or - // other mechanisms that /etc/subuid does not reflect. - if !cfg!(target_os = "macos") && rustix::process::getuid().as_raw() != 0 { - check_subuid_range(); - } - - // The supervisor shares the Podman host network. Linux supervisors can - // therefore use gateway loopback directly; Podman Machine retains its - // standard desktop-host alias. - let endpoint_was_selected = config.grpc_endpoint.is_empty(); - config.grpc_endpoint = select_grpc_endpoint(&config, PodmanEndpointEnvironment::current()); - config.supervisor_otlp = select_supervisor_otlp( - std::mem::take(&mut config.supervisor_otlp), - PodmanEndpointEnvironment::current(), - ); - if endpoint_was_selected { - info!( - grpc_endpoint = %config.grpc_endpoint, - tls = config.tls_enabled(), - "Auto-detected gRPC endpoint" - ); - } - - client.ensure_network(&config.network_name).await?; - info!(network = %config.network_name, "Podman network ready"); - - let (gpu_inventory, allow_all_default_gpu) = local_podman_gpu_selector_state(); - if !gpu_inventory.is_empty() { - info!( - device_count = gpu_inventory.as_slice().len(), - "Discovered local Podman NVIDIA CDI GPU devices" - ); - } - - let driver = Self { - client, - config, - gpu_selector: Arc::new(CdiGpuDefaultSelector::new( - gpu_inventory, - allow_all_default_gpu, - )), - gpu_inventory_refresh: Arc::new(local_podman_gpu_selector_state), - lifecycle_event_fences: LifecycleEventFences::default(), - network_trust, - network_trust_staging, - }; - let reconciler = driver.clone(); - tokio::spawn(async move { - loop { - reconciler.reconcile_resource_admission().await; - tokio::time::sleep(Duration::from_secs(30)).await; - } - }); - Ok(driver) - } - - /// Report driver capabilities. - pub fn capabilities(&self) -> Result { - Ok(GetCapabilitiesResponse { - resource_admission_policy: openshell_core::resource_admission::DriverAdmissionConfig { - allow_driver_config: self.config.allow_driver_config, - resource_admission: self.config.resource_admission.clone(), - } - .acknowledgement(), - driver_name: "podman".to_string(), - driver_version: openshell_core::VERSION.to_string(), - default_image: self.config.default_image.clone(), - gateway_manages_lifecycle: true, - supports_sandbox_authentication: false, - driver_reports_runtime_readiness: false, - resource_capabilities: Some(ResourceCapabilities { - cpu: Some(CpuResourceCapabilities { - limit_supported: true, - }), - memory: Some(MemoryResourceCapabilities { - limit_supported: true, - }), - gpu: Some(GpuResourceCapabilities { - default_selection_supported: true, - count_selection_supported: true, - }), - }), - rootfs_tar_staging_dir: String::new(), - rootfs_tar_max_bytes: 0, - extension: Some(openshell_core::extension_protocol::extension_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - "openshell/podman", - openshell_core::VERSION, - [], - )), - }) - } - - #[must_use] - pub fn default_image(&self) -> &str { - &self.config.default_image - } - - /// Validate a sandbox before creation. - pub async fn validate_sandbox_create( - &self, - sandbox: &DriverSandbox, - ) -> Result<(), ComputeDriverError> { - let _ = self.validated_sandbox_create(sandbox).await?; - Ok(()) - } - - async fn validated_sandbox_create<'a>( - &self, - sandbox: &'a DriverSandbox, - ) -> Result, ComputeDriverError> { - openshell_core::resource_admission::check_sandbox_driver_config( - self.config.allow_driver_config, - sandbox, - ) - .map_err(|error| ComputeDriverError::Precondition(error.message().into()))?; - let gpu_requirements = sandbox - .spec - .as_ref() - .and_then(|spec| spec.resource_requirements.as_ref()) - .and_then(|requirements| driver_gpu_requirements(Some(requirements))); - let driver_config = PodmanSandboxDriverConfig::from_sandbox(sandbox)?; - driver_config.admit_mount_types(&self.config.resource_admission)?; - Self::validate_gpu_request(gpu_requirements, &driver_config)?; - self.validate_user_volume_mounts_available(sandbox).await?; - let _ = self.resolve_gpu_cdi_devices( - gpu_requirements, - &driver_config, - CdiGpuDefaultSelector::peek_device_ids, - )?; - Ok(ValidatedPodmanSandbox { - driver_config, - gpu_requirements, - }) - } - - fn validate_gpu_request( - gpu_requirements: Option<&GpuResourceRequirements>, - driver_config: &PodmanSandboxDriverConfig, - ) -> Result<(), ComputeDriverError> { - let _ = effective_driver_gpu_count(gpu_requirements) - .map_err(ComputeDriverError::InvalidArgument)?; - if let Some(cdi_devices) = driver_config.cdi_devices.as_deref() { - validate_cdi_gpu_device_request( - gpu_requirements, - cdi_devices, - "driver_config.cdi_devices", - ) - .map_err(ComputeDriverError::InvalidArgument)?; - } - - Ok(()) - } - - fn refresh_gpu_inventory(&self) { - let (inventory, allow_all_default_gpu) = (self.gpu_inventory_refresh)(); - self.gpu_selector.refresh(inventory, allow_all_default_gpu); - } - - fn resolve_gpu_cdi_devices( - &self, - gpu_requirements: Option<&GpuResourceRequirements>, - driver_config: &PodmanSandboxDriverConfig, - select_default_devices: fn( - &CdiGpuDefaultSelector, - u32, - ) -> Result, CdiGpuSelectionError>, - ) -> Result>, ComputeDriverError> { - if let Some(cdi_devices) = driver_config.cdi_devices.as_deref() { - validate_cdi_gpu_device_request( - gpu_requirements, - cdi_devices, - "driver_config.cdi_devices", - ) - .map_err(ComputeDriverError::InvalidArgument)?; - return Ok(Some(cdi_devices.to_vec())); - } - - let Some(count) = effective_driver_gpu_count(gpu_requirements) - .map_err(ComputeDriverError::InvalidArgument)? - else { - return Ok(None); - }; - - self.refresh_gpu_inventory(); - select_default_devices(&self.gpu_selector, count) - .map(Some) - .map_err(podman_gpu_selection_error) - } - - async fn validate_user_volume_mounts_available( - &self, - sandbox: &DriverSandbox, - ) -> Result, ComputeDriverError> { - let mut identities = std::collections::BTreeMap::new(); - let volumes = - container::podman_driver_volume_mount_sources(sandbox, self.config.enable_bind_mounts) - .map_err(ComputeDriverError::Precondition)?; - for volume in volumes { - match self.client.inspect_volume(&volume).await { - Ok(volume_info) => { - identities.insert(volume.clone(), volume_info.admission_identity()); - self.config - .resource_admission - .admit( - &sandbox.workspace, - volume_info - .labels - .as_ref() - .into_iter() - .flat_map(|labels| labels.iter()), - ) - .map_err(|error| { - ComputeDriverError::Precondition(format!( - "podman volume '{volume}': {}", - error.message() - )) - })?; - if !self.config.enable_bind_mounts && podman_volume_is_bind_backed(&volume_info) - { - return Err(ComputeDriverError::Precondition(format!( - "podman volume '{volume}' is backed by a host bind mount and requires enable_bind_mounts = true in [openshell.drivers.podman]" - ))); - } - } - Err(PodmanApiError::NotFound(_)) => { - return Err(ComputeDriverError::Precondition(format!( - "podman volume '{volume}' does not exist" - ))); - } - Err(err) => return Err(ComputeDriverError::from(err)), - } - } - Ok(identities) - } - - /// Create a sandbox container. - async fn admit_container_resources(&self, id: &str) -> Result<(), ComputeDriverError> { - if self.config.allow_driver_config && !self.config.resource_admission.enabled { - return Ok(()); - } - let inspect = self.client.inspect_container(id).await?; - let labels = &inspect.config.labels; - let precondition = - |error: tonic::Status| ComputeDriverError::Precondition(error.message().into()); - openshell_core::resource_admission::check_config_provenance( - self.config.allow_driver_config, - labels - .get(openshell_core::resource_admission::CONFIG_USED_LABEL) - .map(String::as_str), - ) - .map_err(precondition)?; - if !self.config.resource_admission.enabled { - return Ok(()); - } - let missing = - || ComputeDriverError::Precondition("sandbox lacks attachment provenance".into()); - let workspace = labels - .get(container::LABEL_SANDBOX_WORKSPACE) - .ok_or_else(missing)?; - let sandbox_id = labels.get(LABEL_SANDBOX_ID).ok_or_else(missing)?; - let mounts = inspect.mounts.as_ref().ok_or_else(missing)?; - let expected: std::collections::BTreeMap = labels - .get(openshell_core::resource_admission::IDENTITIES_LABEL) - .and_then(|value| serde_json::from_str(value).ok()) - .ok_or_else(missing)?; - let mut actual = std::collections::BTreeMap::new(); - for mount in mounts { - match mount["Type"].as_str() { - Some("volume") => { - let name = mount["Name"].as_str().ok_or_else(missing)?; - let volume = - self.client - .inspect_volume(name) - .await - .map_err(|error| match error { - PodmanApiError::NotFound(_) => ComputeDriverError::Precondition( - "attached volume no longer exists".into(), - ), - other => ComputeDriverError::from(other), - })?; - if volume.name != name { - return Err(missing()); - } - let workspace_volume = name == container::volume_name(sandbox_id); - if workspace_volume - || name == crate::isolation::channel_volume_name(sandbox_id) - || name == crate::isolation::control_volume_name(sandbox_id) - { - let owned = volume.labels.as_ref().is_some_and(|labels| { - labels.get(LABEL_SANDBOX_ID) == Some(sandbox_id) - && labels.get(container::LABEL_SANDBOX_WORKSPACE) == Some(workspace) - }); - // The channel volume has no options. The managed - // workspace is owned by the container's final identity, - // or has no options when an older gateway created it. - let options_ok = volume.options.is_empty() - || (workspace_volume - && numeric_user(&inspect.config.user).is_some_and(|owner| { - volume.options_match_requested_owner(Some(owner)) - })); - if !owned || volume.driver != "local" || !options_ok { - return Err(missing()); - } - } else { - actual.insert(name.to_string(), volume.admission_identity()); - self.config - .resource_admission - .admit( - workspace, - volume - .labels - .as_ref() - .into_iter() - .flat_map(|labels| labels.iter()), - ) - .map_err(|error| { - ComputeDriverError::Precondition(format!( - "podman volume '{name}': {}", - error.message() - )) - })?; - if !self.config.enable_bind_mounts && podman_volume_is_bind_backed(&volume) - { - return Err(ComputeDriverError::Precondition( - "bind-backed volume is disabled".into(), - )); - } - } - } - Some("tmpfs") => {} - Some("bind") - if mount["Destination"].as_str() - == Some(openshell_core::driver_utils::SUPERVISOR_CONTAINER_BINARY) - && mount["RW"].as_bool() == Some(false) - && labels - .get("openshell.ai/runtime-binary-source") - .filter(|path| !path.is_empty()) - .map(String::as_str) - == mount["Source"].as_str() => {} - _ => self - .config - .resource_admission - .reject_unlabelable("effective Podman mount") - .map_err(precondition)?, - } - } - if actual != expected { - return Err(ComputeDriverError::Precondition( - "external volume identity or attachment inventory changed".into(), - )); - } - Ok(()) - } - - /// Revalidate running grants every 30 seconds. Outages block launches but - /// only confirmed denials stop existing workloads. - async fn reconcile_resource_admission(&self) { - let Ok(entries) = self - .client - .list_containers(&[LABEL_MANAGED_FILTER, crate::isolation::WORKLOAD_FILTER]) - .await - else { - return; - }; - for entry in entries.iter().filter(|entry| entry.state == "running") { - if let Err(ComputeDriverError::Precondition(reason)) = - self.admit_container_resources(&entry.id).await - { - warn!(container = %entry.id, %reason, "Stopping sandbox after resource admission denial"); - let _ = self.client.stop_container(&entry.id, 0).await; - if let Some(id) = entry.labels.get(LABEL_SANDBOX_ID) { - let _ = self - .client - .stop_container(&crate::isolation::supervisor_name(id), 0) - .await; - } - } - } - } - - fn verify_network_trust(&self) -> Result<(), ComputeDriverError> { - if let Some(bundle) = self.network_trust.as_ref() { - bundle.verify_artifact().map_err(|error| { - ComputeDriverError::Precondition(format!( - "verify gateway-owned network additional CA artifact: {error}" - )) - })?; - } - Ok(()) - } - - fn expected_network_trust_generation(&self) -> &str { - self.network_trust.as_ref().map_or( - NETWORK_SUPERVISOR_TRUST_GENERATION_NONE, - NetworkSupervisorTrustBundle::digest, - ) - } - - /// Create a sandbox container. - #[tracing::instrument( - name = "podman.provision", - skip(self, sandbox), - fields( - otel.name = "podman.provision", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox.id, - sandbox.name = %sandbox.name, - ) - )] - pub async fn create_sandbox(&self, sandbox: &DriverSandbox) -> Result<(), ComputeDriverError> { - self.create_sandbox_with_existing_token(sandbox, None, None, None) - .await - } - - /// Provision a replacement while retaining the existing token secret. - /// Only stopped-pair reconciliation uses this; ordinary creates always - /// generate their own secret from the gateway's create credential. - async fn create_sandbox_with_existing_token( - &self, - sandbox: &DriverSandbox, - existing_token_secret: Option<&str>, - restart_generation: Option<&str>, - existing_workload_container_id: Option<&str>, - ) -> Result<(), ComputeDriverError> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let reuse_existing_resources = restart_generation.is_some(); - let restart_generation = - restart_generation.map_or_else(|| uuid::Uuid::new_v4().to_string(), ToOwned::to_owned); - // The same immutable gateway snapshot is verified immediately before - // any workload/supervisor pair is admitted. Do not turn a tampered - // artifact into a runtime-only supervisor failure. - self.verify_network_trust()?; - if sandbox.name.is_empty() { - return Err(ComputeDriverError::Precondition( - "sandbox name is required".into(), - )); - } - if sandbox.id.is_empty() { - return Err(ComputeDriverError::Precondition( - "sandbox id is required".into(), - )); - } - - // Validate the composed container name early, before creating any - // resources (volume), so we don't leave orphans when the name is - // invalid. - let name = validated_container_name(sandbox)?; - let validated = self.validated_sandbox_create(sandbox).await?; - - let vol_name = container::volume_name(&sandbox.id); - - info!( - sandbox_id = %sandbox.id, - sandbox_name = %sandbox.name, - container = %name, - "Creating sandbox container" - ); - - let resolved_image = async { - let phase_status = openshell_otel::ErrorStatusGuard::current(); - let result = async { - // The sandbox runtime is shipped in a standalone OCI image. - // The driver extracts and verifies its binary before bind-mounting - // it into the workload container. - let sandbox_runtime_pull_policy = - runtime_image_pull_policy(&self.config.sandbox_runtime_image); - info!( - image = %self.config.sandbox_runtime_image, - policy = sandbox_runtime_pull_policy, - "Ensuring sandbox runtime image" - ); - self.client - .pull_image( - &self.config.sandbox_runtime_image, - sandbox_runtime_pull_policy, - ) - .await - .map_err(ComputeDriverError::from)?; - - let supervisor_pull_policy = - runtime_image_pull_policy(&self.config.supervisor_image); - info!( - image = %self.config.supervisor_image, - policy = supervisor_pull_policy, - "Ensuring supervisor image" - ); - self.client - .pull_image(&self.config.supervisor_image, supervisor_pull_policy) - .await - .map_err(ComputeDriverError::from)?; - - // Podman does not pull the sandbox image on container creation. - let image = container::resolve_image(sandbox, &self.config); - if image.is_empty() { - return Err(ComputeDriverError::Precondition( - "no sandbox image configured: set default_image in \ - [openshell.drivers.podman] or provide an image in the sandbox template" - .to_string(), - )); - } - let pull_policy = podman_image_pull_policy(self.config.image_pull_policy); - let resolved_image = if let Some(existing) = existing_workload_container_id { - self.resolve_retained_workload_image(existing, image).await? - } else { - info!(image = %image, policy = %pull_policy, "Ensuring sandbox image"); - self.client - .pull_image(image, pull_policy) - .await - .map_err(ComputeDriverError::from)?; - let inspected_image = self - .client - .inspect_image(image) - .await - .map_err(ComputeDriverError::from)?; - if inspected_image.id.is_empty() { - return Err(ComputeDriverError::Precondition(format!( - "podman image '{image}' inspection did not return an immutable image ID" - ))); - } - container::ResolvedPodmanImage::from_inspect(image, inspected_image)? - }; - - for mount_image in container::podman_driver_image_mount_sources( - sandbox, - self.config.enable_bind_mounts, - ) - .map_err(ComputeDriverError::Precondition)? - { - info!(image = %mount_image, policy = %pull_policy, "Ensuring image mount source"); - self.client - .pull_image(&mount_image, pull_policy) - .await - .map_err(ComputeDriverError::from)?; - } - - Ok(resolved_image) - } - .await; - phase_status.finish(result) - } - .instrument(tracing::info_span!( - "podman.prepare_images", - otel.name = "podman.prepare_images", - otel.status_code = tracing::field::Empty, - )) - .await?; - let managed_workspace = resolved_image.uses_managed_workspace(); - - // Fail closed on a missing/unreadable corporate proxy CA bundle before - // creating any resources, so the operator gets a clear error - // attributable to `proxy_ca_bundle` rather than an opaque bind-mount - // failure. The supervisor independently validates the certificate - // content at startup. - validate_sandbox_proxy_ca_bundle(&self.config).await?; - let host_gateway_ip = self - .config - .resolved_host_gateway_ip() - .map_err(ComputeDriverError::from)?; - - let identity = self - .resolve_workload_identity(sandbox, &resolved_image.id, &resolved_image.oci_user) - .await?; - let channel_volume = crate::isolation::channel_volume_name(&sandbox.id); - let control_volume = crate::isolation::control_volume_name(&sandbox.id); - let mut runtime_config = self.config.clone(); - runtime_config.sandbox_runtime_image = self - .client - .inspect_image(&self.config.sandbox_runtime_image) - .await? - .id; - if runtime_config.sandbox_runtime_image.is_empty() { - return Err(ComputeDriverError::Precondition( - "sandbox runtime image inspection returned no immutable image ID".into(), - )); - } - runtime_config.supervisor_image = self - .client - .inspect_image(&self.config.supervisor_image) - .await? - .id; - if runtime_config.supervisor_image.is_empty() { - return Err(ComputeDriverError::Precondition( - "supervisor image inspection returned no immutable image ID".into(), - )); - } - - // Create the workspace volume and per-sandbox runtime files. During a - // stopped trust replacement, retain the named resources belonging to - // the old pair and reuse its resolver/token secrets. - let ( - resolver_secret_name, - resolver_secret_owned, - token_secret_name, - proxy_auth_secret_name, - ) = async { - let phase_status = openshell_otel::ErrorStatusGuard::current(); - let result = async { - if !reuse_existing_resources && managed_workspace { - self.client - .create_owned_volume( - &vol_name, - &sandbox.id, - &sandbox.workspace, - Some((identity.uid, identity.gid)), - ) - .await - .map_err(ComputeDriverError::from)?; - } - let resolver_secret_name = container::resolver_secret_name(&sandbox.id); - let resolver_secret_owned = if reuse_existing_resources { - if !self - .client - .secret_exists(&resolver_secret_name) - .await - .map_err(ComputeDriverError::from)? - { - return Err(ComputeDriverError::Precondition( - "Podman trust replacement requires the existing resolver secret".into(), - )); - } - false - } else { - create_sandbox_resolver_secret(&self.client, &sandbox.id).await?; - true - }; - let token_secret_name = if let Some(secret) = existing_token_secret { - // The durable gateway Sandbox intentionally does not - // contain the bearer token. Reuse its per-sandbox - // secret after the old stopped workload is renamed. - Some(secret.to_string()) - } else { - match create_sandbox_token_secret(&self.client, sandbox).await { - Ok(name) => name, - Err(e) => { - if !reuse_existing_resources { - if managed_workspace { - let _ = self - .client - .remove_owned_volume(&vol_name, &sandbox.id) - .await; - } - if resolver_secret_owned { - cleanup_sandbox_resolver_secret( - &self.client, - &resolver_secret_name, - ) - .await; - } - } - return Err(e); - } - } - }; - let proxy_auth_secret_name = - match create_sandbox_proxy_auth_secret(&self.client, &self.config, sandbox) - .await - { - Ok(name) => name, - Err(e) => { - if !reuse_existing_resources && managed_workspace { - let _ = self - .client - .remove_owned_volume(&vol_name, &sandbox.id) - .await; - } - if existing_token_secret.is_none() - && let Some(secret) = token_secret_name.as_deref() - { - cleanup_sandbox_token_secret(&self.client, secret).await; - } - if resolver_secret_owned { - cleanup_sandbox_resolver_secret( - &self.client, - &resolver_secret_name, - ) - .await; - } - return Err(e); - } - }; - Ok(( - resolver_secret_name, - resolver_secret_owned, - token_secret_name, - proxy_auth_secret_name, - )) - } - .await; - phase_status.finish(result) - } - .instrument(tracing::info_span!( - "podman.prepare_storage", - otel.name = "podman.prepare_storage", - otel.status_code = tracing::field::Empty, - volume.name = %vol_name, - )) - .await?; - - // Clean up the volume and per-sandbox secrets on any failure past this - // point. Resources retained for a stopped trust replacement are left - // intact so the rollback path can restore the old pair. - let channel_owned = std::sync::atomic::AtomicBool::new(false); - let control_owned = std::sync::atomic::AtomicBool::new(false); - let cleanup_created = || async { - if !reuse_existing_resources && channel_owned.load(std::sync::atomic::Ordering::Relaxed) - { - let _ = self - .client - .remove_owned_volume(&channel_volume, &sandbox.id) - .await; - } - if !reuse_existing_resources && control_owned.load(std::sync::atomic::Ordering::Relaxed) - { - let _ = self - .client - .remove_owned_volume(&control_volume, &sandbox.id) - .await; - } - if !reuse_existing_resources && managed_workspace { - let _ = self - .client - .remove_owned_volume(&vol_name, &sandbox.id) - .await; - } - if resolver_secret_owned { - cleanup_sandbox_resolver_secret(&self.client, &resolver_secret_name).await; - } - if existing_token_secret.is_none() - && let Some(secret) = token_secret_name.as_deref() - { - cleanup_sandbox_token_secret(&self.client, secret).await; - } - if let Some(secret) = proxy_auth_secret_name.as_deref() { - cleanup_sandbox_proxy_auth_secret(&self.client, secret).await; - } - }; - - // Prepare and create the container. - async { - let phase_status = openshell_otel::ErrorStatusGuard::current(); - let result = async { - let gpu_devices = match self.resolve_gpu_cdi_devices( - validated.gpu_requirements, - &validated.driver_config, - CdiGpuDefaultSelector::next_device_ids, - ) { - Ok(devices) => devices, - Err(e) => { - cleanup_created().await; - return Err(e); - } - }; - // Podman's image-volume support varies across libpod/runtime - // combinations. Always use the verified extraction cache so - // workload startup does not depend on type=image mounts. - let supervisor_bin_path = - match extract_sandbox_bin(&self.client, &runtime_config).await { - Ok(path) => Some(path), - Err(e) => { - cleanup_created().await; - return Err(e); - } - }; - - let tls_secret_names = self - .config - .tls_enabled() - .then(|| container::tls_secret_names(&sandbox.id)); - let tls_secrets_owned = if let Some(names) = &tls_secret_names { - if reuse_existing_resources { - // The renamed stopped pair still owns the per-sandbox - // TLS secret under the same sandbox id, and the - // gateway CA it carries is unchanged; the replacement - // pair reuses it instead of colliding on the name. - if !self - .client - .secret_exists(&names[0]) - .await - .map_err(ComputeDriverError::from)? - { - return Err(ComputeDriverError::Precondition( - "Podman trust replacement requires the existing TLS CA secret" - .into(), - )); - } - false - } else { - if let Err(e) = create_tls_secrets(&self.client, &self.config, names).await - { - cleanup_created().await; - return Err(e); - } - true - } - } else { - false - }; - - let cleanup_all = || async { - cleanup_created().await; - if tls_secrets_owned && let Some(names) = &tls_secret_names { - cleanup_tls_secrets(&self.client, names).await; - } - }; - - let specs = container::build_isolation_specs(container::IsolationSpecInput { - sandbox, - config: &runtime_config, - token_secret: token_secret_name.as_deref(), - resolver_secret: &resolver_secret_name, - gpu_devices: gpu_devices.as_deref(), - image: &resolved_image, - supervisor_bin: supervisor_bin_path.as_deref(), - tls_secrets: tls_secret_names.as_ref(), - network_trust: self.network_trust.as_ref(), - identity: &identity, - }); - let mut specs = match specs { - Ok(spec) => spec, - Err(e) => { - cleanup_all().await; - return Err(e); - } - }; - let mut created_workload = None; - let mut created_supervisor = None; - let create_result = async { - let identities = self.validate_user_volume_mounts_available(sandbox).await?; - specs.record_resource_identities(&identities)?; - if !reuse_existing_resources { - self.client - .create_owned_volume( - &channel_volume, - &sandbox.id, - &sandbox.workspace, - None, - ) - .await?; - channel_owned.store(true, std::sync::atomic::Ordering::Relaxed); - self.client - .create_owned_volume( - &control_volume, - &sandbox.id, - &sandbox.workspace, - None, - ) - .await?; - control_owned.store(true, std::sync::atomic::Ordering::Relaxed); - } - // Supervisor-only trust reconciliation reuses the stopped - // workload container together with its volumes, secrets, - // and workspace data. Only the supervisor is replaced. - let workload_id = if let Some(existing) = existing_workload_container_id { - existing.to_string() - } else { - let id = self.client.create_typed_container(&specs.workload).await?; - created_workload = Some(id.clone()); - id - }; - self.client.verify_isolation_fence(&workload_id).await?; - self.admit_container_resources(&workload_id).await?; - let child_env = podman_child_environment(sandbox, &resolved_image.environment); - let launch_authentication = sandbox - .spec - .as_ref() - .filter(|spec| !spec.launch_authentication.is_empty()) - .ok_or_else(|| { - ComputeDriverError::Precondition( - "Podman sandbox launch authentication is required".to_string(), - ) - }) - .and_then(|spec| { - decode_launch_authentication(&spec.launch_authentication) - })?; - let archives = crate::isolation::bootstrap_archives( - crate::isolation::BootstrapArchivesInput { - runtime_initiated: true, - sandbox_id: &sandbox.id, - container_id: &workload_id, - generation: &restart_generation, - host_gateway_ip, - identity: &identity, - allow_extra_supplementary_groups: - crate::isolation::userns_preserves_host_groups( - self.config.userns.as_deref(), - ), - child_env, - launch_authentication: &launch_authentication, - }, - )?; - self.client - .copy_to_container( - &workload_id, - crate::isolation::CHANNEL_ROOT, - archives.channel, - ) - .await?; - if let Some(control) = archives.control { - self.client - .copy_to_container( - &workload_id, - crate::isolation::CONTROL_ROOT, - control, - ) - .await?; - } - if managed_workspace && existing_workload_container_id.is_none() { - self.client - .copy_to_container(&workload_id, "/sandbox", archives.workspace) - .await?; - } - let supervisor_id = self - .client - .create_typed_container(&specs.supervisor) - .await?; - created_supervisor = Some(supervisor_id.clone()); - self.client - .copy_to_container(&supervisor_id, "/", archives.supervisor) - .await?; - // Start the sandbox only after both containers and their - // bootstrap material exist. It keeps the agent stopped - // until the authenticated supervisor confirms the boundary. - self.client.start_container(&workload_id).await?; - self.client.start_container(&supervisor_id).await?; - Ok::<(), ComputeDriverError>(()) - } - .await; - if create_result.is_err() { - for id in [created_supervisor, created_workload].into_iter().flatten() { - let _ = self.client.remove_container(&id, 0).await; - } - } - match create_result { - Ok(()) => Ok(()), - Err(e) => { - cleanup_all().await; - Err(e) - } - } - } - .await; - phase_status.finish(result) - } - .instrument(tracing::info_span!( - "podman.prepare_container", - otel.name = "podman.prepare_container", - otel.status_code = tracing::field::Empty, - container.name = %name, - )) - .await?; - - info!( - sandbox_id = %sandbox.id, - sandbox_name = %sandbox.name, - "Sandbox container started" - ); - - span_status.finish(Ok(())) - } - - /// Resolve the image identity for a supervisor-only refresh of a retained - /// workload container. - /// - /// The retained workload container keeps the image it was created from. - /// Re-resolving the request tag could select a different image whose user - /// and environment no longer match the retained workload, leaving - /// mode-0600 bootstrap files it cannot read. Pin to the immutable image ID - /// recorded on the stopped workload and never pull or resolve its tag - /// during refresh. - async fn resolve_retained_workload_image( - &self, - existing_workload_container_id: &str, - requested_image: &str, - ) -> Result { - let workload = self - .client - .inspect_container(existing_workload_container_id) - .await - .map_err(ComputeDriverError::from)?; - let pinned_image = workload.config.image; - if pinned_image.is_empty() { - return Err(ComputeDriverError::Precondition( - "retained Podman workload does not record its pinned image ID".into(), - )); - } - info!( - image = %pinned_image, - "Reusing retained workload image for supervisor-only refresh" - ); - let inspected_image = self - .client - .inspect_image(&pinned_image) - .await - .map_err(ComputeDriverError::from)?; - if inspected_image.id.is_empty() { - return Err(ComputeDriverError::Precondition(format!( - "podman image '{pinned_image}' inspection did not return an immutable image ID" - ))); - } - container::ResolvedPodmanImage::from_inspect(requested_image, inspected_image) - } - - /// Resolve image accounts without executing any image-supplied program. - async fn resolve_workload_identity( - &self, - sandbox: &DriverSandbox, - image: &str, - image_user: &str, - ) -> Result - { - #[derive(serde::Serialize)] - struct InspectionSpec<'a> { - name: String, - image: &'a str, - } - // Inspect a stopped, unexecuted container pinned to the final image ID. - let id = self - .client - .create_typed_container(&InspectionSpec { - name: format!("openshell-identity-{}", uuid::Uuid::new_v4()), - image, - }) - .await?; - let result = - async { - // Do not let image-controlled symlinks alias the protected channel - // into an agent-readable subtree before Podman mounts it. - match self.client.copy_from_container(&id, "/.openshell").await { - Err(PodmanApiError::NotFound(_)) => {} - Ok(_) => return Err(ComputeDriverError::Precondition( - "workload images must not prepopulate the reserved /.openshell hierarchy" - .into(), - )), - Err(error) => return Err(error.into()), - } - let mut accounts = Vec::new(); - for path in ["/etc/passwd", "/etc/group"] { - let content = match self.client.copy_from_container(&id, path).await { - Ok(archive) => extract_first_tar_entry(&archive) - .map_err(ComputeDriverError::Precondition)?, - Err(PodmanApiError::NotFound(_)) => Vec::new(), - Err(error) => return Err(error.into()), - }; - accounts.push(content); - } - let [passwd, group] = accounts.as_slice() else { - return Err(ComputeDriverError::Precondition( - "image account inspection was incomplete".into(), - )); - }; - crate::isolation::resolve_identity(sandbox, image, image_user, passwd, group) - } - .await; - let cleanup = self.client.remove_container(&id, 0).await; - if let Err(error) = cleanup { - warn!(container = %id, %error, "Failed to remove stopped identity inspection container"); - } - result - } - - /// Find only the workload, never its supervisor companion. - async fn find_container_id( - &self, - sandbox_id: &str, - ) -> Result, ComputeDriverError> { - Ok(self.find_container(sandbox_id).await?.map(|entry| entry.id)) - } - - async fn find_container( - &self, - sandbox_id: &str, - ) -> Result, ComputeDriverError> { - let id_filter = format!("{LABEL_SANDBOX_ID}={sandbox_id}"); - let entries = self - .client - .list_containers(&[ - LABEL_MANAGED_FILTER, - &id_filter, - crate::isolation::WORKLOAD_FILTER, - ]) - .await - .map_err(ComputeDriverError::from)?; - Ok(entries.into_iter().next()) - } - - async fn wait_for_container_stopped( - &self, - sandbox_id: &str, - container_id: &str, - ) -> Result, ComputeDriverError> { - let timeout = Duration::from_secs(u64::from(self.config.stop_timeout_secs)) - + STOP_COMPLETION_TIMEOUT_HEADROOM; - let deadline = tokio::time::Instant::now() + timeout; - - loop { - let inspect = self - .client - .inspect_container(container_id) - .await - .map_err(ComputeDriverError::from)?; - if matches!(inspect.state.status.as_str(), "exited" | "stopped") { - return Ok(inspect.state.finished_at); - } - - let now = tokio::time::Instant::now(); - if now >= deadline { - return Err(ComputeDriverError::Message(format!( - "container {container_id} for sandbox {sandbox_id} did not finish stopping within {timeout:?} (last state: {})", - inspect.state.status, - ))); - } - tokio::time::sleep(STOP_COMPLETION_POLL_INTERVAL.min(deadline - now)).await; - } - } - - /// Stop a sandbox container without deleting it. - #[tracing::instrument( - name = "podman.stop_sandbox", - skip(self), - fields( - otel.name = "podman.stop_sandbox", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - ) - )] - pub async fn stop_sandbox(&self, sandbox_id: &str) -> Result<(), ComputeDriverError> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let container = self.find_container(sandbox_id).await?; - let supervisor = crate::isolation::supervisor_name(sandbox_id); - match self - .client - .stop_container(&supervisor, self.config.stop_timeout_secs) - .await - { - Ok(()) | Err(PodmanApiError::NotFound(_)) => {} - Err(error) => return Err(error.into()), - } - let container = container.ok_or(ComputeDriverError::NotFound)?; - let container_id = container.id; - if container.state == "stopping" { - let result = async { - let finished_at = self - .wait_for_container_stopped(sandbox_id, &container_id) - .await?; - self.lifecycle_event_fences - .record_previous_exit(sandbox_id, finished_at.as_deref()); - Ok(()) - } - .await; - return span_status.finish(result); - } - if container.state != "running" { - return span_status.finish(Ok(())); - } - info!(sandbox_id = %sandbox_id, container = %container_id, "Stopping sandbox container"); - - let result = async { - self.client - .stop_container(&container_id, self.config.stop_timeout_secs) - .await - .map_err(ComputeDriverError::from)?; - - // Podman can return from the stop request before inspect reports the - // container as exited. If start runs during that interval, the exit - // event from the previous run can arrive after the gateway has moved - // the same sandbox to Starting, causing it to regress to Error. Wait - // for the terminal container state before allowing a restart. - let finished_at = self - .wait_for_container_stopped(sandbox_id, &container_id) - .await?; - - // Record the completed run before returning the stop RPC. The server - // may begin a restart as soon as this method returns, while Podman's - // stop/die event can still be queued. Recording the fence here keeps - // that delayed event from regressing the new run from Starting to - // Error. Keep the start-side recording as a fallback for restarts - // after a driver or gateway process restart. - self.lifecycle_event_fences - .record_previous_exit(sandbox_id, finished_at.as_deref()); - Ok(()) - } - .await; - span_status.finish(result) - } - - /// Whether the trusted supervisor of a sandbox predates the gateway's - /// current destination-trust bundle. A missing supervisor or a missing - /// generation label (a supervisor created before this labeling existed) - /// counts as stale: only the supervisor is recreated to refresh it, never - /// the workload or its data. - async fn supervisor_network_trust_stale( - &self, - sandbox_id: &str, - ) -> Result { - let supervisor = crate::isolation::supervisor_name(sandbox_id); - match self.client.inspect_container(&supervisor).await { - Ok(inspect) => Ok(inspect - .config - .labels - .get(NETWORK_SUPERVISOR_TRUST_GENERATION_KEY) - .map(String::as_str) - != Some(self.expected_network_trust_generation())), - Err(PodmanApiError::NotFound(_)) => Ok(true), - Err(error) => Err(error.into()), - } - } - - /// Recreate only the trusted supervisor of a stopped pair so the start - /// picks up the gateway's current destination-trust bundle. The workload - /// container, its volumes, its secrets, and its workspace data are never - /// replaced: the additional CA bundle is mounted only into the supervisor. - async fn replace_supervisor_for_network_trust( - &self, - old_workload: &ContainerListEntry, - durable_sandbox: &DriverSandbox, - generation: &openshell_core::sandbox_generation::SandboxGenerationId, - encoded_authentication: &[u8], - ) -> Result<(), ComputeDriverError> { - if durable_sandbox.id - != old_workload - .labels - .get(LABEL_SANDBOX_ID) - .map_or("", String::as_str) - { - return Err(ComputeDriverError::Precondition( - "durable sandbox id did not match stopped Podman workload".into(), - )); - } - if durable_sandbox.name.is_empty() || durable_sandbox.spec.is_none() { - return Err(ComputeDriverError::Precondition( - "a durable sandbox provisioning snapshot is required for Podman supervisor trust reconciliation".into(), - )); - } - if encoded_authentication.is_empty() { - return Err(ComputeDriverError::Precondition( - "fresh launch authentication is required for Podman supervisor trust reconciliation" - .into(), - )); - } - // Validate all untrusted fields before changing the old supervisor. - // Image selection below is driven exclusively by this durable - // snapshot. - self.validated_sandbox_create(durable_sandbox).await?; - - let canonical_supervisor = crate::isolation::supervisor_name(&durable_sandbox.id); - let previous_supervisor = match self.client.inspect_container(&canonical_supervisor).await { - Ok(inspect) if inspect.state.running => { - return Err(ComputeDriverError::Precondition( - "refusing to replace a running Podman supervisor during trust reconciliation" - .into(), - )); - } - Ok(inspect) => Some(inspect.id), - Err(PodmanApiError::NotFound(_)) => None, - Err(error) => return Err(error.into()), - }; - - // Complete every remaining fallible preparation before the rename so - // a transient failure cannot return with the previous supervisor - // already moved to its rollback name, where a normal delete would - // never find it. - let existing_token_name = container::token_secret_name(&durable_sandbox.id); - let existing_token = self - .client - .secret_exists(&existing_token_name) - .await - .map_err(ComputeDriverError::from)? - .then_some(existing_token_name.as_str()); - let mut replacement = durable_sandbox.clone(); - replacement - .spec - .as_mut() - .expect("validated durable snapshot has a spec") - .launch_authentication = encoded_authentication.to_vec(); - - let supervisor_rollback_name = - format!("openshell-supervisor-rollback-{}", uuid::Uuid::new_v4()); - if previous_supervisor.is_some() - && let Err(error) = self - .client - .rename_container(&canonical_supervisor, &supervisor_rollback_name) - .await - { - return Err(error.into()); - } - - let provisioned = self - .create_sandbox_with_existing_token( - &replacement, - existing_token, - Some(generation.as_str()), - Some(&old_workload.id), - ) - .await; - if let Err(error) = provisioned { - // The stopped workload and all of its resources were retained. - // Restore the canonical supervisor name so a failed replacement - // has no externally observable provisioning change. - if previous_supervisor.is_some() - && let Err(restore_error) = self - .client - .rename_container(&supervisor_rollback_name, &canonical_supervisor) - .await - { - // The previous supervisor keeps the rollback name and must - // stay identifiable for operator cleanup. A later retry - // still succeeds: the canonical name is absent, so the - // replacement path recreates a fresh supervisor. - warn!( - rollback_container = %supervisor_rollback_name, - sandbox_id = %durable_sandbox.id, - restore_error = %restore_error, - "failed to restore the previous Podman supervisor after a failed trust refresh" - ); - return Err(ComputeDriverError::Message(format!( - "trust refresh failed and the previous supervisor could not be \ - restored; the retained supervisor is named '{supervisor_rollback_name}' \ - and can be removed manually: {restore_error}" - ))); - } - return Err(error); - } - - if previous_supervisor.is_some() - && let Err(error) = self - .client - .remove_container_preserving_volumes(&supervisor_rollback_name) - .await - && !matches!(error, PodmanApiError::NotFound(_)) - { - // The replacement supervisor is running; the stopped rollback - // container is an identifiable orphan. Surface the failure so - // the orphan is not silently lost; a retry observes the fresh - // canonical supervisor and resumes the normal start path. - warn!( - rollback_container = %supervisor_rollback_name, - sandbox_id = %durable_sandbox.id, - remove_error = %error, - "failed to remove the previous Podman supervisor after a trust refresh" - ); - return Err(ComputeDriverError::Message(format!( - "trust refresh succeeded but the previous supervisor could not be \ - removed; the orphaned supervisor is named '{supervisor_rollback_name}' \ - and can be removed manually: {error}" - ))); - } - Ok(()) - } - - /// Start a previously stopped sandbox container. - #[tracing::instrument( - name = "podman.start_sandbox", - skip_all, - fields( - otel.name = "podman.start_sandbox", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - ) - )] - pub async fn start_sandbox( - &self, - sandbox_id: &str, - generation_id: &str, - encoded_authentication: &[u8], - durable_sandbox: Option<&DriverSandbox>, - ) -> Result<(), ComputeDriverError> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - // Verify before inspecting or modifying either member of the pair. - // The durable snapshot is used only if a stopped generation must be - // reconciled; it never comes from Podman's mutable inspect response. - self.verify_network_trust()?; - let generation = openshell_core::sandbox_generation::SandboxGenerationId::parse( - generation_id.to_string(), - ) - .map_err(|error| ComputeDriverError::InvalidArgument(error.to_string()))?; - let launch_authentication = (!encoded_authentication.is_empty()) - .then(|| decode_launch_authentication(encoded_authentication)) - .transpose()?; - let container = self - .find_container(sandbox_id) - .await? - .ok_or(ComputeDriverError::NotFound)?; - self.admit_container_resources(&container.id).await?; - let workload_running = container.state == "running"; - if workload_running { - let supervisor = self - .client - .inspect_container(&crate::isolation::supervisor_name(sandbox_id)) - .await; - if supervisor - .as_ref() - .is_ok_and(|inspect| inspect.state.running) - { - let archive = self - .client - .copy_from_container( - &crate::isolation::supervisor_name(sandbox_id), - crate::isolation::RESTART_METADATA_PATH, - ) - .await?; - let bundle = - extract_first_tar_entry(&archive).map_err(ComputeDriverError::Precondition)?; - let metadata = crate::isolation::restart_metadata_from_slice(&bundle)?; - if metadata.generation == generation.as_str() && encoded_authentication.is_empty() { - return span_status.finish(Ok(())); - } - if metadata.generation != generation.as_str() { - return span_status.finish(Err(ComputeDriverError::Precondition(format!( - "Podman sandbox is already running generation {}", - metadata.generation - )))); - } - // A non-empty bundle for the same generation comes from - // gateway startup recovery. Restart both containers so the - // in-memory launch session changes atomically on both sides. - } - self.client.stop_container(&container.id, 0).await?; - self.wait_for_container_stopped(sandbox_id, &container.id) - .await?; - } - // A user-driven start of a stopped sandbox mints fresh launch - // credentials. When the trusted supervisor predates the gateway's - // current destination-trust bundle (including supervisors created - // before generation labels existed), recreate only the supervisor so - // stop/start picks up the current additional CA bundle. The workload - // container, its volumes, and its workspace data are never replaced. - // Recovery without fresh credentials and running sandboxes keep their - // existing supervisor and bundle unchanged. - if !workload_running - && launch_authentication.is_some() - && let Some(durable_sandbox) = durable_sandbox - && self.supervisor_network_trust_stale(sandbox_id).await? - { - let result = self - .replace_supervisor_for_network_trust( - &container, - durable_sandbox, - &generation, - encoded_authentication, - ) - .await; - return span_status.finish(result); - } - let container_id = container.id; - info!(sandbox_id = %sandbox_id, container = %container_id, "Starting sandbox container"); - - // Fence delayed stop/die events from the previous container run before - // issuing the start. Podman's event stream can deliver those events - // after this API call has begun. Use the container's own transition - // timestamp so this remains correct for remote Podman services whose - // wall clock may differ from the gateway host. - let previous = self - .client - .inspect_container(&container_id) - .await - .map_err(ComputeDriverError::from)?; - self.lifecycle_event_fences - .record_previous_exit(sandbox_id, previous.state.finished_at.as_deref()); - let result = async { - let supervisor = crate::isolation::supervisor_name(sandbox_id); - self.client - .stop_container(&supervisor, self.config.stop_timeout_secs) - .await?; - self.wait_for_container_stopped(sandbox_id, &supervisor) - .await?; - let archive = self - .client - .copy_from_container(&supervisor, crate::isolation::RESTART_METADATA_PATH) - .await?; - let bundle = - extract_first_tar_entry(&archive).map_err(ComputeDriverError::Precondition)?; - let restart_metadata = crate::isolation::restart_metadata_from_slice(&bundle)?; - if launch_authentication.is_none() { - if restart_metadata.generation != generation.as_str() { - return Err(ComputeDriverError::Precondition(format!( - "Podman sandbox is already provisioned for generation {}", - restart_metadata.generation - ))); - } - // A gateway crash can recover a persisted Starting transition - // without a newly minted credential. Its stopped pair already - // contains the authenticated channel and supervisor state, so - // restart it as-is rather than fabricating provisioning input. - self.client.verify_isolation_fence(&container_id).await?; - self.client.start_container(&container_id).await?; - if let Err(error) = self.client.start_container(&supervisor).await { - let _ = self.client.stop_container(&container_id, 0).await; - return Err(error.into()); - } - return Ok(()); - } - let archives = - crate::isolation::bootstrap_archives(crate::isolation::BootstrapArchivesInput { - runtime_initiated: restart_metadata.runtime_initiated, - sandbox_id, - container_id: &container_id, - generation: generation.as_str(), - host_gateway_ip: self - .config - .resolved_host_gateway_ip() - .map_err(ComputeDriverError::from)?, - identity: &restart_metadata.workload_identity, - allow_extra_supplementary_groups: - crate::isolation::userns_preserves_host_groups( - self.config.userns.as_deref(), - ), - child_env: restart_metadata.child_env, - launch_authentication: launch_authentication.as_ref().expect("checked above"), - })?; - self.client - .copy_to_container( - &container_id, - crate::isolation::CHANNEL_ROOT, - archives.channel, - ) - .await?; - if let Some(control) = archives.control { - self.client - .copy_to_container(&container_id, crate::isolation::CONTROL_ROOT, control) - .await?; - } - self.client - .copy_to_container(&supervisor, "/", archives.supervisor) - .await?; - self.client.verify_isolation_fence(&container_id).await?; - self.client.start_container(&container_id).await?; - if let Err(error) = self.client.start_container(&supervisor).await { - let _ = self.client.stop_container(&container_id, 0).await; - return Err(error.into()); - } - Ok(()) - } - .await; - span_status.finish(result) - } - - /// Delete a sandbox container and its workspace volume. - #[tracing::instrument( - name = "podman.delete_sandbox", - skip(self), - fields( - otel.name = "podman.delete_sandbox", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - ) - )] - pub async fn delete_sandbox(&self, sandbox_id: &str) -> Result { - let span_status = openshell_otel::ErrorStatusGuard::current(); - if sandbox_id.is_empty() { - return Err(ComputeDriverError::Precondition( - "sandbox id is required".into(), - )); - } - - let supervisor = crate::isolation::supervisor_name(sandbox_id); - match self - .client - .remove_container(&supervisor, self.config.stop_timeout_secs) - .await - { - Ok(()) | Err(PodmanApiError::NotFound(_)) => {} - Err(error) => return Err(error.into()), - } - match self - .client - .remove_owned_volume( - &crate::isolation::channel_volume_name(sandbox_id), - sandbox_id, - ) - .await - { - Ok(()) | Err(PodmanApiError::NotFound(_)) => {} - // The workload still owns the volume until its removal below. - Err(error) => { - debug!(%error, "Channel volume not removed yet; retrying after workload removal"); - } - } - - let Some(container_id) = self.find_container_id(sandbox_id).await? else { - debug!(sandbox_id = %sandbox_id, "Sandbox container not found (already deleted)"); - let _ = self - .client - .remove_owned_volume( - &crate::isolation::control_volume_name(sandbox_id), - sandbox_id, - ) - .await; - let vol = container::volume_name(sandbox_id); - if let Err(e) = self.client.remove_owned_volume(&vol, sandbox_id).await { - warn!(sandbox_id = %sandbox_id, volume = %vol, error = %e, "Failed to remove workspace volume"); - } - cleanup_sandbox_token_secret(&self.client, &container::token_secret_name(sandbox_id)) - .await; - cleanup_sandbox_resolver_secret( - &self.client, - &container::resolver_secret_name(sandbox_id), - ) - .await; - cleanup_sandbox_proxy_auth_secret( - &self.client, - &container::proxy_auth_secret_name(sandbox_id), - ) - .await; - cleanup_tls_secrets(&self.client, &container::tls_secret_names(sandbox_id)).await; - self.lifecycle_event_fences.remove(sandbox_id); - return span_status.finish(Ok(false)); - }; - info!(sandbox_id = %sandbox_id, container = %container_id, "Deleting sandbox container"); - - // Keep stop, timeout, and removal in one Podman operation. Splitting - // stop and remove can race with another container starting an image - // mount when the stop reaches its timeout. - let container_existed = match self - .client - .remove_container(&container_id, self.config.stop_timeout_secs) - .await - { - Ok(()) => true, - Err(PodmanApiError::NotFound(_)) => false, - Err(e) => return Err(ComputeDriverError::from(e)), - }; - - if let Err(error) = self - .client - .remove_owned_volume( - &crate::isolation::control_volume_name(sandbox_id), - sandbox_id, - ) - .await - && !matches!(error, PodmanApiError::NotFound(_)) - { - warn!(%sandbox_id, %error, "Failed to remove private control volume"); - } - if let Err(error) = self - .client - .remove_owned_volume( - &crate::isolation::channel_volume_name(sandbox_id), - sandbox_id, - ) - .await - { - warn!(%sandbox_id, %error, "Failed to remove private channel volume"); - } - let vol = container::volume_name(sandbox_id); - if let Err(e) = self.client.remove_owned_volume(&vol, sandbox_id).await { - warn!( - sandbox_id = %sandbox_id, - volume = %vol, - error = %e, - "Failed to remove workspace volume" - ); - } - cleanup_sandbox_token_secret(&self.client, &container::token_secret_name(sandbox_id)).await; - cleanup_sandbox_resolver_secret(&self.client, &container::resolver_secret_name(sandbox_id)) - .await; - cleanup_sandbox_proxy_auth_secret( - &self.client, - &container::proxy_auth_secret_name(sandbox_id), - ) - .await; - cleanup_tls_secrets(&self.client, &container::tls_secret_names(sandbox_id)).await; - self.lifecycle_event_fences.remove(sandbox_id); - - span_status.finish(Ok(container_existed)) - } - - /// Check whether a sandbox container exists. - pub async fn sandbox_exists(&self, sandbox_id: &str) -> Result { - let id_filter = format!("{LABEL_SANDBOX_ID}={sandbox_id}"); - let entries = self - .client - .list_containers(&[ - LABEL_MANAGED_FILTER, - &id_filter, - crate::isolation::WORKLOAD_FILTER, - ]) - .await - .map_err(ComputeDriverError::from)?; - Ok(!entries.is_empty()) - } - - /// Fetch a single sandbox by ID. - pub async fn get_sandbox( - &self, - sandbox_id: &str, - ) -> Result, ComputeDriverError> { - let id_filter = format!("{LABEL_SANDBOX_ID}={sandbox_id}"); - let entries = self - .client - .list_containers(&[ - LABEL_MANAGED_FILTER, - &id_filter, - crate::isolation::WORKLOAD_FILTER, - ]) - .await - .map_err(ComputeDriverError::from)?; - let Some(entry) = entries.first() else { - return Ok(None); - }; - if entry.state == "running" { - Ok(watcher::inspect_workload(&self.client, &entry.id) - .await - .ok() - .and_then(|inspect| driver_sandbox_from_inspect(&inspect)) - .or_else(|| driver_sandbox_from_list_entry(entry))) - } else { - Ok(driver_sandbox_from_list_entry(entry)) - } - } - - /// List all managed sandboxes. - /// - /// Only inspects running containers (to get health status). Non-running - /// containers are built directly from the list entry data. - pub async fn list_sandboxes(&self) -> Result, ComputeDriverError> { - let entries = self - .client - .list_containers(&[LABEL_MANAGED_FILTER, crate::isolation::WORKLOAD_FILTER]) - .await - .map_err(ComputeDriverError::from)?; - - let mut sandboxes = Vec::with_capacity(entries.len()); - for entry in &entries { - if entry.state == "running" { - // Running containers need inspect for health check status. - match watcher::inspect_workload(&self.client, &entry.id).await { - Ok(inspect) => { - if let Some(sandbox) = driver_sandbox_from_inspect(&inspect) { - sandboxes.push(sandbox); - continue; - } - } - Err(e) => { - let name = entry.names.first().cloned().unwrap_or_default(); - warn!( - container = %name, - error = %e, - "Failed to inspect running container during list, falling back to list entry" - ); - } - } - } - // Non-running containers (or inspect fallback): build from list data. - if let Some(sandbox) = driver_sandbox_from_list_entry(entry) { - sandboxes.push(sandbox); - } - } - - sandboxes.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.id.cmp(&b.id))); - Ok(sandboxes) - } - - /// Start watching all managed sandbox containers. - pub async fn watch_sandboxes(&self) -> Result { - watcher::start_watch(self.client.clone(), self.lifecycle_event_fences.clone()) - .await - .map_err(ComputeDriverError::from) - } -} - -#[cfg(test)] -impl PodmanComputeDriver { - pub(crate) fn for_tests(config: PodmanComputeConfig) -> Self { - Self::for_tests_with_gpu_inventory(config, CdiGpuInventory::default()) - } - - pub(crate) fn for_tests_with_gpu_inventory( - config: PodmanComputeConfig, - gpu_inventory: CdiGpuInventory, - ) -> Self { - Self::for_tests_with_gpu_inventory_and_all_fallback(config, gpu_inventory, false) - } - - pub(crate) fn for_tests_with_gpu_inventory_and_all_fallback( - config: PodmanComputeConfig, - gpu_inventory: CdiGpuInventory, - allow_all_default_gpu: bool, - ) -> Self { - let client = PodmanClient::new(config.socket_path.clone().unwrap_or_default()); - let refresh_inventory = gpu_inventory.clone(); - Self { - client, - config, - gpu_selector: Arc::new(CdiGpuDefaultSelector::new( - gpu_inventory, - allow_all_default_gpu, - )), - gpu_inventory_refresh: Arc::new(move || { - (refresh_inventory.clone(), allow_all_default_gpu) - }), - lifecycle_event_fences: LifecycleEventFences::default(), - network_trust: None, - network_trust_staging: None, - } - } -} - -fn validate_apparmor_support( - profile: Option<&openshell_core::AppArmorProfile>, - apparmor_enabled: bool, -) -> Result<(), PodmanApiError> { - let requires_apparmor = matches!( - profile, - Some( - openshell_core::AppArmorProfile::RuntimeDefault - | openshell_core::AppArmorProfile::Localhost(_) - ) - ); - if requires_apparmor && !apparmor_enabled { - return Err(PodmanApiError::InvalidInput( - "app_armor_profile requires AppArmor, but Podman reports AppArmor is unavailable; install/enable AppArmor or use Unconfined explicitly" - .to_string(), - )); - } - Ok(()) -} - -fn runtime_image_pull_policy(image: &str) -> &'static str { - if supervisor_image_should_refresh(image) { - "newer" - } else { - "missing" - } -} - -/// Check whether the current user has subuid/subgid ranges configured. -/// -/// Rootless Podman requires entries in `/etc/subuid` and `/etc/subgid` for -/// the running user. If missing, container creation fails with an obscure -/// error. This pre-flight check emits a warning to guide operators. -fn check_subuid_range() { - let uid = nix::unistd::getuid().as_raw(); - let username = nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid)) - .ok() - .flatten() - .map(|u| u.name); - - let has_range = |path: &str| -> bool { - let Ok(content) = std::fs::read_to_string(path) else { - return false; - }; - let uid_str = uid.to_string(); - content.lines().any(|line| { - let Some(entry) = line.split(':').next() else { - return false; - }; - entry == uid_str || username.as_deref() == Some(entry) - }) - }; - - if !has_range("/etc/subuid") || !has_range("/etc/subgid") { - let user_display = username.as_deref().map_or_else( - || format!("UID {uid}"), - |name| format!("{name} (UID {uid})"), - ); - warn!( - user = %user_display, - "Rootless Podman detected but no /etc/subuid or /etc/subgid entry found. \ - Container creation may fail. Add entries with: \ - sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 $(whoami)" - ); - } -} - -// ── Sandbox binary extraction (userns fallback) ──────────────────────── - -async fn extract_sandbox_bin( - client: &PodmanClient, - config: &PodmanComputeConfig, -) -> Result { - let mut inspect = client - .inspect_image(&config.sandbox_runtime_image) - .await - .map_err(ComputeDriverError::from)?; - - if supervisor_image_should_refresh(&config.sandbox_runtime_image) { - info!( - image = %config.sandbox_runtime_image, - "Refreshing mutable Podman sandbox runtime image" - ); - match client - .pull_image(&config.sandbox_runtime_image, "always") - .await - { - Ok(()) => { - inspect = client - .inspect_image(&config.sandbox_runtime_image) - .await - .map_err(ComputeDriverError::from)?; - } - Err(err) => { - warn!( - image = %config.sandbox_runtime_image, - error = %err, - "Failed to refresh mutable Podman sandbox runtime image; \ - falling back to local image if present", - ); - } - } - } - - let digest = if inspect.id.is_empty() { - return Err(ComputeDriverError::Precondition(format!( - "sandbox runtime image '{}' has no ID", - config.sandbox_runtime_image, - ))); - } else { - &inspect.id - }; - - let cache_path = openshell_core::driver_utils::supervisor_cache_path("podman-sandbox", digest) - .map_err(ComputeDriverError::Precondition)?; - // Unit tests use ordered Podman API stubs and intentionally exercise the - // extraction path on every create. Production reuses the immutable cache. - #[cfg(not(test))] - if cache_path.is_file() { - validate_linux_elf_binary(&cache_path).map_err(ComputeDriverError::Precondition)?; - info!( - cache_path = %cache_path.display(), - "Using cached sandbox binary" - ); - return Ok(cache_path); - } - - info!( - image = %config.sandbox_runtime_image, - cache_path = %cache_path.display(), - "Extracting sandbox binary from image" - ); - - let container_name = temp_extract_container_name(); - let spec = serde_json::json!({ - "image": config.sandbox_runtime_image, - "name": container_name, - "entrypoint": [SANDBOX_RUNTIME_IMAGE_BINARY_PATH], - "command": [], - }); - client - .create_container(&spec) - .await - .map_err(ComputeDriverError::from)?; - - let result = extract_binary_from_container(client, &container_name, &cache_path).await; - - if let Err(err) = client.remove_container(&container_name, 0).await { - warn!( - container = container_name, - error = %err, - "Failed to remove sandbox runtime extractor container" - ); - } - - result -} - -async fn extract_binary_from_container( - client: &PodmanClient, - container_name: &str, - cache_path: &Path, -) -> Result { - let tar_bytes = client - .copy_from_container(container_name, SANDBOX_RUNTIME_IMAGE_BINARY_PATH) - .await - .map_err(ComputeDriverError::from)?; - - let binary_bytes = extract_first_tar_entry(&tar_bytes).map_err(|err| { - ComputeDriverError::Precondition(format!( - "failed to extract sandbox binary from tar: {err}" - )) - })?; - - write_cache_binary_atomic(cache_path, &binary_bytes) - .map_err(ComputeDriverError::Precondition)?; - validate_linux_elf_binary(cache_path).map_err(ComputeDriverError::Precondition)?; - Ok(cache_path.to_path_buf()) -} - -fn podman_child_environment( - sandbox: &DriverSandbox, - image_env: &[String], -) -> HashMap { - let mut environment = image_env - .iter() - .filter_map(|entry| { - entry - .split_once('=') - .map(|(key, value)| (key.to_string(), value.to_string())) - }) - .collect::>(); - if let Some(spec) = sandbox.spec.as_ref() { - if let Some(template) = spec.template.as_ref() { - environment.extend(template.environment.clone()); - } - environment.extend(spec.environment.clone()); - } - environment.retain(|key, _| !key.starts_with("OPENSHELL_")); - environment -} - -/// Returns `true` when userns remaps all UIDs, making host-owned bind mounts -/// unreadable from inside the container. `auto` and `no-map` remap every UID; -/// `keep-id` preserves the host user's UID; `host` uses the host namespace. -#[cfg(test)] -fn userns_remaps_uids(userns: Option<&str>) -> bool { - userns.is_some_and(|mode| { - let base = mode.split(':').next().unwrap_or(mode); - !matches!(base.to_ascii_lowercase().as_str(), "host" | "keep-id") - }) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::test_utils::{StubResponse, spawn_podman_stub}; - use hyper::StatusCode; - use openshell_core::jwt::{ - CredentialEpoch, SandboxLaunchAuthentication, SecretJwt, SessionVerificationKey, - SupervisorAuthBundle, - }; - use openshell_core::proto::compute::v1::{ - DriverSandboxSpec, DriverSandboxTemplate, ResourceRequirements, - }; - use std::collections::HashMap; - use std::fs; - use std::path::{Path, PathBuf}; - - fn launch_authentication() -> SandboxLaunchAuthentication { - SandboxLaunchAuthentication { - supervisor: SupervisorAuthBundle { - session_id: openshell_core::SandboxSessionId::new(), - runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( - "generation-1", - ) - .unwrap(), - session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), - auth_epoch: CredentialEpoch::new(1).unwrap(), - gateway_token: SecretJwt::parse("gateway.token.value").unwrap(), - gateway_expires_at: i64::MAX, - sandbox_token: SecretJwt::parse("sandbox.token.value").unwrap(), - sandbox_expires_at: i64::MAX, - ssh_host_private_key: None, - traces_otlp_headers: None, - ocsf_otlp_headers: None, - agent_otlp_headers: None, - otlp_tls: Vec::new(), - traces_otlp_tls: None, - ocsf_otlp_tls: None, - agent_otlp_tls: None, - }, - gateway_id: "gateway-test".to_string(), - verification_keys: vec![SessionVerificationKey { - key_id: "test-key".to_string(), - public_key_pem: b"public-key".to_vec(), - }], - } - } - - fn encoded_launch_authentication() -> Vec { - serde_json::to_vec(&launch_authentication()).unwrap() - } - - // ── socket resolution ─────────────────────────────────────────────── - // - // These test resolve_socket_path directly with an injected detector, so - // they are deterministic regardless of the host's real environment - // variables or whether a Podman socket happens to be running. - - #[test] - fn resolve_socket_path_prefers_explicit_configuration() { - let path = resolve_socket_path(Some(PathBuf::from("/explicit.sock")), || { - Some(PathBuf::from("/detected.sock")) - }) - .unwrap(); - - assert_eq!(path, PathBuf::from("/explicit.sock")); - } - - #[test] - fn resolve_socket_path_uses_detected_socket_when_unconfigured() { - let path = resolve_socket_path(None, || Some(PathBuf::from("/detected.sock"))).unwrap(); - - assert_eq!(path, PathBuf::from("/detected.sock")); - } - - #[test] - fn resolve_socket_path_errors_when_neither_source_resolves() { - let err = resolve_socket_path(None, || None).unwrap_err(); - - assert!(err.to_string().contains("no responsive Podman API socket")); - } - - fn cdi_devices_config(device_ids: &[&str]) -> prost_types::Struct { - prost_types::Struct { - fields: std::iter::once(( - "cdi_devices".to_string(), - prost_types::Value { - kind: Some(prost_types::value::Kind::ListValue( - prost_types::ListValue { - values: device_ids - .iter() - .map(|device_id| prost_types::Value { - kind: Some(prost_types::value::Kind::StringValue( - (*device_id).to_string(), - )), - }) - .collect(), - }, - )), - }, - )) - .collect(), - } - } - - fn gpu_resources(count: Option) -> ResourceRequirements { - ResourceRequirements { - gpu: Some(GpuResourceRequirements { count }), - } - } - - #[test] - fn podman_driver_error_from_conflict() { - let err = ComputeDriverError::from(PodmanApiError::Conflict("exists".into())); - assert!(matches!(err, ComputeDriverError::AlreadyExists)); - } - - #[tokio::test] - async fn supervisor_refresh_pins_retained_workload_image_without_pulling_tag() { - let (socket, requests, handle) = spawn_podman_stub( - "refresh-pinned-image", - vec![ - // Inspect of the retained, stopped workload container: it was - // created from an immutable image ID. - StubResponse::new( - StatusCode::OK, - r#"{"Id":"ctr-retained","Name":"workload","State":{"Status":"exited","Running":false},"Config":{"Image":"sha256:pinned-image-id"}}"#, - ), - // Inspection of the pinned image by ID, not by its tag. - StubResponse::new( - StatusCode::OK, - r#"{"Id":"sha256:pinned-image-id","Config":{"User":"1000:1000","Env":["PATH=/usr/bin"],"WorkingDir":"/"}}"#, - ), - ], - ); - let driver = test_driver(socket); - let resolved = driver - .resolve_retained_workload_image("ctr-retained", "app:test") - .await - .expect("pin retained workload image"); - handle.await.unwrap(); - assert_eq!(resolved.id, "sha256:pinned-image-id"); - assert_eq!(resolved.oci_user, "1000:1000"); - let requests = requests.lock().unwrap(); - assert_eq!(requests.len(), 2, "unexpected requests: {requests:?}"); - assert!( - requests[0].contains("/libpod/containers/ctr-retained/json"), - "expected retained workload inspection first: {requests:?}" - ); - assert!( - requests[1].contains("/libpod/images/sha256%3Apinned-image-id/json"), - "expected pinned image inspection: {requests:?}" - ); - assert!( - !requests.iter().any(|request| request.contains("/pull")), - "supervisor-only refresh must never pull the workload tag: {requests:?}" - ); - } - - fn refresh_fixture( - sandbox_id: &str, - ) -> ( - ContainerListEntry, - DriverSandbox, - openshell_core::sandbox_generation::SandboxGenerationId, - ) { - use openshell_core::proto::compute::v1::DriverSandboxSpec; - let old_workload = ContainerListEntry { - id: format!("workload-{sandbox_id}"), - names: vec![format!("openshell-default--{sandbox_id}")], - state: "exited".to_string(), - labels: HashMap::from([(LABEL_SANDBOX_ID.to_string(), sandbox_id.to_string())]), - ports: None, - networks: None, - exit_code: 0, - }; - let durable = DriverSandbox { - id: sandbox_id.to_string(), - name: format!("sandbox-{sandbox_id}"), - namespace: String::new(), - spec: Some(DriverSandboxSpec::default()), - status: None, - workspace: String::new(), - }; - let generation = - openshell_core::sandbox_generation::SandboxGenerationId::parse("generation-1") - .expect("valid generation"); - (old_workload, durable, generation) - } - - const REFRESH_STOPPED_SUPERVISOR: &str = r#"{"Id":"sup-1","Name":"supervisor","State":{"Status":"exited","Running":false},"Config":{"Image":"sha256:supervisor-image"}}"#; - - #[tokio::test] - async fn supervisor_refresh_completes_fallible_prep_before_renaming() { - // A transient secret-lookup failure must return before the previous - // supervisor is renamed, so the canonical supervisor is never left - // under its rollback name where a normal delete cannot find it. - let (socket, requests, handle) = spawn_podman_stub( - "refresh-prep-before-rename", - vec![ - StubResponse::new(StatusCode::OK, REFRESH_STOPPED_SUPERVISOR), - StubResponse::new( - StatusCode::INTERNAL_SERVER_ERROR, - r#"{"message":"transient secret lookup failure"}"#, - ), - ], - ); - let driver = test_driver(socket); - let (old_workload, durable, generation) = refresh_fixture("prep-1"); - let result = driver - .replace_supervisor_for_network_trust(&old_workload, &durable, &generation, b"auth") - .await; - assert!( - result.is_err(), - "secret lookup failure must fail the refresh" - ); - handle.await.unwrap(); - let requests = requests.lock().unwrap(); - assert!( - !requests.iter().any(|request| request.contains("/rename")), - "fallible preparation must complete before any rename: {requests:?}" - ); - } - - #[tokio::test] - async fn supervisor_refresh_restores_canonical_name_when_replacement_fails() { - // The replacement create fails at its first image pull; the previous - // supervisor must be restored to the canonical name and must not be - // deleted, so a later retry observes the original stopped pair. - let (socket, requests, handle) = spawn_podman_stub( - "refresh-restore-on-failure", - vec![ - StubResponse::new(StatusCode::OK, REFRESH_STOPPED_SUPERVISOR), - StubResponse::new(StatusCode::NOT_FOUND, r#"{"message":"no secret"}"#), - StubResponse::new(StatusCode::NO_CONTENT, ""), - StubResponse::new( - StatusCode::INTERNAL_SERVER_ERROR, - r#"{"message":"image pull failed"}"#, - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), - ], - ); - let driver = test_driver(socket); - let (old_workload, durable, generation) = refresh_fixture("restore-1"); - let result = driver - .replace_supervisor_for_network_trust(&old_workload, &durable, &generation, b"auth") - .await; - assert!(result.is_err(), "failed replacement must fail the refresh"); - handle.await.unwrap(); - let requests = requests.lock().unwrap(); - let renames = requests - .iter() - .filter(|request| request.contains("/rename")) - .collect::>(); - assert_eq!( - renames.len(), - 2, - "expected rename to rollback and rename back: {requests:?}" - ); - assert!( - renames[0].contains("openshell-supervisor-restore-1") - && renames[0].contains("openshell-supervisor-rollback-"), - "first rename moves the canonical supervisor to the rollback name: {renames:?}" - ); - assert!( - renames[1].contains("openshell-supervisor-rollback-") - && renames[1].contains("name=openshell-supervisor-restore-1"), - "second rename restores the canonical name: {renames:?}" - ); - assert!( - !requests - .iter() - .any(|request| request.starts_with("DELETE") && request.contains("rollback")), - "the restored supervisor must not be deleted: {requests:?}" - ); - } - - #[tokio::test] - async fn supervisor_refresh_names_orphaned_rollback_when_restore_fails() { - // If the restore rename itself fails, the error must name the - // rollback container so the orphan is identifiable for cleanup. - let (socket, _requests, handle) = spawn_podman_stub( - "refresh-restore-failure-orphan", - vec![ - StubResponse::new(StatusCode::OK, REFRESH_STOPPED_SUPERVISOR), - StubResponse::new(StatusCode::NOT_FOUND, r#"{"message":"no secret"}"#), - StubResponse::new(StatusCode::NO_CONTENT, ""), - StubResponse::new( - StatusCode::INTERNAL_SERVER_ERROR, - r#"{"message":"image pull failed"}"#, - ), - StubResponse::new( - StatusCode::INTERNAL_SERVER_ERROR, - r#"{"message":"rename raced with cleanup"}"#, - ), - ], - ); - let driver = test_driver(socket); - let (old_workload, durable, generation) = refresh_fixture("orphan-1"); - let error = driver - .replace_supervisor_for_network_trust(&old_workload, &durable, &generation, b"auth") - .await - .expect_err("restore failure must fail the refresh"); - handle.await.unwrap(); - let message = error.to_string(); - assert!( - message.contains("openshell-supervisor-rollback-"), - "error must name the orphaned rollback container: {message}" - ); - } - - #[test] - fn podman_driver_error_from_not_found() { - let err = ComputeDriverError::from(PodmanApiError::NotFound("gone".into())); - assert!(matches!(err, ComputeDriverError::NotFound)); - } - - #[tokio::test] - async fn stop_missing_workload_still_reclaims_supervisor() { - let (socket, requests, handle) = spawn_podman_stub( - "stop-orphan-supervisor", - vec![ - StubResponse::new(StatusCode::OK, "[]"), - StubResponse::new(StatusCode::NO_CONTENT, ""), - ], - ); - let result = test_driver(socket).stop_sandbox("sandbox-1").await; - assert!(matches!(result, Err(ComputeDriverError::NotFound))); - handle.await.unwrap(); - let requests = requests.lock().unwrap(); - assert_eq!(requests.len(), 2); - assert!(requests[1].contains("/stop?timeout=10")); - assert!(requests[1].contains(&crate::isolation::supervisor_name("sandbox-1"))); - } - - #[tokio::test] - async fn stop_and_start_target_the_existing_container() { - let (stop_socket, stop_requests, stop_handle) = spawn_podman_stub( - "lifecycle-stop", - vec![ - StubResponse::new(StatusCode::OK, r#"[{"Id":"ctr-1","State":"running"}]"#), - StubResponse::new(StatusCode::NO_CONTENT, ""), // companion stop - StubResponse::new(StatusCode::NO_CONTENT, ""), - StubResponse::new( - StatusCode::OK, - r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#, - ), - ], - ); - test_driver(stop_socket.clone()) - .stop_sandbox("sandbox-1") - .await - .expect("stop should succeed"); - stop_handle.await.expect("stop stub should finish"); - assert_eq!( - stop_requests - .lock() - .expect("request log lock should not be poisoned")[2], - format!( - "POST {}", - api_path("/libpod/containers/ctr-1/stop?timeout=10") - ) - ); - assert_eq!( - stop_requests - .lock() - .expect("request log lock should not be poisoned")[3], - format!("GET {}", api_path("/libpod/containers/ctr-1/json")) - ); - - let (start_socket, start_requests, start_handle) = spawn_podman_stub( - "lifecycle-start", - vec![ - StubResponse::new( - StatusCode::OK, - r#"[{"Id":"ctr-1","State":"stopped","Labels":{"openshell.ai/additional-ca-generation":"none"}}]"#, - ), - StubResponse::new( - StatusCode::OK, - r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#, - ), - ].into_iter().chain(restart_responses()).collect(), - ); - let authentication = encoded_launch_authentication(); - test_driver(start_socket.clone()) - .start_sandbox("sandbox-1", "generation-1", &authentication, None) - .await - .expect("start should succeed"); - start_handle.await.expect("start stub should finish"); - let restart_requests = start_requests.lock().unwrap().clone(); - assert_eq!( - restart_requests - .iter() - .filter(|request| request.starts_with("PUT ")) - .cloned() - .collect::>(), - vec![ - format!( - "PUT {}", - api_path("/libpod/containers/ctr-1/archive?path=%2F.openshell%2Fchannel") - ), - format!( - "PUT {}", - api_path("/libpod/containers/openshell-supervisor-sandbox-1/archive?path=%2F") - ), - ] - ); - assert!( - !restart_requests - .iter() - .any(|request| request.contains("/volumes/create") - || request.contains("/containers/create")) - ); - assert_eq!( - start_requests - .lock() - .expect("request log lock should not be poisoned")[1], - format!("GET {}", api_path("/libpod/containers/ctr-1/json")) - ); - assert_eq!( - start_requests - .lock() - .expect("request log lock should not be poisoned")[2], - format!( - "POST {}", - api_path("/libpod/containers/openshell-supervisor-sandbox-1/stop?timeout=10") - ) - ); - - let _ = fs::remove_file(stop_socket); - let _ = fs::remove_file(start_socket); - } - - #[tokio::test] - async fn stop_waits_for_the_container_to_leave_stopping_state() { - let (socket, requests, handle) = spawn_podman_stub( - "lifecycle-stop-wait", - vec![ - StubResponse::new(StatusCode::OK, r#"[{"Id":"ctr-1","State":"running"}]"#), - StubResponse::new(StatusCode::NO_CONTENT, ""), // companion stop - StubResponse::new(StatusCode::NO_CONTENT, ""), - StubResponse::new( - StatusCode::OK, - r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"stopping","Running":true},"Config":{}}"#, - ), - StubResponse::new( - StatusCode::OK, - r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#, - ), - ], - ); - - test_driver(socket.clone()) - .stop_sandbox("sandbox-1") - .await - .expect("stop should wait for the terminal container state"); - handle.await.expect("stop stub should finish"); - - let requests = requests - .lock() - .expect("request log lock should not be poisoned"); - assert_eq!(requests.len(), 5); - assert_eq!( - requests[3], - format!("GET {}", api_path("/libpod/containers/ctr-1/json")) - ); - assert_eq!(requests[4], requests[3]); - - let _ = fs::remove_file(socket); - } - - #[tokio::test] - async fn stop_retry_waits_for_an_existing_stopping_container() { - let (socket, requests, handle) = spawn_podman_stub( - "lifecycle-stop-retry", - vec![ - StubResponse::new(StatusCode::OK, r#"[{"Id":"ctr-1","State":"stopping"}]"#), - StubResponse::new(StatusCode::NO_CONTENT, ""), // companion stop - StubResponse::new( - StatusCode::OK, - r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#, - ), - ], - ); - - test_driver(socket.clone()) - .stop_sandbox("sandbox-1") - .await - .expect("stop retry should wait for the terminal container state"); - handle.await.expect("stop retry stub should finish"); - - let requests = requests - .lock() - .expect("request log lock should not be poisoned"); - assert_eq!(requests.len(), 3); - assert_eq!( - requests[2], - format!("GET {}", api_path("/libpod/containers/ctr-1/json")) - ); - - let _ = fs::remove_file(socket); - } - - #[tokio::test] - async fn stop_sandbox_exports_a_podman_operation_span() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let (socket_path, _requests, handle) = spawn_podman_stub( - "trace-stop", - vec![ - StubResponse::new(StatusCode::OK, r#"[{"Id":"ctr-1","State":"running"}]"#), - StubResponse::new(StatusCode::NO_CONTENT, ""), // companion stop - StubResponse::new(StatusCode::NO_CONTENT, ""), - StubResponse::new( - StatusCode::OK, - r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#, - ), - ], - ); - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = - tracing_subscriber::registry().with(crate::otel_tracing::TRACING.layer(&provider)); - - test_driver(socket_path.clone()) - .stop_sandbox("sandbox-1") - .with_subscriber(subscriber) - .await - .expect("stop should succeed"); - handle.await.expect("stub should finish"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "podman.stop_sandbox") - .expect("stop operation should be exported"); - assert_eq!( - span.attributes - .iter() - .find(|attribute| attribute.key.as_str() == "sandbox.id") - .map(|attribute| attribute.value.to_string()) - .as_deref(), - Some("sandbox-1") - ); - provider.shutdown().unwrap(); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn start_sandbox_span_does_not_capture_launch_authentication() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = - tracing_subscriber::registry().with(crate::otel_tracing::TRACING.layer(&provider)); - - test_driver(PathBuf::from("/nonexistent/podman.sock")) - .start_sandbox( - "sandbox-1", - "invalid-generation", - b"secret-launch-authentication", - None, - ) - .with_subscriber(subscriber) - .await - .expect_err("invalid generation must fail before contacting Podman"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "podman.start_sandbox") - .expect("start operation span"); - assert!(span.attributes.iter().all(|attribute| { - !matches!( - attribute.key.as_str(), - "launch_authentication" | "encoded_authentication" - ) - })); - provider.shutdown().unwrap(); - } - - #[tokio::test] - async fn create_sandbox_exports_nested_preparation_spans() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let (socket_path, requests, handle) = spawn_podman_stub( - "trace-create", - create_setup_responses(false, "sandbox-trace") - .into_iter() - .chain(create_launch_responses()) - .collect(), - ); - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = - tracing_subscriber::registry().with(crate::otel_tracing::TRACING.layer(&provider)); - - let mut sandbox = plain_sandbox("sandbox-trace", "demo"); - sandbox.spec = Some(DriverSandboxSpec { - launch_authentication: encoded_launch_authentication(), - ..DriverSandboxSpec::default() - }); - test_driver(socket_path.clone()) - .create_sandbox(&sandbox) - .with_subscriber(subscriber) - .await - .expect("create should succeed"); - handle.await.expect("stub should finish"); - let uploads: Vec<_> = requests - .lock() - .unwrap() - .iter() - .filter(|request| request.starts_with("PUT ")) - .cloned() - .collect(); - assert_eq!( - uploads, - [ - "/libpod/containers/workload/archive?path=%2F.openshell%2Fchannel", - "/libpod/containers/workload/archive?path=%2F.openshell%2Fchannel%2Fcontrol", - "/libpod/containers/workload/archive?path=%2Fsandbox", - "/libpod/containers/supervisor/archive?path=%2F", - ] - .map(|path| format!("PUT {}", api_path(path))) - ); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let create = spans - .iter() - .find(|span| span.name == "podman.provision") - .expect("create operation should be exported"); - for name in [ - "podman.prepare_images", - "podman.prepare_storage", - "podman.prepare_container", - ] { - let child = spans - .iter() - .find(|span| span.name == name) - .unwrap_or_else(|| panic!("{name} should be exported")); - assert_eq!( - child.parent_span_id, - create.span_context.span_id(), - "{name}" - ); - } - provider.shutdown().unwrap(); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn prepare_images_span_covers_and_marks_sandbox_image_pull_failure() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let (socket_path, _requests, handle) = spawn_podman_stub( - "trace-image-failure", - vec![ - StubResponse::new(StatusCode::OK, "{}"), - StubResponse::new(StatusCode::INTERNAL_SERVER_ERROR, "pull failed"), - ], - ); - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = - tracing_subscriber::registry().with(crate::otel_tracing::TRACING.layer(&provider)); - - test_driver(socket_path.clone()) - .create_sandbox(&plain_sandbox("sandbox-trace", "demo")) - .with_subscriber(subscriber) - .await - .expect_err("sandbox image pull should fail"); - handle.await.expect("stub should finish"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let phase = spans - .iter() - .find(|span| span.name == "podman.prepare_images") - .expect("image preparation should be exported"); - assert!(matches!( - phase.status, - opentelemetry::trace::Status::Error { .. } - )); - provider.shutdown().unwrap(); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn start_and_delete_export_podman_operation_spans() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = - tracing_subscriber::registry().with(crate::otel_tracing::TRACING.layer(&provider)); - - let (start_socket, _requests, start_handle) = spawn_podman_stub( - "trace-start", - vec![ - StubResponse::new( - StatusCode::OK, - r#"[{"Id":"ctr-1","State":"stopped","Labels":{"openshell.ai/additional-ca-generation":"none"}}]"#, - ), - StubResponse::new( - StatusCode::OK, - r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{}}"#, - ), - ].into_iter().chain(restart_responses()).collect(), - ); - let authentication = encoded_launch_authentication(); - test_driver(start_socket.clone()) - .start_sandbox("sandbox-1", "generation-1", &authentication, None) - .with_subscriber(subscriber) - .await - .expect("start should succeed"); - start_handle.await.expect("start stub should finish"); - - let (delete_socket, _requests, delete_handle) = spawn_podman_stub( - "trace-delete", - vec![ - StubResponse::new(StatusCode::NOT_FOUND, ""), // no companion - StubResponse::new(StatusCode::NOT_FOUND, ""), // no channel volume - StubResponse::new(StatusCode::OK, "[]"), - StubResponse::new(StatusCode::NOT_FOUND, ""), // no control volume - StubResponse::new(StatusCode::NOT_FOUND, ""), // no workspace volume - ], - ); - let subscriber = - tracing_subscriber::registry().with(crate::otel_tracing::TRACING.layer(&provider)); - test_driver(delete_socket.clone()) - .delete_sandbox("sandbox-1") - .with_subscriber(subscriber) - .await - .expect("delete should succeed"); - delete_handle.await.expect("delete stub should finish"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - assert!(spans.iter().any(|span| span.name == "podman.start_sandbox")); - assert!( - spans - .iter() - .any(|span| span.name == "podman.delete_sandbox") - ); - provider.shutdown().unwrap(); - let _ = fs::remove_file(start_socket); - let _ = fs::remove_file(delete_socket); - } - - #[test] - fn validate_gpu_request_accepts_gpu_count_request_shape() { - let gpu = GpuResourceRequirements { count: Some(2) }; - let driver_config = PodmanSandboxDriverConfig::default(); - - PodmanComputeDriver::validate_gpu_request(Some(&gpu), &driver_config) - .expect("default GPU count shape should be accepted before inventory selection"); - } - - #[test] - fn validate_gpu_request_accepts_single_cdi_device_without_gpu_count() { - let gpu = GpuResourceRequirements { count: None }; - let mut driver_config = PodmanSandboxDriverConfig::default(); - driver_config.cdi_devices = Some(vec!["nvidia.com/gpu=0".to_string()]); - - PodmanComputeDriver::validate_gpu_request(Some(&gpu), &driver_config) - .expect("single exact CDI device should pass count validation"); - } - - #[test] - fn validate_gpu_request_rejects_multiple_cdi_devices_without_gpu_count() { - let gpu = GpuResourceRequirements { count: None }; - let mut driver_config = PodmanSandboxDriverConfig::default(); - driver_config.cdi_devices = Some(vec![ - "nvidia.com/gpu=0".to_string(), - "nvidia.com/gpu=1".to_string(), - ]); - let err = PodmanComputeDriver::validate_gpu_request(Some(&gpu), &driver_config) - .expect_err("missing CDI device count should be rejected for multiple devices"); - - assert!(matches!(err, ComputeDriverError::InvalidArgument(_))); - assert!( - err.to_string() - .contains("gpu count (1) must match driver_config.cdi_devices length (2)") - ); - } - - #[test] - fn validate_gpu_request_rejects_cdi_devices_without_gpu_request() { - let mut driver_config = PodmanSandboxDriverConfig::default(); - driver_config.cdi_devices = Some(vec!["nvidia.com/gpu=0".to_string()]); - let err = PodmanComputeDriver::validate_gpu_request(None, &driver_config) - .expect_err("missing GPU request should be rejected"); - - assert!(matches!(err, ComputeDriverError::InvalidArgument(_))); - assert!(err.to_string().contains("requires a gpu request")); - } - - #[test] - fn validate_gpu_request_rejects_mismatched_cdi_device_count() { - let gpu = GpuResourceRequirements { count: Some(2) }; - let mut driver_config = PodmanSandboxDriverConfig::default(); - driver_config.cdi_devices = Some(vec!["nvidia.com/gpu=0".to_string()]); - let err = PodmanComputeDriver::validate_gpu_request(Some(&gpu), &driver_config) - .expect_err("mismatched CDI device count should be rejected"); - - assert!(matches!(err, ComputeDriverError::InvalidArgument(_))); - assert!( - err.to_string() - .contains("gpu count (2) must match driver_config.cdi_devices length (1)") - ); - } - - // ── grpc_endpoint auto-detection ─────────────────────────────────── - // - // PodmanComputeDriver::new() fills grpc_endpoint through - // select_grpc_endpoint() when it is empty. - - #[test] - fn grpc_endpoint_uses_loopback_on_linux() { - let cfg = PodmanComputeConfig { - gateway_port: 8081, - ..PodmanComputeConfig::default() - }; - assert_eq!( - select_grpc_endpoint(&cfg, PodmanEndpointEnvironment::LinuxHost), - "http://127.0.0.1:8081" - ); - } - - #[test] - fn grpc_endpoint_uses_host_alias_on_podman_machine() { - let cfg = PodmanComputeConfig { - gateway_port: 8080, - guest_tls_ca: Some(PathBuf::from("/tls/ca.crt")), - ..PodmanComputeConfig::default() - }; - assert_eq!( - select_grpc_endpoint(&cfg, PodmanEndpointEnvironment::PodmanMachine), - "https://host.containers.internal:8080" - ); - } - - fn supervisor_otlp(endpoint: &str) -> openshell_core::sandbox_env::SupervisorOtlp { - use openshell_core::sandbox_env::{OtlpExport, OtlpProtocol, SupervisorOtlp}; - let export = |protocol| { - Some(OtlpExport { - endpoint: endpoint.to_string(), - protocol, - }) - }; - SupervisorOtlp { - traces: export(OtlpProtocol::Grpc), - ocsf: export(OtlpProtocol::HttpProtobuf), - agent: export(OtlpProtocol::HttpProtobuf), - } - } - - #[test] - fn supervisor_otlp_stays_empty_without_gateway_export() { - assert!( - select_supervisor_otlp( - openshell_core::sandbox_env::SupervisorOtlp::default(), - PodmanEndpointEnvironment::PodmanMachine - ) - .is_empty() - ); - } - - #[test] - fn supervisor_otlp_keeps_loopback_on_linux() { - assert_eq!( - select_supervisor_otlp( - supervisor_otlp("http://127.0.0.1:4317"), - PodmanEndpointEnvironment::LinuxHost - ), - supervisor_otlp("http://127.0.0.1:4317") - ); - } - - #[test] - fn supervisor_otlp_uses_host_alias_for_loopback_on_podman_machine() { - for endpoint in [ - "http://127.0.0.1:4317", - "http://localhost:4317", - "http://[::1]:4317", - ] { - assert_eq!( - select_supervisor_otlp( - supervisor_otlp(endpoint), - PodmanEndpointEnvironment::PodmanMachine - ), - supervisor_otlp("http://host.containers.internal:4317"), - "{endpoint}" - ); - } - } - - #[test] - fn supervisor_otlp_keeps_routable_hosts_on_podman_machine() { - assert_eq!( - select_supervisor_otlp( - supervisor_otlp("https://collector.example.com:4317"), - PodmanEndpointEnvironment::PodmanMachine - ), - supervisor_otlp("https://collector.example.com:4317") - ); - } - - #[test] - fn ca_only_tls_config_is_enabled() { - let cfg = PodmanComputeConfig { - gateway_port: 8080, - guest_tls_ca: Some(PathBuf::from("/tls/ca.crt")), - ..PodmanComputeConfig::default() - }; - assert!(cfg.tls_enabled()); - cfg.validate_tls_config().expect("CA-only TLS is valid"); - } - - #[test] - fn explicit_grpc_endpoint_takes_precedence() { - let cfg = PodmanComputeConfig { - grpc_endpoint: "https://gateway.internal:9000".to_string(), - gateway_port: 8081, - ..PodmanComputeConfig::default() - }; - assert_eq!( - select_grpc_endpoint(&cfg, PodmanEndpointEnvironment::LinuxHost), - "https://gateway.internal:9000" - ); - } - - #[test] - fn confined_apparmor_profiles_follow_podman_capability() { - use openshell_core::AppArmorProfile; - - for profile in [ - AppArmorProfile::RuntimeDefault, - AppArmorProfile::Localhost("openshell-supervisor".to_string()), - ] { - validate_apparmor_support(Some(&profile), true) - .expect("confined profile should be accepted when Podman reports AppArmor"); - let error = validate_apparmor_support(Some(&profile), false) - .expect_err("confined profile must fail when AppArmor is unavailable"); - assert!(error.to_string().contains("AppArmor is unavailable")); - } - validate_apparmor_support(Some(&AppArmorProfile::Unconfined), false) - .expect("Unconfined does not require AppArmor support"); - validate_apparmor_support(None, false) - .expect("an omitted profile preserves Podman's runtime behavior"); - } - - #[test] - - fn local_podman_cdi_gpu_inventory_maps_nvidia_device_nodes() { - let root = std::env::temp_dir().join(format!( - "openshell-podman-gpu-test-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system time should be after unix epoch") - .as_nanos() - )); - fs::create_dir(&root).expect("create temp dev root"); - fs::write(root.join("nvidia2"), "").expect("create nvidia2"); - fs::write(root.join("nvidiactl"), "").expect("create nvidiactl"); - fs::write(root.join("nvidia0"), "").expect("create nvidia0"); - - let inventory = local_podman_cdi_gpu_inventory_from(&root); - - fs::remove_dir_all(&root).expect("remove temp dev root"); - assert_eq!( - inventory.as_slice(), - &vec![ - "nvidia.com/gpu=0".to_string(), - "nvidia.com/gpu=2".to_string() - ] - ); - } - - #[test] - fn local_podman_cdi_gpu_inventory_maps_dxg_to_all_gpu_fallback() { - let root = std::env::temp_dir().join(format!( - "openshell-podman-dxg-test-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .expect("system time should be after unix epoch") - .as_nanos() - )); - fs::create_dir(&root).expect("create temp dev root"); - fs::write(root.join("dxg"), "").expect("create dxg"); - - let inventory = local_podman_cdi_gpu_inventory_from(&root); - let allow_all_default = local_podman_all_gpu_default_supported_from(&root); - - fs::remove_dir_all(&root).expect("remove temp dev root"); - assert_eq!(inventory.as_slice(), &vec![CDI_GPU_DEVICE_ALL.to_string()]); - assert!(allow_all_default); - } - - #[tokio::test] - async fn validate_sandbox_create_accepts_default_gpu_with_inventory() { - use openshell_core::proto::compute::v1::DriverSandboxSpec; - - let driver = PodmanComputeDriver::for_tests_with_gpu_inventory( - PodmanComputeConfig::default(), - CdiGpuInventory::new(["nvidia.com/gpu=0"]), - ); - let sandbox = DriverSandbox { - spec: Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }), - ..Default::default() - }; - - driver.validate_sandbox_create(&sandbox).await.unwrap(); - } - - #[tokio::test] - async fn validate_sandbox_create_accepts_all_only_inventory_when_dxg_fallback_allowed() { - use openshell_core::proto::compute::v1::DriverSandboxSpec; - - let driver = PodmanComputeDriver::for_tests_with_gpu_inventory_and_all_fallback( - PodmanComputeConfig::default(), - CdiGpuInventory::new([CDI_GPU_DEVICE_ALL]), - true, - ); - let sandbox = DriverSandbox { - spec: Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }), - ..Default::default() - }; - - driver.validate_sandbox_create(&sandbox).await.unwrap(); - } - - #[tokio::test] - async fn validate_sandbox_create_rejects_all_only_inventory_without_dxg_fallback() { - use openshell_core::proto::compute::v1::DriverSandboxSpec; - - let driver = PodmanComputeDriver::for_tests_with_gpu_inventory( - PodmanComputeConfig::default(), - CdiGpuInventory::new([CDI_GPU_DEVICE_ALL]), - ); - let sandbox = DriverSandbox { - spec: Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }), - ..Default::default() - }; - - let err = driver.validate_sandbox_create(&sandbox).await.unwrap_err(); - - assert!(err.to_string().contains("nvidia.com/gpu=all")); - } - - #[tokio::test] - async fn validate_sandbox_create_rejects_host_device_paths() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { - allow_driver_config: true, - ..Default::default() - }); - for device in ["/dev/sda", "/dev", "/dev/sda:/dev/sda:rwm"] { - let sandbox = DriverSandbox { - spec: Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(DriverSandboxTemplate { - driver_config: Some(cdi_devices_config(&[device])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = driver.validate_sandbox_create(&sandbox).await.unwrap_err(); - assert!(matches!(err, ComputeDriverError::InvalidArgument(_))); - assert!(err.to_string().contains("CDI qualified names")); - } - } - - #[tokio::test] - async fn validate_sandbox_create_passes_explicit_cdi_device_id_without_inventory() { - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { - allow_driver_config: true, - ..Default::default() - }); - let sandbox = DriverSandbox { - spec: Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(DriverSandboxTemplate { - driver_config: Some(cdi_devices_config(&["nvidia.com/gpu=0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - - driver.validate_sandbox_create(&sandbox).await.unwrap(); - } - - #[test] - fn driver_default_gpu_selection_consumes_distinct_devices_for_creates() { - use openshell_core::proto::compute::v1::DriverSandboxSpec; - - let driver = PodmanComputeDriver::for_tests_with_gpu_inventory( - PodmanComputeConfig::default(), - CdiGpuInventory::new(["nvidia.com/gpu=0", "nvidia.com/gpu=1"]), - ); - let first_sandbox = DriverSandbox { - id: "sbx-first".to_string(), - name: "first".to_string(), - spec: Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }), - ..Default::default() - }; - let second_sandbox = DriverSandbox { - id: "sbx-second".to_string(), - name: "second".to_string(), - spec: Some(DriverSandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }), - ..Default::default() - }; - - assert_eq!( - driver.gpu_selector.peek_device_ids(1).unwrap(), - vec!["nvidia.com/gpu=0".to_string()] - ); - let first_devices = driver.gpu_selector.next_device_ids(1).unwrap(); - let first_spec = container::build_container_spec_with_token_and_gpu_devices( - &first_sandbox, - &driver.config, - None, - Some(&first_devices), - ) - .unwrap(); - - assert_eq!( - driver.gpu_selector.peek_device_ids(1).unwrap(), - vec!["nvidia.com/gpu=1".to_string()] - ); - let second_devices = driver.gpu_selector.next_device_ids(1).unwrap(); - let second_spec = container::build_container_spec_with_token_and_gpu_devices( - &second_sandbox, - &driver.config, - None, - Some(&second_devices), - ) - .unwrap(); - - assert_eq!( - first_spec["devices"][0]["path"].as_str(), - Some("nvidia.com/gpu=0") - ); - assert_eq!( - second_spec["devices"][0]["path"].as_str(), - Some("nvidia.com/gpu=1") - ); - } - - #[test] - fn supervisor_pull_policy_refreshes_mutable_tags_only() { - assert_eq!( - runtime_image_pull_policy("quay.io/ai-openshell/supervisor:dev"), - "newer" - ); - assert_eq!( - runtime_image_pull_policy("quay.io/ai-openshell/supervisor:latest"), - "newer" - ); - assert_eq!( - runtime_image_pull_policy("quay.io/ai-openshell/supervisor"), - "newer" - ); - assert_eq!( - runtime_image_pull_policy("quay.io/ai-openshell/supervisor:0.0.47-dev.13-g57b71c68f"), - "missing" - ); - assert_eq!( - runtime_image_pull_policy("quay.io/ai-openshell/supervisor@sha256:abc123"), - "missing" - ); - } - - fn test_driver(socket_path: PathBuf) -> PodmanComputeDriver { - let config = PodmanComputeConfig { - allow_driver_config: true, - resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig { - enabled: false, - ..Default::default() - }, - socket_path: Some(socket_path), - stop_timeout_secs: 10, - ..PodmanComputeConfig::default() - }; - PodmanComputeDriver::for_tests(config) - } - - fn test_driver_with_config(mut config: PodmanComputeConfig) -> PodmanComputeDriver { - config.allow_driver_config = true; - config.resource_admission.enabled = false; - PodmanComputeDriver::for_tests(config) - } - - fn json_struct(value: serde_json::Value) -> prost_types::Struct { - let serde_json::Value::Object(object) = value else { - panic!("expected JSON object"); - }; - openshell_core::proto_struct::json_object_to_struct(object) - .expect("test JSON must convert to a protobuf Struct") - } - - fn sandbox_with_volume_mount(volume: &str) -> DriverSandbox { - DriverSandbox { - id: "sandbox-123".to_string(), - name: "demo".to_string(), - namespace: String::new(), - spec: Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - driver_config: Some(json_struct(serde_json::json!({ - "mounts": [{ - "type": "volume", - "source": volume, - "target": "/sandbox/work" - }] - }))), - ..Default::default() - }), - ..Default::default() - }), - status: None, - workspace: String::new(), - } - } - - #[tokio::test] - async fn private_volume_collision_is_not_adopted_or_relabelled() { - let (socket, requests, handle) = spawn_podman_stub( - "admission-collision", - vec![StubResponse::new( - StatusCode::OK, - serde_json::json!({ - "Name":"private-collision", "Driver":"local", "Options":{}, "Labels":{} - }) - .to_string(), - )], - ); - let driver = test_driver(socket.clone()); - assert!( - driver - .client - .create_owned_volume("private-collision", "sandbox-123", "team-a", None) - .await - .is_err() - ); - handle.await.unwrap(); - let logged = requests.lock().unwrap(); - assert_eq!(logged.len(), 1); - assert!(logged[0].starts_with("GET ")); - let _ = fs::remove_file(socket); - } - - #[tokio::test] - async fn admission_requires_explicit_volume_labels_and_workspace_match() { - for (labels, allowed) in [ - (serde_json::json!(null), false), - (serde_json::json!({}), false), - ( - serde_json::json!({"openshell.ai/sandbox-attachable":"true","openshell.ai/sandbox-attachable-workspace":"other"}), - false, - ), - ( - serde_json::json!({"openshell.ai/sandbox-attachable":"true","openshell.ai/sandbox-attachable-workspace":"team-a"}), - true, - ), - ] { - let (socket, requests, handle) = spawn_podman_stub("admission-labels", vec![StubResponse::new(StatusCode::OK, - serde_json::json!({"Name":"existing","Driver":"local","Options":{},"Labels":labels}).to_string())]); - let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { - socket_path: Some(socket.clone()), - allow_driver_config: true, - ..Default::default() - }); - let mut sandbox = sandbox_with_volume_mount("existing"); - sandbox.workspace = "team-a".into(); - let result = driver.validate_sandbox_create(&sandbox).await; - if !allowed { - assert!( - result - .as_ref() - .unwrap_err() - .to_string() - .contains("podman volume 'existing'") - ); - } - assert_eq!(result.is_ok(), allowed); - handle.await.unwrap(); - assert!( - requests - .lock() - .unwrap() - .iter() - .all(|request| request.starts_with("GET ")) - ); - let _ = fs::remove_file(socket); - } - } - - #[tokio::test] - async fn admission_accepts_workspace_volume_owned_by_workload_identity() { - let owned = serde_json::json!({"o":"uid=1234,gid=1235","UID":"1234","GID":"1235"}); - for (workspace_options, channel_options, allowed) in [ - (owned.clone(), serde_json::json!({}), true), - // Created by a gateway that did not set volume ownership. - (serde_json::json!({}), serde_json::json!({}), true), - ( - serde_json::json!({"o":"uid=0,gid=0","UID":"0","GID":"0"}), - serde_json::json!({}), - false, - ), - (owned.clone(), owned.clone(), false), - ] { - let sandbox_id = "sandbox-owned"; - let workspace_volume = container::volume_name(sandbox_id); - let channel_volume = crate::isolation::channel_volume_name(sandbox_id); - let volume = |name: &str, options: &serde_json::Value| { - StubResponse::new( - StatusCode::OK, - serde_json::json!({ - "Name": name, "Driver": "local", "Options": options, - "Labels": {LABEL_SANDBOX_ID: sandbox_id, container::LABEL_SANDBOX_WORKSPACE: "team-a"} - }) - .to_string(), - ) - }; - let container = serde_json::json!({ - "Id": "workload", "Name": "workload", "State": {"Status": "created", "Running": false}, - "Config": { - "User": "1234:1235", - "Labels": { - LABEL_SANDBOX_ID: sandbox_id, - container::LABEL_SANDBOX_WORKSPACE: "team-a", - openshell_core::resource_admission::CONFIG_USED_LABEL: "false", - openshell_core::resource_admission::IDENTITIES_LABEL: "{}", - } - }, - "Mounts": [ - {"Type": "volume", "Name": workspace_volume}, - {"Type": "volume", "Name": channel_volume}, - ] - }); - let (socket, _, handle) = spawn_podman_stub( - "admission-owned", - vec![ - StubResponse::new(StatusCode::OK, container.to_string()), - volume(&workspace_volume, &workspace_options), - volume(&channel_volume, &channel_options), - ], - ); - let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { - socket_path: Some(socket.clone()), - resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig { - enabled: true, - ..Default::default() - }, - ..Default::default() - }); - let result = driver.admit_container_resources("workload").await; - assert_eq!( - result.is_ok(), - allowed, - "workspace {workspace_options}, channel {channel_options}: {result:?}" - ); - if allowed { - handle.await.unwrap(); - } else { - handle.abort(); - } - let _ = fs::remove_file(socket); - } - } - - #[tokio::test] - async fn admission_driver_config_denial_does_not_contact_podman() { - for enabled in [true, false] { - let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig { - resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig { - enabled, - ..Default::default() - }, - ..Default::default() - }); - let error = driver - .validate_sandbox_create(&sandbox_with_volume_mount("existing")) - .await - .unwrap_err(); - assert!(error.to_string().contains("allow_driver_config")); - } - } - - fn api_path(path: &str) -> String { - format!("/v5.0.0{path}") - } - - fn volume_deletes(request_log: &std::sync::Mutex>) -> Vec { - request_log - .lock() - .expect("request log lock should not be poisoned") - .iter() - .filter(|request| request.starts_with("DELETE /v5.0.0/libpod/volumes/")) - .cloned() - .collect() - } - - #[test] - fn podman_local_volume_with_bind_option_is_bind_backed() { - let volume = VolumeInspect { - created_at: None, - labels: None, - name: String::new(), - driver: "local".to_string(), - options: HashMap::from([("o".to_string(), "rw,bind".to_string())]), - }; - - assert!(podman_volume_is_bind_backed(&volume)); - } - - #[test] - fn podman_local_volume_with_rbind_option_is_bind_backed() { - let volume = VolumeInspect { - created_at: None, - labels: None, - name: String::new(), - driver: "local".to_string(), - options: HashMap::from([("o".to_string(), "rw,rbind".to_string())]), - }; - - assert!(podman_volume_is_bind_backed(&volume)); - } - - #[test] - fn podman_empty_driver_volume_with_bind_option_is_bind_backed() { - let volume = VolumeInspect { - created_at: None, - labels: None, - name: String::new(), - driver: String::new(), - options: HashMap::from([("o".to_string(), "bind".to_string())]), - }; - - assert!(podman_volume_is_bind_backed(&volume)); - } - - #[test] - fn podman_local_volume_without_bind_option_is_not_bind_backed() { - let volume = VolumeInspect { - created_at: None, - labels: None, - name: String::new(), - driver: "local".to_string(), - options: HashMap::from([("o".to_string(), "addr=127.0.0.1,rw".to_string())]), - }; - - assert!(!podman_volume_is_bind_backed(&volume)); - } - - #[test] - fn podman_nonlocal_volume_with_bind_option_is_not_bind_backed() { - let volume = VolumeInspect { - created_at: None, - labels: None, - name: String::new(), - driver: "custom".to_string(), - options: HashMap::from([("o".to_string(), "bind".to_string())]), - }; - - assert!(!podman_volume_is_bind_backed(&volume)); - } - - #[tokio::test] - async fn validate_sandbox_rejects_bind_backed_named_volume_unless_enabled() { - let (socket_path, request_log, handle) = spawn_podman_stub( - "bind-volume-disabled", - vec![StubResponse::new( - StatusCode::OK, - r#"{"Name":"work-bind","Driver":"local","Options":{"type":"none","o":"rw,bind","device":"/srv/work"}}"#, - )], - ); - let driver = test_driver(socket_path.clone()); - let sandbox = sandbox_with_volume_mount("work-bind"); - - let err = driver - .validate_sandbox_create(&sandbox) - .await - .expect_err("bind-backed volume should require bind mount opt-in"); - - match err { - ComputeDriverError::Precondition(message) => { - assert!(message.contains("enable_bind_mounts = true")); - } - other => panic!("expected precondition error, got {other:?}"), - } - handle.await.expect("stub task should finish"); - assert_eq!( - request_log - .lock() - .expect("request log lock should not be poisoned") - .as_slice(), - [format!( - "GET {}", - api_path("/libpod/volumes/work-bind/json") - )] - ); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn validate_sandbox_rejects_rbind_backed_named_volume_unless_enabled() { - let (socket_path, request_log, handle) = spawn_podman_stub( - "rbind-volume-disabled", - vec![StubResponse::new( - StatusCode::OK, - r#"{"Name":"work-rbind","Driver":"local","Options":{"type":"none","o":"rw,rbind","device":"/srv/work"}}"#, - )], - ); - let driver = test_driver(socket_path.clone()); - let sandbox = sandbox_with_volume_mount("work-rbind"); - - let err = driver - .validate_sandbox_create(&sandbox) - .await - .expect_err("rbind-backed volume should require bind mount opt-in"); - - match err { - ComputeDriverError::Precondition(message) => { - assert!(message.contains("enable_bind_mounts = true")); - } - other => panic!("expected precondition error, got {other:?}"), - } - handle.await.expect("stub task should finish"); - assert_eq!( - request_log - .lock() - .expect("request log lock should not be poisoned") - .as_slice(), - [format!( - "GET {}", - api_path("/libpod/volumes/work-rbind/json") - )] - ); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn validate_sandbox_allows_bind_backed_named_volume_when_enabled() { - let (socket_path, _request_log, handle) = spawn_podman_stub( - "bind-volume-enabled", - vec![StubResponse::new( - StatusCode::OK, - r#"{"Name":"work-bind","Driver":"local","Options":{"type":"none","o":"rw,bind","device":"/srv/work"}}"#, - )], - ); - let config = PodmanComputeConfig { - socket_path: Some(socket_path.clone()), - enable_bind_mounts: true, - ..PodmanComputeConfig::default() - }; - let driver = test_driver_with_config(config); - let sandbox = sandbox_with_volume_mount("work-bind"); - - driver - .validate_sandbox_create(&sandbox) - .await - .expect("bind-backed volume should be allowed when bind mounts are enabled"); - - handle.await.expect("stub task should finish"); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn delete_sandbox_cleans_up_volume_when_container_is_already_gone() { - let sandbox_id = "sandbox-123"; - let volume_name = container::volume_name(sandbox_id); - let (socket_path, request_log, handle) = spawn_podman_stub( - "delete-not-found", - vec![ - StubResponse::new(StatusCode::NOT_FOUND, ""), // no companion - StubResponse::new(StatusCode::NOT_FOUND, ""), // channel volume already gone - // list_containers returns empty (container already gone) - StubResponse::new(StatusCode::OK, "[]"), - StubResponse::new(StatusCode::NOT_FOUND, ""), // control volume already gone - owned_volume_response(&volume_name, sandbox_id, Some((1234, 1235))), - // remove_volume - StubResponse::new(StatusCode::NO_CONTENT, ""), - ], - ); - let driver = test_driver(socket_path.clone()); - - let deleted = driver - .delete_sandbox(sandbox_id) - .await - .expect("delete should succeed"); - - assert!(!deleted, "missing container should report deleted=false"); - handle.await.expect("stub task should finish"); - assert_eq!( - volume_deletes(&request_log), - ["DELETE /v5.0.0/libpod/volumes/openshell-sandbox-sandbox-123-workspace"] - ); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn delete_sandbox_keeps_unowned_volumes_when_container_is_already_gone() { - let sandbox_id = "sandbox-123"; - let unlabeled_channel = serde_json::json!({ - "Name": crate::isolation::channel_volume_name(sandbox_id), - "Driver": "local", "Options": {}, "Labels": {} - }); - let (socket_path, request_log, handle) = spawn_podman_stub( - "delete-unowned-not-found", - vec![ - StubResponse::new(StatusCode::NOT_FOUND, ""), // no companion - StubResponse::new(StatusCode::OK, unlabeled_channel.to_string()), - StubResponse::new(StatusCode::OK, "[]"), // no workload - StubResponse::new(StatusCode::NOT_FOUND, ""), // no control volume - owned_volume_response( - &container::volume_name(sandbox_id), - "sandbox-other", - Some((1234, 1235)), - ), - StubResponse::new(StatusCode::NOT_FOUND, ""), // token secret - StubResponse::new(StatusCode::NOT_FOUND, ""), // resolver secret - StubResponse::new(StatusCode::NOT_FOUND, ""), // proxy-auth secret - StubResponse::new(StatusCode::NOT_FOUND, ""), // TLS CA secret - ], - ); - - let deleted = test_driver(socket_path.clone()) - .delete_sandbox(sandbox_id) - .await - .expect("delete should succeed"); - - assert!(!deleted, "missing container should report deleted=false"); - tokio::time::timeout(Duration::from_secs(5), handle) - .await - .expect("stub should receive every scripted request") - .expect("stub task should finish"); - assert_eq!(volume_deletes(&request_log), Vec::::new()); - let _ = fs::remove_file(socket_path); - } - - /// Write a valid `user:pass` credential to a unique path for proxy-auth - /// secret tests. Caller removes it. - fn write_proxy_auth_file(test_name: &str) -> PathBuf { - let path = crate::test_utils::unique_socket_path(test_name).with_extension("auth"); - fs::write(&path, "user:pass\n").expect("write proxy auth file"); - path - } - - fn proxy_auth_config(socket_path: PathBuf, auth_file: &Path) -> PodmanComputeConfig { - PodmanComputeConfig { - socket_path: Some(socket_path), - stop_timeout_secs: 10, - proxy_auth_file: Some(auth_file.to_string_lossy().into_owned()), - proxy_auth_allow_insecure: Some(true), - ..PodmanComputeConfig::default() - } - } - - fn plain_sandbox(id: &str, name: &str) -> DriverSandbox { - DriverSandbox { - id: id.to_string(), - name: name.to_string(), - namespace: String::new(), - workspace: String::new(), - spec: Some(DriverSandboxSpec { - launch_authentication: encoded_launch_authentication(), - ..Default::default() - }), - status: None, - } - } - - #[test] - fn child_environment_preserves_precedence_and_strips_control_keys() { - let mut sandbox = plain_sandbox("sandbox", "agent"); - sandbox.spec = Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - environment: HashMap::from([ - ("TEMPLATE_ONLY".to_string(), "template".to_string()), - ("OVERRIDE".to_string(), "template".to_string()), - ]), - ..Default::default() - }), - environment: HashMap::from([ - ("REQUEST_ONLY".to_string(), "request".to_string()), - ("OVERRIDE".to_string(), "request".to_string()), - ("OPENSHELL_SANDBOX_TOKEN".to_string(), "spoofed".to_string()), - ]), - ..Default::default() - }); - let image_env = vec![ - "IMAGE_ONLY=image".to_string(), - "OVERRIDE=image".to_string(), - "OPENSHELL_ENDPOINT=spoofed".to_string(), - ]; - - let environment = podman_child_environment(&sandbox, &image_env); - - assert_eq!( - environment.get("IMAGE_ONLY").map(String::as_str), - Some("image") - ); - assert_eq!( - environment.get("TEMPLATE_ONLY").map(String::as_str), - Some("template") - ); - assert_eq!( - environment.get("REQUEST_ONLY").map(String::as_str), - Some("request") - ); - assert_eq!( - environment.get("OVERRIDE").map(String::as_str), - Some("request") - ); - assert!(!environment.keys().any(|key| key.starts_with("OPENSHELL_"))); - } - - fn proxy_auth_secret_delete_request(sandbox_id: &str) -> String { - format!( - "DELETE {}", - api_path(&format!( - "/libpod/secrets/{}", - container::proxy_auth_secret_name(sandbox_id) - )) - ) - } - - fn resolver_secret_delete_request(sandbox_id: &str) -> String { - format!( - "DELETE {}", - api_path(&format!( - "/libpod/secrets/{}", - container::resolver_secret_name(sandbox_id) - )) - ) - } - - fn restart_responses() -> Vec { - let mut archive = tar::Builder::new(Vec::new()); - let identity = openshell_isolation_interface::contract::ResolvedWorkloadIdentity::new( - 1000, - 1001, - vec![], - "image".into(), - "sha256:image".into(), - ) - .unwrap(); - let bundle = serde_json::to_vec(&crate::isolation::RestartMetadata { - runtime_initiated: false, - generation: "generation-1".to_string(), - workload_identity: identity, - child_env: HashMap::new(), - }) - .unwrap(); - let mut header = tar::Header::new_gnu(); - header.set_size(bundle.len() as u64); - header.set_mode(0o600); - header.set_cksum(); - archive - .append_data(&mut header, "restart-metadata.json", bundle.as_slice()) - .unwrap(); - vec![ - StubResponse::new(StatusCode::NO_CONTENT, ""), // supervisor stop - StubResponse::new( - StatusCode::OK, - r#"{"Id":"supervisor","Name":"supervisor","State":{"Status":"exited","Running":false},"Config":{}}"#, - ), - StubResponse::new(StatusCode::OK, archive.into_inner().unwrap()), - StubResponse::new(StatusCode::OK, "").with_archive_members(channel_archive_members()), - StubResponse::new(StatusCode::OK, ""), // refreshed supervisor auth and runtime descriptor - fence_response(), - StubResponse::new(StatusCode::NO_CONTENT, ""), // workload start - StubResponse::new(StatusCode::NO_CONTENT, ""), // supervisor start - ] - } - - fn fence_response() -> StubResponse { - #[derive(serde::Serialize)] - #[serde(rename_all = "PascalCase")] - struct HostConfig { - network_mode: &'static str, - privileged: bool, - } - #[derive(serde::Serialize)] - #[serde(rename_all = "PascalCase")] - struct Networks { - networks: std::collections::BTreeMap, - } - #[derive(serde::Serialize)] - #[serde(rename_all = "PascalCase")] - struct Fence { - host_config: HostConfig, - network_settings: Networks, - } - StubResponse::new( - StatusCode::OK, - serde_json::to_vec(&Fence { - host_config: HostConfig { - network_mode: "none", - privileged: false, - }, - network_settings: Networks { - networks: std::collections::BTreeMap::default(), - }, - }) - .unwrap(), - ) - } - - fn created_response(id: &'static str) -> StubResponse { - #[derive(serde::Serialize)] - struct Created { - #[serde(rename = "Id")] - id: &'static str, - } - StubResponse::new( - StatusCode::CREATED, - serde_json::to_vec(&Created { id }).unwrap(), - ) - } - - fn image_response(id: &'static str) -> StubResponse { - #[derive(serde::Serialize)] - #[serde(rename_all = "PascalCase")] - struct Config { - user: &'static str, - } - #[derive(serde::Serialize)] - #[serde(rename_all = "PascalCase")] - struct Image { - id: &'static str, - config: Config, - } - StubResponse::new( - StatusCode::OK, - serde_json::to_vec(&Image { - id, - config: Config { user: "1234:1235" }, - }) - .unwrap(), - ) - } - - fn sandbox_binary_archive_response() -> StubResponse { - let mut archive = Vec::new(); - { - let mut builder = tar::Builder::new(&mut archive); - let payload = b"\x7fELF-test-sandbox"; - let mut header = tar::Header::new_gnu(); - header.set_path("openshell-sandbox").unwrap(); - header.set_size(payload.len() as u64); - header.set_mode(0o755); - header.set_cksum(); - builder.append(&header, payload.as_slice()).unwrap(); - builder.finish().unwrap(); - } - StubResponse::new(StatusCode::OK, archive) - } - - fn create_setup_responses(proxy_secret: bool, sandbox_id: &str) -> Vec { - let mut responses = vec![ - StubResponse::new(StatusCode::OK, "{}"), // sandbox runtime pull - StubResponse::new(StatusCode::OK, "{}"), // supervisor pull - StubResponse::new(StatusCode::OK, "{}"), // workload pull - image_response("sha256:sandbox"), - created_response("identity-reader"), - StubResponse::new(StatusCode::NOT_FOUND, ""), // reserved hierarchy absent - StubResponse::new(StatusCode::NOT_FOUND, ""), // optional passwd - StubResponse::new(StatusCode::NOT_FOUND, ""), // optional group - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove stopped reader - image_response("sha256:sandbox-runtime"), - image_response("sha256:supervisor"), - StubResponse::new(StatusCode::NOT_FOUND, ""), // no existing private workspace - StubResponse::new(StatusCode::CREATED, "{}"), // workspace volume - owned_volume_response( - &container::volume_name(sandbox_id), - sandbox_id, - Some((1234, 1235)), // the stub image's OCI user - ), - StubResponse::new(StatusCode::CREATED, "{}"), // resolver secret - ]; - if proxy_secret { - responses.push(StubResponse::new(StatusCode::CREATED, "{}")); - } - responses.extend([ - image_response("sha256:sandbox-runtime"), - created_response("sandbox-runtime-extractor"), - sandbox_binary_archive_response(), - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove extractor - ]); - responses.push(StubResponse::new(StatusCode::NOT_FOUND, "")); - responses.push(StubResponse::new(StatusCode::CREATED, "{}")); // channel volume - responses.push(owned_volume_response( - &crate::isolation::channel_volume_name(sandbox_id), - sandbox_id, - None, - )); - responses.push(StubResponse::new(StatusCode::NOT_FOUND, "")); - responses.push(StubResponse::new(StatusCode::CREATED, "{}")); - responses.push(owned_volume_response( - &crate::isolation::control_volume_name(sandbox_id), - sandbox_id, - None, - )); - responses - } - - fn owned_volume_response( - name: &str, - sandbox_id: &str, - owner: Option<(u32, u32)>, - ) -> StubResponse { - let options = owner.map_or_else( - || serde_json::json!({}), - |(uid, gid)| { - serde_json::json!({ - "o": format!("uid={uid},gid={gid}"), - "UID": uid.to_string(), - "GID": gid.to_string(), - }) - }, - ); - StubResponse::new( - StatusCode::OK, - serde_json::json!({ - "Name": name, "Driver": "local", "Options": options, - "Labels": {LABEL_SANDBOX_ID: sandbox_id, container::LABEL_SANDBOX_WORKSPACE: ""} - }) - .to_string(), - ) - } - - fn create_launch_responses() -> Vec { - vec![ - created_response("workload"), - fence_response(), - StubResponse::new(StatusCode::OK, "").with_archive_members(channel_archive_members()), - StubResponse::new(StatusCode::OK, "").with_archive_members(&["."]), // control volume - StubResponse::new(StatusCode::OK, "").with_archive_members(&["."]), - created_response("supervisor"), - StubResponse::new(StatusCode::OK, ""), // supervisor archive - StubResponse::new(StatusCode::NO_CONTENT, ""), // workload start - StubResponse::new(StatusCode::NO_CONTENT, ""), // supervisor start - ] - } - - fn channel_archive_members() -> &'static [&'static str] { - &[ - ".", - "sandbox", - "sandbox/bootstrap.json", - "sandbox/server.crt", - "sandbox/server.key", - ] - } - - #[tokio::test] - async fn reserved_image_control_root_fails_before_workload_or_secrets() { - let (path, requests, handle) = spawn_podman_stub( - "reserved-control-root", - vec![ - StubResponse::new(StatusCode::OK, "{}"), - StubResponse::new(StatusCode::OK, "{}"), - StubResponse::new(StatusCode::OK, "{}"), - image_response("sha256:image"), - created_response("identity-reader"), - StubResponse::new(StatusCode::OK, "existing reserved path"), - StubResponse::new(StatusCode::NO_CONTENT, ""), - ], - ); - let error = test_driver(path.clone()) - .create_sandbox(&plain_sandbox("id", "name")) - .await - .unwrap_err(); - assert!(error.to_string().contains("reserved /.openshell")); - handle.await.unwrap(); - assert!( - !requests - .lock() - .unwrap() - .iter() - .any(|request| request.contains("/libpod/volumes") - || request.contains("/libpod/secrets")) - ); - let _ = fs::remove_file(path); - } - - #[tokio::test] - async fn create_sandbox_removes_proxy_auth_secret_on_container_create_failure() { - // A credential secret is staged before the container is created, so a - // container-create failure must remove it — no credential residue. - let sandbox_id = "sandbox-cc"; - let auth_file = write_proxy_auth_file("create-fail"); - let (socket_path, request_log, handle) = spawn_podman_stub( - "create-container-fail", - create_setup_responses(true, sandbox_id) - .into_iter() - .chain([ - StubResponse::new(StatusCode::INTERNAL_SERVER_ERROR, "create failed"), - owned_volume_response( - &crate::isolation::channel_volume_name(sandbox_id), - sandbox_id, - None, - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), // channel - owned_volume_response( - &crate::isolation::control_volume_name(sandbox_id), - sandbox_id, - None, - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), // control - owned_volume_response( - &container::volume_name(sandbox_id), - sandbox_id, - Some((1234, 1235)), - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), // workspace - StubResponse::new(StatusCode::NO_CONTENT, ""), // resolver secret - StubResponse::new(StatusCode::NO_CONTENT, ""), // proxy secret - ]) - .collect(), - ); - let driver = test_driver_with_config(proxy_auth_config(socket_path.clone(), &auth_file)); - let mut sandbox = plain_sandbox(sandbox_id, "demo"); - sandbox.spec = Some(DriverSandboxSpec { - launch_authentication: encoded_launch_authentication(), - ..DriverSandboxSpec::default() - }); - - driver - .create_sandbox(&sandbox) - .await - .expect_err("container create should fail"); - - handle.await.expect("stub task should finish"); - let requests = request_log - .lock() - .expect("request log lock should not be poisoned") - .clone(); - assert!( - requests.contains(&proxy_auth_secret_delete_request(sandbox_id)), - "proxy-auth secret must be removed on container-create failure: {requests:?}" - ); - assert!( - requests.contains(&resolver_secret_delete_request(sandbox_id)), - "resolver secret must be removed on container-create failure: {requests:?}" - ); - let _ = fs::remove_file(&auth_file); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn create_sandbox_rollback_skips_unmanaged_workspace_volume() { - let sandbox_id = "sandbox-workdir"; - // Give the workload image a custom WORKDIR and drop the workspace volume - // inspect, create, and verify responses that it no longer reaches. - let mut responses = create_setup_responses(false, sandbox_id); - responses[3] = StubResponse::new( - StatusCode::OK, - r#"{"Id":"sha256:sandbox","Config":{"User":"1234:1235","WorkingDir":"/workspace/project"}}"#, - ); - responses.drain(11..14); - responses.extend([ - StubResponse::new(StatusCode::INTERNAL_SERVER_ERROR, "create failed"), - owned_volume_response( - &crate::isolation::channel_volume_name(sandbox_id), - sandbox_id, - None, - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), // channel - owned_volume_response( - &crate::isolation::control_volume_name(sandbox_id), - sandbox_id, - None, - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), // control - StubResponse::new(StatusCode::NO_CONTENT, ""), // resolver secret - ]); - let (socket_path, request_log, handle) = - spawn_podman_stub("create-custom-workdir-fail", responses); - - test_driver(socket_path.clone()) - .create_sandbox(&plain_sandbox(sandbox_id, "demo")) - .await - .expect_err("container create should fail"); - - tokio::time::timeout(Duration::from_secs(5), handle) - .await - .expect("stub should receive every scripted request") - .expect("stub task should finish"); - let requests = request_log - .lock() - .expect("request log lock should not be poisoned"); - let workspace = container::volume_name(sandbox_id); - assert!( - !requests.iter().any(|request| request.contains(&workspace)), - "custom WORKDIR create must not touch {workspace}: {requests:?}" - ); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn create_sandbox_removes_proxy_auth_secret_on_start_failure() { - // The container is created but fails to start; the staged credential - // secret must still be removed. - let sandbox_id = "sandbox-sf"; - let auth_file = write_proxy_auth_file("start-fail"); - let (socket_path, request_log, handle) = spawn_podman_stub( - "create-start-fail", - create_setup_responses(true, sandbox_id) - .into_iter() - .chain(create_launch_responses().into_iter().take(8)) - .chain([ - StubResponse::new(StatusCode::INTERNAL_SERVER_ERROR, "supervisor start failed"), - StubResponse::new(StatusCode::NO_CONTENT, ""), // supervisor - StubResponse::new(StatusCode::NO_CONTENT, ""), // workload - owned_volume_response( - &crate::isolation::channel_volume_name(sandbox_id), - sandbox_id, - None, - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), // channel - owned_volume_response( - &crate::isolation::control_volume_name(sandbox_id), - sandbox_id, - None, - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), // control - owned_volume_response( - &container::volume_name(sandbox_id), - sandbox_id, - Some((1234, 1235)), - ), - StubResponse::new(StatusCode::NO_CONTENT, ""), // workspace - StubResponse::new(StatusCode::NO_CONTENT, ""), // resolver secret - StubResponse::new(StatusCode::NO_CONTENT, ""), // proxy secret - ]) - .collect(), - ); - let driver = test_driver_with_config(proxy_auth_config(socket_path.clone(), &auth_file)); - let mut sandbox = plain_sandbox(sandbox_id, "demo"); - sandbox.spec = Some(DriverSandboxSpec { - launch_authentication: encoded_launch_authentication(), - ..DriverSandboxSpec::default() - }); - - driver - .create_sandbox(&sandbox) - .await - .expect_err("container start should fail"); - - handle.await.expect("stub task should finish"); - let requests = request_log - .lock() - .expect("request log lock should not be poisoned") - .clone(); - assert!( - requests.contains(&proxy_auth_secret_delete_request(sandbox_id)), - "proxy-auth secret must be removed on start failure: {requests:?}" - ); - assert!( - requests.contains(&resolver_secret_delete_request(sandbox_id)), - "resolver secret must be removed on start failure: {requests:?}" - ); - let _ = fs::remove_file(&auth_file); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn delete_sandbox_removes_proxy_auth_secret() { - // Deleting a sandbox (here already gone out of band) must remove the - // per-sandbox proxy-auth secret so credentials never outlive it. - let sandbox_id = "sandbox-del"; - let (socket_path, request_log, handle) = spawn_podman_stub( - "delete-proxy-auth", - vec![ - StubResponse::new(StatusCode::NOT_FOUND, ""), // no companion - StubResponse::new(StatusCode::NOT_FOUND, ""), // no channel volume - StubResponse::new(StatusCode::OK, "[]"), // list_containers (not found) - StubResponse::new(StatusCode::NOT_FOUND, ""), // no control volume - StubResponse::new(StatusCode::NOT_FOUND, ""), // no workspace volume - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove token secret - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove resolver secret - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove proxy-auth secret - ], - ); - let driver = test_driver(socket_path.clone()); - - driver - .delete_sandbox(sandbox_id) - .await - .expect("delete should succeed"); - - handle.await.expect("stub task should finish"); - let requests = request_log - .lock() - .expect("request log lock should not be poisoned") - .clone(); - assert!( - requests.contains(&proxy_auth_secret_delete_request(sandbox_id)), - "proxy-auth secret must be removed on delete: {requests:?}" - ); - assert!( - requests.contains(&resolver_secret_delete_request(sandbox_id)), - "resolver secret must be removed on delete: {requests:?}" - ); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn delete_sandbox_finds_container_by_label_and_removes() { - let sandbox_id = "sandbox-request-id"; - let container_id = "abc123def456"; - let container_name = "openshell-default--demo-sandbox-request-id"; - let volume_name = container::volume_name(sandbox_id); - let channel_volume = crate::isolation::channel_volume_name(sandbox_id); - let control_volume = crate::isolation::control_volume_name(sandbox_id); - let list_body = serde_json::json!([{ - "Id": container_id, - "Names": [container_name], - "State": "running", - "Labels": { - LABEL_SANDBOX_ID: sandbox_id - } - }]) - .to_string(); - let (socket_path, request_log, handle) = spawn_podman_stub( - "delete-label-lookup", - vec![ - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove companion - owned_volume_response(&channel_volume, sandbox_id, None), - StubResponse::new(StatusCode::CONFLICT, ""), // channel still attached - // list_containers by label - StubResponse::new(StatusCode::OK, list_body), - // single timed remove_container operation - StubResponse::new(StatusCode::NO_CONTENT, ""), - owned_volume_response(&control_volume, sandbox_id, None), - StubResponse::new(StatusCode::NO_CONTENT, ""), // control volume - // channel volume, now detached - owned_volume_response(&channel_volume, sandbox_id, None), - StubResponse::new(StatusCode::NO_CONTENT, ""), - // remove_volume - owned_volume_response(&volume_name, sandbox_id, None), - StubResponse::new(StatusCode::NO_CONTENT, ""), - ], - ); - let driver = test_driver(socket_path.clone()); - - let deleted = driver - .delete_sandbox(sandbox_id) - .await - .expect("delete should succeed"); - - assert!(deleted, "existing container should report deleted=true"); - handle.await.expect("stub task should finish"); - let requests = request_log - .lock() - .expect("request log lock should not be poisoned") - .clone(); - assert!(requests.contains(&format!( - "DELETE {}", - api_path(&format!( - "/libpod/containers/{container_id}?force=true&volumes=true&timeout=10" - )) - ))); - assert_eq!( - volume_deletes(&request_log), - [ - "DELETE /v5.0.0/libpod/volumes/openshell-channel-sandbox-request-id", - "DELETE /v5.0.0/libpod/volumes/openshell-control-sandbox-request-id", - "DELETE /v5.0.0/libpod/volumes/openshell-channel-sandbox-request-id", - "DELETE /v5.0.0/libpod/volumes/openshell-sandbox-sandbox-request-id-workspace", - ] - ); - let _ = fs::remove_file(socket_path); - } - - #[tokio::test] - async fn delete_sandbox_keeps_unowned_workspace_volume_after_container_removal() { - let sandbox_id = "sandbox-123"; - let channel_volume = crate::isolation::channel_volume_name(sandbox_id); - let control_volume = crate::isolation::control_volume_name(sandbox_id); - let list_body = serde_json::json!([{ - "Id": "workload", "State": "running", "Labels": {LABEL_SANDBOX_ID: sandbox_id} - }]); - // A custom-WORKDIR sandbox never creates its workspace volume. - let unlabeled_workspace = serde_json::json!({ - "Name": container::volume_name(sandbox_id), - "Driver": "local", "Options": {}, "Labels": {} - }); - let (socket_path, request_log, handle) = spawn_podman_stub( - "delete-unowned-workspace", - vec![ - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove companion - owned_volume_response(&channel_volume, sandbox_id, None), - StubResponse::new(StatusCode::CONFLICT, ""), // channel still attached - StubResponse::new(StatusCode::OK, list_body.to_string()), - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove workload - owned_volume_response(&control_volume, sandbox_id, None), - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove control - owned_volume_response(&channel_volume, sandbox_id, None), - StubResponse::new(StatusCode::NO_CONTENT, ""), // remove channel - StubResponse::new(StatusCode::OK, unlabeled_workspace.to_string()), - StubResponse::new(StatusCode::NO_CONTENT, ""), // token secret - StubResponse::new(StatusCode::NO_CONTENT, ""), // resolver secret - StubResponse::new(StatusCode::NO_CONTENT, ""), // proxy-auth secret - StubResponse::new(StatusCode::NO_CONTENT, ""), // TLS CA secret - ], - ); - - let deleted = test_driver(socket_path.clone()) - .delete_sandbox(sandbox_id) - .await - .expect("delete should succeed"); - - assert!(deleted, "existing container should report deleted=true"); - tokio::time::timeout(Duration::from_secs(5), handle) - .await - .expect("stub should receive every scripted request") - .expect("stub task should finish"); - assert_eq!( - volume_deletes(&request_log), - [ - "DELETE /v5.0.0/libpod/volumes/openshell-channel-sandbox-123", - "DELETE /v5.0.0/libpod/volumes/openshell-control-sandbox-123", - "DELETE /v5.0.0/libpod/volumes/openshell-channel-sandbox-123", - ] - ); - let _ = fs::remove_file(socket_path); - } - - #[test] - fn userns_remaps_uids_cases() { - assert!(!userns_remaps_uids(None)); - assert!(!userns_remaps_uids(Some("host"))); - assert!(!userns_remaps_uids(Some("keep-id"))); - assert!(userns_remaps_uids(Some("auto"))); - assert!(userns_remaps_uids(Some("auto:size=65536"))); - assert!(userns_remaps_uids(Some("no-map"))); - assert!(userns_remaps_uids(Some("private"))); - } - - #[test] - fn capabilities_report_static_resource_support() { - let driver = PodmanComputeDriver::for_tests(PodmanComputeConfig::default()); - let resources = driver - .capabilities() - .unwrap() - .resource_capabilities - .unwrap(); - assert!(resources.cpu.unwrap().limit_supported); - assert!(resources.memory.unwrap().limit_supported); - let gpu = resources.gpu.unwrap(); - assert!(gpu.default_selection_supported); - assert!(gpu.count_selection_supported); - } - - #[test] - fn operator_network_trust_stages_immutable_artifact_from_readable_source() { - use std::os::unix::fs::PermissionsExt as _; - - let mut ca_params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); - ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); - let ca_key = openshell_crypto::pki::generate_keypair().unwrap(); - let ca = openshell_crypto::pki::self_signed(ca_params, &ca_key).unwrap(); - let source = std::env::temp_dir().join(format!( - "openshell-operator-ca-{}-{}.crt", - std::process::id(), - uuid::Uuid::new_v4() - )); - fs::write(&source, ca.pem()).unwrap(); - // The operator-owned source is deliberately writable `0644`, which - // the immutable-artifact verification must never see. - fs::set_permissions(&source, fs::Permissions::from_mode(0o644)).unwrap(); - - let (bundle, staging) = - operator_network_trust(source.to_str().unwrap()).expect("stage operator trust"); - let artifact = bundle.artifact_path(); - assert_ne!( - artifact, source, - "staged artifact must not be the source path" - ); - assert!(artifact.starts_with(staging.path())); - // The verification every create/start performs must accept the staged - // artifact without touching the operator's source permissions. - bundle - .verify_artifact() - .expect("staged operator artifact must satisfy immutable verification"); - let source_mode = fs::metadata(&source).unwrap().permissions().mode() & 0o777; - assert_eq!( - source_mode, 0o644, - "operator source permissions must be preserved" - ); - let artifact_mode = fs::metadata(artifact).unwrap().permissions().mode() & 0o777; - assert_eq!(artifact_mode, 0o444, "staged artifact must be read-only"); - let _ = fs::remove_file(&source); - } -} diff --git a/crates/openshell-driver-podman/src/grpc.rs b/crates/openshell-driver-podman/src/grpc.rs deleted file mode 100644 index 5318b3f833..0000000000 --- a/crates/openshell-driver-podman/src/grpc.rs +++ /dev/null @@ -1,741 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![allow(clippy::result_large_err)] // gRPC handlers return Result<_, tonic::Status> - -use futures::{Stream, StreamExt}; -use openshell_core::proto::compute::v1::{ - CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - DeleteWorkspaceRequest, DeleteWorkspaceResponse, EnsureWorkspaceRequest, - EnsureWorkspaceResponse, GetCapabilitiesRequest, GetCapabilitiesResponse, GetSandboxRequest, - GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest, - StartSandboxResponse, StopSandboxRequest, StopSandboxResponse, SuspendSandboxRequest, - SuspendSandboxResponse, ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, - WatchSandboxesEvent, WatchSandboxesRequest, compute_driver_server::ComputeDriver, -}; -use std::pin::Pin; -use tonic::{Request, Response, Status}; - -use crate::PodmanComputeDriver; - -type ComputeDriverWatchStream = - Pin> + Send + 'static>>; - -#[cfg(test)] -type TracedWatchStream = openshell_otel::TracedGrpcStream; - -#[derive(Debug, Clone)] -pub struct ComputeDriverService { - driver: PodmanComputeDriver, - rpc_tracer: openshell_otel::InProcessRpcTracer, -} - -impl ComputeDriverService { - #[must_use] - pub fn new(driver: PodmanComputeDriver) -> Self { - Self { - driver, - rpc_tracer: openshell_otel::InProcessRpcTracer::disabled(), - } - } - - #[must_use] - pub fn new_in_process(driver: PodmanComputeDriver) -> Self { - Self { - driver, - rpc_tracer: openshell_otel::InProcessRpcTracer::enabled(), - } - } -} - -#[tonic::async_trait] -impl openshell_core::compute::ComputeDriver for ComputeDriverService {} - -#[tonic::async_trait] -impl ComputeDriver for ComputeDriverService { - async fn authenticate_sandbox( - &self, - _request: Request, - ) -> Result, Status> - { - self.rpc_tracer - .trace(openshell_otel::rpc::AUTHENTICATE_SANDBOX, async { - Err(Status::unimplemented( - "podman does not authenticate sandbox credentials", - )) - }) - .await - } - - async fn get_capabilities( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::GET_CAPABILITIES, async { - let capabilities = self.driver.capabilities().map_err(Status::from)?; - openshell_core::extension_protocol::validate_gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - "podman", - capabilities.extension.as_ref(), - request.into_inner().gateway, - ) - .map_err(|error| Status::failed_precondition(error.to_string()))?; - Ok(Response::new(capabilities)) - }) - .await - } - - async fn validate_sandbox_create( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::VALIDATE_SANDBOX_CREATE, async { - let sandbox = request - .into_inner() - .sandbox - .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; - self.driver - .validate_sandbox_create(&sandbox) - .await - .map_err(Status::from)?; - Ok(Response::new(ValidateSandboxCreateResponse {})) - }) - .await - } - - async fn get_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::GET_SANDBOX, async { - let request = request.into_inner(); - if request.sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox_id is required")); - } - let sandbox = self - .driver - .get_sandbox(&request.sandbox_id) - .await - .map_err(Status::from)? - .ok_or_else(|| Status::not_found("sandbox not found"))?; - Ok(Response::new(GetSandboxResponse { - sandbox: Some(sandbox), - })) - }) - .await - } - - async fn list_sandboxes( - &self, - _request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::LIST_SANDBOXES, async { - let sandboxes = self.driver.list_sandboxes().await.map_err(Status::from)?; - Ok(Response::new(ListSandboxesResponse { sandboxes })) - }) - .await - } - - async fn create_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::CREATE_SANDBOX, async { - let sandbox = request - .into_inner() - .sandbox - .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; - Box::pin(self.driver.create_sandbox(&sandbox)) - .await - .map_err(Status::from)?; - Ok(Response::new(CreateSandboxResponse::default())) - }) - .await - } - - async fn suspend_sandbox( - &self, - _request: Request, - ) -> Result, Status> { - Err(Status::unimplemented( - "the Podman compute driver does not support sandbox suspend", - )) - } - - async fn stop_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::STOP_SANDBOX, async { - let request = request.into_inner(); - if request.sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox_id is required")); - } - self.driver - .stop_sandbox(&request.sandbox_id) - .await - .map_err(Status::from)?; - Ok(Response::new(StopSandboxResponse {})) - }) - .await - } - - async fn start_sandbox( - &self, - request: Request, - ) -> Result, Status> { - Box::pin( - self.rpc_tracer - .trace(openshell_otel::rpc::START_SANDBOX, async { - let request = request.into_inner(); - if request.sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox_id is required")); - } - self.driver - .start_sandbox( - &request.sandbox_id, - &request.generation_id, - &request.launch_authentication, - request.sandbox.as_ref(), - ) - .await - .map_err(Status::from)?; - Ok(Response::new(StartSandboxResponse::default())) - }), - ) - .await - } - - async fn delete_sandbox( - &self, - request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::DELETE_SANDBOX, async { - let request = request.into_inner(); - if request.sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox_id is required")); - } - let deleted = self - .driver - .delete_sandbox(&request.sandbox_id) - .await - .map_err(Status::from)?; - Ok(Response::new(DeleteSandboxResponse { deleted })) - }) - .await - } - - type WatchSandboxesStream = ComputeDriverWatchStream; - - async fn watch_sandboxes( - &self, - _request: Request, - ) -> Result, Status> { - let create_stream = async { - let stream = self.driver.watch_sandboxes().await.map_err(Status::from)?; - let stream = stream.map(|item| item.map_err(|err| Status::internal(err.to_string()))); - Ok::(Box::pin(stream)) - }; - self.rpc_tracer - .trace_stream(openshell_otel::rpc::WATCH_SANDBOXES, create_stream) - .await - .map(Response::new) - } - - async fn ensure_workspace( - &self, - _request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::ENSURE_WORKSPACE, async { - Ok(Response::new(EnsureWorkspaceResponse {})) - }) - .await - } - - async fn delete_workspace( - &self, - _request: Request, - ) -> Result, Status> { - self.rpc_tracer - .trace(openshell_otel::rpc::DELETE_WORKSPACE, async { - Ok(Response::new(DeleteWorkspaceResponse {})) - }) - .await - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::config::PodmanComputeConfig; - use crate::container; - use crate::test_utils::{StubResponse, spawn_podman_stub, unique_socket_path}; - use hyper::StatusCode; - use openshell_core::ComputeDriverError; - use std::path::PathBuf; - - type TestDriverClient = - openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient< - tonic::transport::Channel, - >; - - fn request_with_traceparent(message: T) -> Request { - let mut request = Request::new(message); - request.metadata_mut().insert( - "traceparent", - "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" - .parse() - .unwrap(), - ); - request - } - - async fn standalone_traced_client() -> ( - TestDriverClient, - tokio::sync::oneshot::Sender<()>, - tokio::task::JoinHandle>, - ) { - use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let (shutdown, shutdown_rx) = tokio::sync::oneshot::channel(); - let service = ComputeDriverService::new(PodmanComputeDriver::for_tests( - PodmanComputeConfig::default(), - )); - let server = tokio::spawn(async move { - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(ComputeDriverServer::new(service)) - .serve_with_incoming_shutdown( - tokio_stream::wrappers::TcpListenerStream::new(listener), - async { - let _ = shutdown_rx.await; - }, - ) - .await - }); - let client = TestDriverClient::connect(format!("http://{address}")) - .await - .unwrap(); - (client, shutdown, server) - } - - #[test] - fn precondition_driver_errors_map_to_failed_precondition_status() { - let status: Status = - ComputeDriverError::Precondition("sandbox container is not running".to_string()).into(); - - assert_eq!(status.code(), tonic::Code::FailedPrecondition); - assert_eq!(status.message(), "sandbox container is not running"); - } - - #[test] - fn already_exists_driver_errors_map_to_already_exists_status() { - let status: Status = ComputeDriverError::AlreadyExists.into(); - assert_eq!(status.code(), tonic::Code::AlreadyExists); - } - - #[test] - fn not_found_driver_errors_map_to_not_found_status() { - let status: Status = ComputeDriverError::NotFound.into(); - assert_eq!(status.code(), tonic::Code::NotFound); - } - - #[tokio::test] - async fn in_process_service_preserves_the_driver_rpc_server_boundary() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::{Instrument as _, instrument::WithSubscriber as _}; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let gateway_exporter = InMemorySpanExporterBuilder::new().build(); - let gateway_provider = SdkTracerProvider::builder() - .with_simple_exporter(gateway_exporter.clone()) - .build(); - let driver_exporter = InMemorySpanExporterBuilder::new().build(); - let driver_provider = SdkTracerProvider::builder() - .with_simple_exporter(driver_exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry() - .with(openshell_otel::layer_excluding_target_prefixes( - &gateway_provider, - "gateway-test", - crate::otel_tracing::TRACING.in_process_targets(), - )) - .with(crate::otel_tracing::TRACING.in_process_layer(&driver_provider)); - let service = ComputeDriverService::new_in_process(PodmanComputeDriver::for_tests( - PodmanComputeConfig::default(), - )); - - async { - let gateway_span = tracing::info_span!(target: "openshell_server::compute", "driver", otel.name = "openshell.compute.v1.ComputeDriver/GetCapabilities", otel.kind = "client"); - ComputeDriver::get_capabilities( - &service, - Request::new(GetCapabilitiesRequest { - gateway: Some(openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - )), - }), - ) - .instrument(gateway_span) - .await - } - .with_subscriber(subscriber) - .await - .expect("capabilities should succeed"); - gateway_provider.force_flush().unwrap(); - driver_provider.force_flush().unwrap(); - - let gateway_spans = gateway_exporter.get_finished_spans().unwrap(); - let driver_spans = driver_exporter.get_finished_spans().unwrap(); - let client = gateway_spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/GetCapabilities") - .unwrap(); - let server = driver_spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/GetCapabilities") - .expect("in-process server span"); - assert_eq!( - server.span_context.trace_id(), - client.span_context.trace_id() - ); - assert_eq!(server.parent_span_id, client.span_context.span_id()); - assert_eq!(server.span_kind, opentelemetry::trace::SpanKind::Server); - assert!(server.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.method" - && attribute.value.to_string() - == "openshell.compute.v1.ComputeDriver/GetCapabilities" - })); - assert!( - server - .attributes - .iter() - .all(|attribute| attribute.key.as_str() != "rpc.service"), - "the current RPC semantic conventions integrate the service into rpc.method" - ); - assert!(server.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.response.status_code" - && attribute.value.to_string() == "OK" - })); - gateway_provider.shutdown().unwrap(); - driver_provider.shutdown().unwrap(); - } - - #[tokio::test] - async fn standalone_rpc_layer_propagates_context_and_records_errors() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let dispatch = tracing::Dispatch::new( - tracing_subscriber::registry().with(crate::otel_tracing::TRACING.layer(&provider)), - ); - let _dispatch = tracing::dispatcher::set_default(&dispatch); - let (mut client, shutdown, server) = standalone_traced_client().await; - - client - .get_capabilities(request_with_traceparent(GetCapabilitiesRequest { - gateway: Some(openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - )), - })) - .await - .expect("capabilities should succeed"); - client - .validate_sandbox_create(request_with_traceparent(ValidateSandboxCreateRequest { - sandbox: None, - })) - .await - .expect_err("missing sandbox should fail"); - drop(client); - shutdown.send(()).unwrap(); - tokio::time::timeout(std::time::Duration::from_secs(5), server) - .await - .expect("standalone test server should stop") - .expect("standalone test server should not panic") - .expect("standalone test server should stop cleanly"); - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let capabilities = spans - .iter() - .filter(|span| span.name == "openshell.compute.v1.ComputeDriver/GetCapabilities") - .collect::>(); - assert_eq!(capabilities.len(), 1, "exactly one RPC span is expected"); - assert_eq!( - capabilities[0].span_context.trace_id().to_string(), - "4bf92f3577b34da6a3ce929d0e0e4736" - ); - assert_eq!( - capabilities[0].parent_span_id.to_string(), - "00f067aa0ba902b7" - ); - assert_eq!( - capabilities[0].span_kind, - opentelemetry::trace::SpanKind::Server - ); - assert!(capabilities[0].attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.response.status_code" - && attribute.value.to_string() == "OK" - })); - - let failed = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/ValidateSandboxCreate") - .expect("failed RPC span should be exported"); - assert!(matches!( - failed.status, - opentelemetry::trace::Status::Error { .. } - )); - assert!(failed.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.response.status_code" - && attribute.value.to_string() == "INVALID_ARGUMENT" - })); - provider.shutdown().unwrap(); - } - - #[tokio::test] - async fn in_process_stream_span_lives_until_stream_failure() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry() - .with(crate::otel_tracing::TRACING.in_process_layer(&provider)); - - async { - let span = tracing::info_span!( - target: crate::otel_tracing::TRACING.in_process_target(), - "driver_rpc", - otel.name = "openshell.compute.v1.ComputeDriver/WatchSandboxes", - otel.kind = "server", - otel.status_code = tracing::field::Empty, - rpc.response.status_code = tracing::field::Empty, - ); - let inner: ComputeDriverWatchStream = Box::pin(futures::stream::iter([Err( - Status::internal("watch failed"), - )])); - let mut stream = TracedWatchStream::new(inner, span); - - provider.force_flush().unwrap(); - assert!( - exporter.get_finished_spans().unwrap().is_empty(), - "server span must remain open while the response stream is alive" - ); - stream - .next() - .await - .expect("stream item") - .expect_err("stream should fail"); - drop(stream); - } - .with_subscriber(subscriber) - .await; - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/WatchSandboxes") - .expect("watch server span should be exported when the stream ends"); - assert!(matches!( - span.status, - opentelemetry::trace::Status::Error { .. } - )); - provider.shutdown().unwrap(); - } - - #[tokio::test] - async fn in_process_stream_records_ok_when_stream_completes() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry() - .with(crate::otel_tracing::TRACING.in_process_layer(&provider)); - - async { - let span = tracing::info_span!( - target: crate::otel_tracing::TRACING.in_process_target(), - "driver_rpc", - otel.name = "openshell.compute.v1.ComputeDriver/WatchSandboxes", - otel.kind = "server", - otel.status_code = tracing::field::Empty, - rpc.response.status_code = tracing::field::Empty, - ); - let inner: ComputeDriverWatchStream = Box::pin(futures::stream::empty()); - let mut stream = TracedWatchStream::new(inner, span); - - assert!(stream.next().await.is_none()); - drop(stream); - } - .with_subscriber(subscriber) - .await; - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/WatchSandboxes") - .expect("watch server span should be exported when the stream completes"); - assert!(span.attributes.iter().any(|attribute| { - attribute.key.as_str() == "rpc.response.status_code" - && attribute.value.to_string() == "OK" - })); - provider.shutdown().unwrap(); - } - - #[tokio::test] - async fn in_process_stream_leaves_status_unset_when_dropped() { - use opentelemetry_sdk::trace::{InMemorySpanExporterBuilder, SdkTracerProvider}; - use tracing::instrument::WithSubscriber as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let _tracing_lock = openshell_otel_test_support::tracing_test_lock().await; - let exporter = InMemorySpanExporterBuilder::new().build(); - let provider = SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry() - .with(crate::otel_tracing::TRACING.in_process_layer(&provider)); - - async { - let span = tracing::info_span!( - target: crate::otel_tracing::TRACING.in_process_target(), - "driver_rpc", - otel.name = "openshell.compute.v1.ComputeDriver/WatchSandboxes", - otel.kind = "server", - otel.status_code = tracing::field::Empty, - rpc.response.status_code = tracing::field::Empty, - error.type = tracing::field::Empty, - ); - let inner: ComputeDriverWatchStream = Box::pin(futures::stream::pending()); - let stream = TracedWatchStream::new(inner, span); - - drop(stream); - } - .with_subscriber(subscriber) - .await; - provider.force_flush().unwrap(); - - let spans = exporter.get_finished_spans().unwrap(); - let span = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/WatchSandboxes") - .expect("watch server span should be exported when the stream is dropped"); - assert!(matches!(span.status, opentelemetry::trace::Status::Unset)); - assert!( - span.attributes - .iter() - .all(|attribute| attribute.key.as_str() != "rpc.response.status_code") - ); - provider.shutdown().unwrap(); - } - - fn test_service(socket_path: PathBuf) -> ComputeDriverService { - let config = PodmanComputeConfig { - socket_path: Some(socket_path), - stop_timeout_secs: 10, - ..PodmanComputeConfig::default() - }; - ComputeDriverService::new(PodmanComputeDriver::for_tests(config)) - } - - fn api_path(path: &str) -> String { - format!("/v5.0.0{path}") - } - - #[tokio::test] - async fn delete_sandbox_rejects_missing_sandbox_id() { - let service = test_service(unique_socket_path("missing-id")); - - let err = ComputeDriver::delete_sandbox( - &service, - Request::new(DeleteSandboxRequest { - sandbox_id: String::new(), - name: "demo".to_string(), - }), - ) - .await - .expect_err("missing sandbox_id should fail"); - - assert_eq!(err.code(), tonic::Code::InvalidArgument); - assert_eq!(err.message(), "sandbox_id is required"); - } - - #[tokio::test] - async fn delete_sandbox_forwards_request_sandbox_id_to_driver_cleanup() { - let sandbox_id = "sandbox-abc"; - let volume_name = container::volume_name(sandbox_id); - let (socket_path, request_log, handle) = spawn_podman_stub( - "forward-id", - vec![ - StubResponse::new(StatusCode::NOT_FOUND, ""), // companion - StubResponse::new(StatusCode::NOT_FOUND, ""), // channel - // list_containers returns empty (container already gone) - StubResponse::new(StatusCode::OK, "[]"), - StubResponse::new(StatusCode::NOT_FOUND, ""), // control volume - StubResponse::new( - StatusCode::OK, - serde_json::json!({ - "Name": volume_name, "Labels": {container::LABEL_SANDBOX_ID: sandbox_id} - }) - .to_string(), - ), - // remove_volume - StubResponse::new(StatusCode::NO_CONTENT, ""), - ], - ); - let service = test_service(socket_path.clone()); - - let response = ComputeDriver::delete_sandbox( - &service, - Request::new(DeleteSandboxRequest { - sandbox_id: sandbox_id.to_string(), - name: "demo".to_string(), - }), - ) - .await - .expect("delete should succeed") - .into_inner(); - - assert!( - !response.deleted, - "already-removed containers should still report deleted=false" - ); - handle.await.expect("stub task should finish"); - let requests = request_log - .lock() - .expect("request log lock should not be poisoned") - .clone(); - assert!(requests.contains(&format!( - "DELETE {}", - api_path(&format!("/libpod/volumes/{volume_name}")) - ))); - let _ = std::fs::remove_file(socket_path); - } -} diff --git a/crates/openshell-driver-podman/src/isolation.rs b/crates/openshell-driver-podman/src/isolation.rs deleted file mode 100644 index f9fc790588..0000000000 --- a/crates/openshell-driver-podman/src/isolation.rs +++ /dev/null @@ -1,649 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Podman-owned provisioning for the common authenticated isolation channel. - -use std::collections::{BTreeMap, HashMap}; -#[cfg(test)] -use std::io::Read; -use std::path::PathBuf; - -use openshell_core::ComputeDriverError; -use openshell_core::proto::compute::v1::DriverSandbox; -use openshell_isolation_interface::contract::{ProvisioningEvidence, ResolvedWorkloadIdentity}; -use openshell_sandbox_backend::ALLOW_EXTRA_SUPPLEMENTARY_GROUPS_RESOURCE_CLAIM; -use openshell_sandbox_backend::boundary_protocol::{ - BoundaryConfig, BoundaryListener, GatewayVerificationKey, SandboxRuntimeDescriptor, - SandboxTlsClientConfig, SandboxTlsServerConfig, SandboxTransport, - generate_sandbox_tls_material, -}; -use serde::{Deserialize, Serialize}; - -pub const LABEL_ROLE: &str = "openshell.ai/isolation-role"; -pub const WORKLOAD_FILTER: &str = "openshell.ai/isolation-role=sandbox"; -pub const CHANNEL_ROOT: &str = "/.openshell/channel"; -pub const BOOTSTRAP_PATH: &str = "/.openshell/channel/sandbox/bootstrap.json"; -pub const RUNTIME_DESCRIPTOR_PATH: &str = "/.openshell/supervisor/runtime-descriptor.json"; -pub const AUTH_BUNDLE_PATH: &str = "/.openshell/supervisor/auth.json"; -pub const RESTART_METADATA_PATH: &str = "/.openshell/supervisor/restart-metadata.json"; -pub const CONTROL_ROOT: &str = "/.openshell/channel/control"; -const RUNTIME_INITIATED_SOCKET: &str = "/.openshell/channel/control/control.sock"; -const SOCKET_PATH: &str = "/.openshell/channel/sandbox/control.sock"; - -#[derive(Serialize)] -struct PodmanOuterFenceEvidence<'a> { - container_id: &'a str, - network_mode: &'static str, - unexpected_networks: &'a [String], -} - -impl PodmanOuterFenceEvidence<'_> { - fn project(&self, generation: &str) -> Result { - if self.container_id.is_empty() - || self.network_mode != "none" - || !self.unexpected_networks.is_empty() - { - return Err(invalid("Podman provisioning evidence is incomplete")); - } - let encoded = serde_json::to_vec(self).map_err(invalid)?; - let projection = ProvisioningEvidence::from_enforcement_evidence(generation, &encoded) - .map_err(invalid)?; - projection.validate(generation).map_err(invalid)?; - Ok(projection) - } -} - -pub fn supervisor_name(id: &str) -> String { - format!("openshell-supervisor-{id}") -} -pub fn control_volume_name(id: &str) -> String { - format!("openshell-control-{id}") -} -pub fn channel_volume_name(id: &str) -> String { - format!("openshell-channel-{id}") -} - -/// `keep-id` may retain the gateway user's supplementary groups in the -/// container. Other user-namespace modes, including `auto`, do not. -pub fn userns_preserves_host_groups(userns: Option<&str>) -> bool { - userns.is_some_and(|mode| mode.split(':').next() == Some("keep-id")) -} - -fn invalid(error: impl std::fmt::Display) -> ComputeDriverError { - ComputeDriverError::Precondition(error.to_string()) -} - -/// Resolve policy names against the pinned workload image, never the gateway. -pub fn resolve_identity( - sandbox: &DriverSandbox, - image_id: &str, - image_user: &str, - passwd: &[u8], - group: &[u8], -) -> Result { - let passwd = std::str::from_utf8(passwd).map_err(invalid)?; - let group = std::str::from_utf8(group).map_err(invalid)?; - let accounts: Vec<_> = passwd - .lines() - .filter_map(|line| { - let mut fields = line.split(':'); - let name = fields.next()?; - fields.next()?; - Some(( - name, - fields.next()?.parse::().ok()?, - fields.next()?.parse::().ok()?, - )) - }) - .collect(); - let groups: Vec<_> = group - .lines() - .filter_map(|line| { - let mut fields = line.split(':'); - let name = fields.next()?; - fields.next()?; - Some((name, fields.next()?.parse::().ok()?, fields.next()?)) - }) - .collect(); - let request = sandbox - .spec - .as_ref() - .and_then(|spec| spec.workload_identity.as_ref()); - let requested_user = request.map_or("", |identity| identity.user.trim()); - let requested_group = request.map_or("", |identity| identity.group.trim()); - let (image_user, image_group) = image_user.split_once(':').unwrap_or((image_user, "")); - let user = if requested_user.is_empty() { - image_user - } else { - requested_user - }; - let group = if requested_group.is_empty() { - image_group - } else { - requested_group - }; - if user.is_empty() && group.is_empty() { - // The image declares no OCI USER (for example, a minimal base image) and the - // policy requested no identity. Synthesize a numeric non-root identity - // instead of rejecting the image, matching Docker, Kubernetes, and VM. - return ResolvedWorkloadIdentity::new( - openshell_core::sandbox_env::DEFAULT_SANDBOX_UID, - openshell_core::sandbox_env::DEFAULT_SANDBOX_GID, - Vec::new(), - "default".into(), - image_id.into(), - ) - .map_err(invalid); - } - let account = accounts - .iter() - .find(|(name, uid, _)| *name == user || user.parse::().ok() == Some(*uid)); - let uid = user - .parse() - .ok() - .or_else(|| account.map(|(_, uid, _)| *uid)) - .ok_or_else(|| invalid("configure a non-root workload user present in the pinned image"))?; - let gid = if group.is_empty() { - account.map(|(_, _, gid)| *gid) - } else { - group.parse().ok().or_else(|| { - groups - .iter() - .find(|(name, _, _)| *name == group) - .map(|(_, gid, _)| *gid) - }) - } - .ok_or_else(|| { - invalid("configure an explicit workload group for a UID without an image passwd entry") - })?; - let supplemental = account.map_or_else(Vec::new, |(username, _, _)| { - groups - .iter() - .filter(|(_, id, members)| { - *id != gid && members.split(',').any(|member| member == *username) - }) - .map(|(_, gid, _)| *gid) - .collect() - }); - let source = if requested_user.is_empty() && requested_group.is_empty() { - "image" - } else { - "policy" - }; - ResolvedWorkloadIdentity::new(uid, gid, supplemental, source.into(), image_id.into()) - .map_err(invalid) -} - -pub struct BootstrapArchives { - pub channel: Vec, - pub control: Option>, - pub workspace: Vec, - pub supervisor: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct RestartMetadata { - pub(crate) generation: String, - #[serde(default)] - pub(crate) runtime_initiated: bool, - pub(crate) workload_identity: ResolvedWorkloadIdentity, - pub(crate) child_env: HashMap, -} - -pub struct BootstrapArchivesInput<'a> { - pub runtime_initiated: bool, - pub sandbox_id: &'a str, - pub container_id: &'a str, - pub generation: &'a str, - pub host_gateway_ip: std::net::IpAddr, - pub identity: &'a ResolvedWorkloadIdentity, - pub allow_extra_supplementary_groups: bool, - pub child_env: HashMap, - pub launch_authentication: &'a openshell_core::jwt::SandboxLaunchAuthentication, -} - -/// The shared volume contains only sandbox credentials. Supervisor credentials, -/// gateway authorization, and the restart copy never enter that volume. -pub fn bootstrap_archives( - input: BootstrapArchivesInput<'_>, -) -> Result { - let BootstrapArchivesInput { - runtime_initiated, - sandbox_id, - container_id, - generation, - host_gateway_ip, - identity, - allow_extra_supplementary_groups, - child_env, - launch_authentication, - } = input; - launch_authentication.validate().map_err(invalid)?; - let session_id = launch_authentication.supervisor.session_id; - let tls = generate_sandbox_tls_material(session_id).map_err(invalid)?; - let mut resource_claims = BTreeMap::from([ - ("podman.container_id".into(), container_id.into()), - ( - "podman.image_identity".into(), - identity.resource_digest.clone(), - ), - ]); - if allow_extra_supplementary_groups { - resource_claims.insert( - ALLOW_EXTRA_SUPPLEMENTARY_GROUPS_RESOURCE_CLAIM.into(), - "true".into(), - ); - } - let runtime_generation = launch_authentication - .supervisor - .runtime_generation - .to_string(); - let unexpected_networks = Vec::new(); - let provisioning_evidence = PodmanOuterFenceEvidence { - container_id, - network_mode: "none", - unexpected_networks: &unexpected_networks, - } - .project(&runtime_generation)?; - let verification_keys = launch_authentication - .verification_keys - .iter() - .map(|key| { - String::from_utf8(key.public_key_pem.clone()) - .map(|public_key_pem| GatewayVerificationKey { - key_id: key.key_id.clone(), - public_key_pem, - }) - .map_err(invalid) - }) - .collect::, _>>()?; - let config = BoundaryConfig { - boundary_id: sandbox_id.into(), - generation: runtime_generation.clone(), - session_id, - session_rotation: launch_authentication.supervisor.session_rotation, - auth_epoch: launch_authentication.supervisor.auth_epoch, - gateway_id: launch_authentication.gateway_id.clone(), - verification_keys, - listener: { - let tls = SandboxTlsServerConfig { - certificate_chain_path: PathBuf::from("/.openshell/channel/sandbox/server.crt"), - private_key_path: PathBuf::from("/.openshell/channel/sandbox/server.key"), - }; - if runtime_initiated { - BoundaryListener::RuntimeInitiatedUnix { - socket_path: RUNTIME_INITIATED_SOCKET.into(), - tls, - } - } else { - BoundaryListener::Unix { - socket_path: SOCKET_PATH.into(), - tls, - } - } - }, - resource_claims: resource_claims.clone(), - resource_claim_files: BTreeMap::new(), - workload_identity: identity.clone(), - provisioning_evidence: provisioning_evidence.clone(), - child_env: child_env.clone(), - }; - let runtime_descriptor = SandboxRuntimeDescriptor { - boundary_id: sandbox_id.into(), - generation: runtime_generation, - session_id, - transport: if runtime_initiated { - SandboxTransport::RuntimeInitiatedUnix { - socket_path: RUNTIME_INITIATED_SOCKET.into(), - } - } else { - SandboxTransport::Unix { - socket_path: SOCKET_PATH.into(), - } - }, - tls: SandboxTlsClientConfig { - server_name: tls.server_name, - trust_anchor_pem: tls.trust_anchor_pem, - }, - host_gateway_ip: Some(host_gateway_ip), - resource_claims, - workload_identity: identity.clone(), - provisioning_evidence, - }; - // Libpod resolves the requested upload destination once for a stopped - // container. Archive entries must be relative to the selected named volume, - // not rootfs paths that the volume would shadow on container start. - let mut channel = Archive::new(identity); - channel.directory(".", 0o755, false)?; - channel.directory("sandbox", 0o711, true)?; - channel.file( - "sandbox/bootstrap.json", - &serde_json::to_vec(&config).map_err(invalid)?, - )?; - channel.file("sandbox/server.crt", tls.certificate_chain_pem.as_bytes())?; - channel.file("sandbox/server.key", tls.private_key_pem.as_bytes())?; - let channel = channel.finish()?; - let mut workspace = Archive::new(identity); - workspace.directory(".", 0o700, true)?; - let mut supervisor = Archive::new(identity); - supervisor.directory(".openshell", 0o755, false)?; - supervisor.directory(".openshell/supervisor", 0o700, true)?; - supervisor.file( - RUNTIME_DESCRIPTOR_PATH, - &serde_json::to_vec(&runtime_descriptor).map_err(invalid)?, - )?; - supervisor.file( - AUTH_BUNDLE_PATH, - &serde_json::to_vec(&launch_authentication.supervisor).map_err(invalid)?, - )?; - let restart_metadata = RestartMetadata { - runtime_initiated, - generation: generation.to_string(), - workload_identity: identity.clone(), - child_env, - }; - supervisor.file( - RESTART_METADATA_PATH, - &serde_json::to_vec(&restart_metadata).map_err(invalid)?, - )?; - let control = if runtime_initiated { - let mut archive = Archive::new(identity); - // The containers can use different rootless user-namespace mappings. - // Only this socket volume is writable; keys stay in the read-only - // bootstrap volume. The sticky bit protects existing socket inodes. - archive.directory(".", 0o1777, false)?; - Some(archive.finish()?) - } else { - None - }; - Ok(BootstrapArchives { - control, - channel, - workspace: workspace.finish()?, - supervisor: supervisor.finish()?, - }) -} - -pub fn restart_metadata_from_slice(bytes: &[u8]) -> Result { - serde_json::from_slice(bytes).map_err(invalid) -} - -struct Archive<'a> { - builder: tar::Builder>, - identity: &'a ResolvedWorkloadIdentity, -} -impl<'a> Archive<'a> { - fn new(identity: &'a ResolvedWorkloadIdentity) -> Self { - Self { - builder: tar::Builder::new(Vec::new()), - identity, - } - } - fn directory(&mut self, path: &str, mode: u32, owned: bool) -> Result<(), ComputeDriverError> { - self.append(path, mode, owned, tar::EntryType::Directory, &[]) - } - fn file(&mut self, path: &str, content: &[u8]) -> Result<(), ComputeDriverError> { - self.append( - path.trim_start_matches('/'), - 0o600, - true, - tar::EntryType::Regular, - content, - ) - } - fn append( - &mut self, - path: &str, - mode: u32, - owned: bool, - kind: tar::EntryType, - content: &[u8], - ) -> Result<(), ComputeDriverError> { - let mut header = tar::Header::new_gnu(); - header.set_entry_type(kind); - header.set_mode(mode); - header.set_uid(if owned { - u64::from(self.identity.uid) - } else { - 0 - }); - header.set_gid(if owned { - u64::from(self.identity.gid) - } else { - 0 - }); - header.set_size(content.len() as u64); - header.set_mtime(0); - header.set_cksum(); - self.builder - .append_data(&mut header, path, content) - .map_err(invalid) - } - fn finish(self) -> Result, ComputeDriverError> { - self.builder.into_inner().map_err(invalid) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use openshell_core::jwt::{ - CredentialEpoch, SandboxLaunchAuthentication, SecretJwt, SessionVerificationKey, - SupervisorAuthBundle, - }; - - #[test] - fn outer_fence_projection_rejects_each_missing_native_fact() { - let unexpected_networks = vec!["podman".to_string()]; - for evidence in [ - PodmanOuterFenceEvidence { - container_id: "", - network_mode: "none", - unexpected_networks: &[], - }, - PodmanOuterFenceEvidence { - container_id: "container", - network_mode: "bridge", - unexpected_networks: &[], - }, - PodmanOuterFenceEvidence { - container_id: "container", - network_mode: "none", - unexpected_networks: &unexpected_networks, - }, - ] { - assert!(evidence.project("generation-1").is_err()); - } - } - - fn authentication() -> SandboxLaunchAuthentication { - SandboxLaunchAuthentication { - supervisor: SupervisorAuthBundle { - session_id: openshell_core::SandboxSessionId::new(), - runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( - "generation-1", - ) - .unwrap(), - session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), - auth_epoch: CredentialEpoch::new(1).unwrap(), - gateway_token: SecretJwt::parse("gateway.token.value").unwrap(), - gateway_expires_at: i64::MAX, - sandbox_token: SecretJwt::parse("sandbox.token.value").unwrap(), - sandbox_expires_at: i64::MAX, - ssh_host_private_key: None, - traces_otlp_headers: None, - ocsf_otlp_headers: None, - agent_otlp_headers: None, - otlp_tls: Vec::new(), - traces_otlp_tls: None, - ocsf_otlp_tls: None, - agent_otlp_tls: None, - }, - gateway_id: "gateway-test".to_string(), - verification_keys: vec![SessionVerificationKey { - key_id: "test-key".to_string(), - public_key_pem: b"public-key".to_vec(), - }], - } - } - - #[test] - fn identity_uses_pinned_image_accounts_and_rejects_root() { - let sandbox = DriverSandbox::default(); - let passwd = b"root:x:0:0:root:/root:/bin/sh\nagent:x:1000:1001::/home/agent:/bin/sh\n"; - let groups = b"agent:x:1001:\ndata:x:2000:agent\n"; - let identity = - resolve_identity(&sandbox, "sha256:pinned", "agent", passwd, groups).unwrap(); - assert_eq!((identity.uid, identity.gid), (1000, 1001)); - assert_eq!(identity.supplementary_gids, vec![2000]); - assert_eq!(identity.resource_digest, "sha256:pinned"); - assert!(resolve_identity(&sandbox, "sha256:pinned", "root", passwd, groups).is_err()); - assert!(resolve_identity(&sandbox, "sha256:pinned", "2000", passwd, groups).is_err()); - } - - #[test] - fn identity_uses_numeric_default_for_userless_image() { - let identity = resolve_identity( - &DriverSandbox::default(), - "sha256:pinned", - "", - b"root:x:0:0:root:/root:/bin/sh\n", - b"root:x:0:\n", - ) - .unwrap(); - - assert_eq!( - (identity.uid, identity.gid), - ( - openshell_core::sandbox_env::DEFAULT_SANDBOX_UID, - openshell_core::sandbox_env::DEFAULT_SANDBOX_GID, - ) - ); - assert_eq!(identity.source, "default"); - } - - fn files(bytes: &[u8]) -> BTreeMap> { - tar::Archive::new(bytes) - .entries() - .unwrap() - .filter_map(|entry| { - let mut entry = entry.unwrap(); - if !entry.header().entry_type().is_file() { - return None; - } - let path = entry.path().unwrap().into_owned(); - assert_eq!(entry.header().mode().unwrap(), 0o600); - assert_eq!(entry.header().uid().unwrap(), 1000); - let mut content = Vec::new(); - entry.read_to_end(&mut content).unwrap(); - Some((path, content)) - }) - .collect() - } - - #[test] - fn archives_separate_supervisor_credentials_and_bind_one_channel() { - let identity = ResolvedWorkloadIdentity::new( - 1000, - 1001, - vec![], - "image".into(), - "sha256:image".into(), - ) - .unwrap(); - let authentication = authentication(); - let child_env = HashMap::from([("PATH".to_string(), "/agent/bin".to_string())]); - let archives = bootstrap_archives(BootstrapArchivesInput { - runtime_initiated: false, - sandbox_id: "sandbox", - container_id: "container", - generation: "generation-1", - host_gateway_ip: "127.0.0.1".parse().unwrap(), - identity: &identity, - allow_extra_supplementary_groups: false, - child_env: child_env.clone(), - launch_authentication: &authentication, - }) - .unwrap(); - let workload = files(&archives.channel); - let supervisor = files(&archives.supervisor); - let mut workspace = tar::Archive::new(archives.workspace.as_slice()); - let mut entries = workspace.entries().unwrap(); - let root = entries.next().unwrap().unwrap(); - assert_eq!(root.path().unwrap().as_ref(), std::path::Path::new(".")); - assert!(root.header().entry_type().is_dir()); - assert_eq!(root.header().uid().unwrap(), u64::from(identity.uid)); - assert_eq!(root.header().gid().unwrap(), u64::from(identity.gid)); - assert_eq!(root.header().mode().unwrap(), 0o700); - assert!(entries.next().is_none()); - assert_eq!(workload.len(), 3); - assert_eq!(supervisor.len(), 3); - assert!(workload.keys().all(|path| path.starts_with("sandbox"))); - assert!( - supervisor - .keys() - .all(|path| path.starts_with(".openshell/supervisor")) - ); - let config: BoundaryConfig = serde_json::from_slice( - workload - .get(&PathBuf::from("sandbox/bootstrap.json")) - .unwrap(), - ) - .unwrap(); - let runtime_descriptor: SandboxRuntimeDescriptor = serde_json::from_slice( - supervisor - .get(&PathBuf::from( - RUNTIME_DESCRIPTOR_PATH.trim_start_matches('/'), - )) - .unwrap(), - ) - .unwrap(); - assert_eq!(config.boundary_id, runtime_descriptor.boundary_id); - assert_eq!(config.session_id, runtime_descriptor.session_id); - assert_eq!( - config.provisioning_evidence, - runtime_descriptor.provisioning_evidence - ); - assert_eq!(config.workload_identity, identity); - assert_eq!( - runtime_descriptor.host_gateway_ip, - Some("127.0.0.1".parse().unwrap()) - ); - runtime_descriptor - .provisioning_evidence - .validate(&runtime_descriptor.generation) - .unwrap(); - assert!( - !config - .resource_claims - .contains_key(ALLOW_EXTRA_SUPPLEMENTARY_GROUPS_RESOURCE_CLAIM) - ); - let restart_metadata: RestartMetadata = serde_json::from_slice( - supervisor - .get(&PathBuf::from( - RESTART_METADATA_PATH.trim_start_matches('/'), - )) - .unwrap(), - ) - .unwrap(); - assert_eq!(restart_metadata.workload_identity, identity); - assert_eq!(restart_metadata.child_env, child_env); - let restart_bytes = serde_json::to_vec(&restart_metadata).unwrap(); - assert!( - !restart_bytes - .windows(b"PRIVATE KEY".len()) - .any(|window| window == b"PRIVATE KEY") - ); - } - - #[test] - fn keep_id_is_the_only_userns_mode_that_preserves_host_groups() { - assert!(userns_preserves_host_groups(Some("keep-id"))); - assert!(userns_preserves_host_groups(Some( - "keep-id:uid=1000,gid=1000" - ))); - assert!(!userns_preserves_host_groups(Some("auto"))); - assert!(!userns_preserves_host_groups(Some("private"))); - assert!(!userns_preserves_host_groups(None)); - } -} diff --git a/crates/openshell-driver-podman/src/lib.rs b/crates/openshell-driver-podman/src/lib.rs deleted file mode 100644 index 74bef509e3..0000000000 --- a/crates/openshell-driver-podman/src/lib.rs +++ /dev/null @@ -1,17 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -pub(crate) mod client; -pub mod config; -pub(crate) mod container; -pub mod driver; -pub mod grpc; -mod isolation; -pub mod otel_tracing; -#[cfg(test)] -pub(crate) mod test_utils; -pub(crate) mod watcher; - -pub use config::PodmanComputeConfig; -pub use driver::PodmanComputeDriver; -pub use grpc::ComputeDriverService; diff --git a/crates/openshell-driver-podman/src/main.rs b/crates/openshell-driver-podman/src/main.rs deleted file mode 100644 index 84079c856f..0000000000 --- a/crates/openshell-driver-podman/src/main.rs +++ /dev/null @@ -1,402 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use clap::Parser; -use miette::{IntoDiagnostic, Result}; -use std::future::Future; -use std::net::SocketAddr; -use std::num::{NonZeroI64, NonZeroU64}; -use std::path::PathBuf; -use tracing::info; - -mod serve; - -use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; -use openshell_core::sandbox_env::SupervisorOtlpArgs; -use openshell_core::{AppArmorProfile, ImagePullPolicy, VERSION}; -use openshell_driver_podman::config::{DEFAULT_NETWORK_NAME, DEFAULT_PODMAN_STOP_TIMEOUT_SECS}; -use openshell_driver_podman::{ComputeDriverService, PodmanComputeConfig, PodmanComputeDriver}; - -#[derive(Parser)] -#[command(name = "openshell-driver-podman")] -#[command(version = VERSION)] -struct Args { - /// Operator-owned JSON policy; omitted means driver config disabled and labels required. - #[arg( - long, - env = "OPENSHELL_DRIVER_ADMISSION_CONFIG_JSON", - default_value = "{}" - )] - admission_config_json: openshell_core::resource_admission::DriverAdmissionConfig, - /// Public compute-driver Unix socket used by an external gateway. - #[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_SOCKET")] - bind_socket: Option, - - #[arg( - long, - env = "OPENSHELL_COMPUTE_DRIVER_BIND", - default_value = "127.0.0.1:50061" - )] - bind_address: SocketAddr, - - #[arg(long, env = "OPENSHELL_LOG_LEVEL", default_value = "info")] - log_level: String, - - #[command(flatten)] - otlp: SupervisorOtlpArgs, - - #[arg(long, env = "OPENSHELL_GATEWAY_NAME")] - gateway_name: Option, - - /// Path to the Podman API Unix socket. - #[arg(long, env = "OPENSHELL_PODMAN_SOCKET")] - podman_socket: Option, - - #[arg(long, env = "OPENSHELL_SANDBOX_IMAGE")] - sandbox_image: Option, - - #[arg( - long, - env = "OPENSHELL_SANDBOX_IMAGE_PULL_POLICY", - default_value_t = ImagePullPolicy::IfNotPresent - )] - sandbox_image_pull_policy: ImagePullPolicy, - - #[arg(long, env = "OPENSHELL_GRPC_ENDPOINT")] - grpc_endpoint: Option, - - /// Port the gateway server is listening on. - /// - /// Used when `--grpc-endpoint` is not set to auto-detect the endpoint - /// that sandbox containers dial back to. - #[arg( - long, - env = "OPENSHELL_GATEWAY_PORT", - default_value_t = openshell_core::config::DEFAULT_SERVER_PORT - )] - gateway_port: u16, - - /// Trusted supervisor-side destination used for sandbox host aliases. - /// - /// Empty uses loopback on native Linux and the gvproxy host address on - /// macOS Podman Machine. - #[arg(long, env = "OPENSHELL_PODMAN_HOST_GATEWAY_IP")] - host_gateway_ip: Option, - - #[arg( - long, - env = "OPENSHELL_SANDBOX_SSH_SOCKET_PATH", - default_value = openshell_core::container_paths::SSH_SOCKET_PATH - )] - sandbox_ssh_socket_path: String, - - /// Podman network name retained for driver-managed resources. - #[arg(long, env = "OPENSHELL_NETWORK_NAME", default_value = DEFAULT_NETWORK_NAME)] - network_name: String, - - /// Container stop timeout in seconds (SIGTERM → SIGKILL). - #[arg(long, env = "OPENSHELL_STOP_TIMEOUT", default_value_t = DEFAULT_PODMAN_STOP_TIMEOUT_SECS)] - stop_timeout: u32, - - /// Container cgroup PID limit for sandbox containers. Omit to use - /// `OpenShell`'s 2048-process default. - #[arg(long, env = "OPENSHELL_SANDBOX_PIDS_LIMIT", default_value = "2048")] - sandbox_pids_limit: Option, - - /// Health check interval in seconds. Omit it in gateway TOML to disable - /// health checks; the standalone driver keeps its prior 10-second default. - #[arg( - long, - env = "OPENSHELL_HEALTH_CHECK_INTERVAL_SECS", - default_value = "10" - )] - health_check_interval_secs: Option, - - /// OCI image containing the `openshell-sandbox` runtime binary. - #[arg(long, env = openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV)] - sandbox_runtime_image: Option, - - /// OCI image containing the `openshell-supervisor` control binary. - #[arg(long, env = openshell_core::config::SUPERVISOR_IMAGE_ENV)] - supervisor_image: Option, - - /// Host path to the CA certificate for supervisor-to-gateway TLS. - #[arg(long, env = "OPENSHELL_PODMAN_TLS_CA")] - podman_tls_ca: Option, - - /// Deprecated; client certificates are rejected. - #[arg(long, env = "OPENSHELL_PODMAN_TLS_CERT")] - podman_tls_cert: Option, - - /// Deprecated; client private keys are rejected. - #[arg(long, env = "OPENSHELL_PODMAN_TLS_KEY")] - podman_tls_key: Option, - - /// Host UNIX socket projected into supervisors for provider SPIFFE token exchange. - #[arg(long, env = "OPENSHELL_PROVIDER_SPIFFE_WORKLOAD_API_SOCKET")] - provider_spiffe_workload_api_socket: Option, - - /// `AppArmor` model: `RuntimeDefault`, `Unconfined`, or `Localhost/`. - #[arg(long, env = "OPENSHELL_APP_ARMOR_PROFILE")] - app_armor_profile: Option, - - /// Corporate forward proxy URL for the supervisor's upstream TLS dials, - /// in explicit `http://host:port` form (scheme and port required). - /// Credentials must not be embedded in the URL; use - /// `--sandbox-proxy-auth-file` instead. - #[arg(long, env = "OPENSHELL_SANDBOX_HTTPS_PROXY")] - sandbox_https_proxy: Option, - - /// Comma-separated `NO_PROXY` list injected alongside the proxy URL. - #[arg(long, env = "OPENSHELL_SANDBOX_NO_PROXY")] - sandbox_no_proxy: Option, - - /// Path to a file containing the corporate proxy credentials as - /// `user:pass`. Delivered to the supervisor through a root-only secret - /// mount so the credentials never appear in config or container metadata. - #[arg(long, env = "OPENSHELL_SANDBOX_PROXY_AUTH_FILE")] - sandbox_proxy_auth_file: Option, - - /// Explicit acknowledgement (`true`) that the proxy credential is sent - /// as cleartext Basic auth over the plain-TCP connection to the http:// - /// proxy. Required when `--sandbox-proxy-auth-file` is set. - #[arg(long, env = "OPENSHELL_SANDBOX_PROXY_AUTH_ALLOW_INSECURE")] - sandbox_proxy_auth_allow_insecure: Option, - - /// Send the destination hostname in CONNECT requests to the corporate - /// proxy instead of a validated IP. Only for proxies whose ACLs filter - /// on hostnames: the proxy then resolves the name itself, so sandbox - /// SSRF/`allowed_ips` validation no longer binds the connection. - #[arg(long, env = "OPENSHELL_SANDBOX_PROXY_CONNECT_BY_HOSTNAME")] - sandbox_proxy_connect_by_hostname: Option, - - /// Path (on the gateway host) to a PEM CA bundle trusted for the corporate - /// proxy: the TLS handshake with an `https://` proxy and, for - /// TLS-intercepting proxies, re-signed upstream certificates. Bind-mounted - /// read-only into the sandbox. Only meaningful with `--sandbox-https-proxy`. - #[arg(long, env = "OPENSHELL_SANDBOX_PROXY_CA_BUNDLE")] - sandbox_proxy_ca_bundle: Option, - - /// Path (on the gateway host) to a PEM CA bundle trusted for direct - /// (non-proxied), policy-inspected HTTPS egress to destinations signed by - /// a private CA. Unlike `--sandbox-proxy-ca-bundle`, this applies - /// regardless of whether a corporate proxy is configured. Bind-mounted - /// read-only into the supervisor container. - #[arg(long, env = "OPENSHELL_SANDBOX_ADDITIONAL_CA_BUNDLE")] - sandbox_additional_ca_bundle: Option, - /// AAAA handling for the supervisor's mediated policy DNS: `auto`, - /// `enabled` or `disabled`. - #[arg(long, env = "OPENSHELL_SANDBOX_POLICY_DNS_IPV6_EGRESS")] - sandbox_policy_dns_ipv6_egress: Option, - - /// NAT64 prefixes (RFC 6052 CIDRs) of the sandbox network. - #[arg(long, env = "OPENSHELL_SANDBOX_NAT64_PREFIXES", value_delimiter = ',')] - sandbox_nat64_prefixes: Vec, - - /// User namespace mode for sandbox containers (e.g. `auto`). - /// When unset, containers use the default user namespace. - #[arg(long, env = "OPENSHELL_PODMAN_USERNS")] - userns: Option, - - /// Explicit UID mappings for `userns = "private"`. - /// Each entry is `"container_id:host_id:size"`. - #[arg(long = "uidmap")] - uidmap: Vec, - - /// Explicit GID mappings for `userns = "private"`. - /// Each entry is `"container_id:host_id:size"`. - #[arg(long = "gidmap")] - gidmap: Vec, - - /// Allow sandbox requests to attach host bind mounts. - #[arg(long, env = "OPENSHELL_ENABLE_BIND_MOUNTS", default_value_t = false)] - enable_bind_mounts: bool, -} - -#[tokio::main] -async fn main() -> Result<()> { - if let Some(code) = serve::dispatch().await { - std::process::exit(code); - } - let args = Args::parse(); - let _tracing = openshell_otel::install_driver_tracing( - openshell_driver_podman::otel_tracing::TRACING, - openshell_otel::DriverTracingConfig { - endpoint: args.otlp.endpoint.as_deref(), - protocol: args.otlp.protocol.into(), - ca_file: args.otlp.ca_file.as_deref(), - cert_file: args.otlp.cert_file.as_deref(), - key_file: args.otlp.key_file.as_deref(), - gateway_name: args.gateway_name.as_deref(), - service_version: VERSION, - log_level: &args.log_level, - ansi: openshell_core::color::stdout_ansi(), - }, - ); - args.otlp.warn_deprecated(); - - let supervisor_otlp = args.otlp.supervisor_otlp(); - // External drivers have no gateway-local staged artifact. Do not accept - // a path or silently emulate destination-CA delivery outside the gateway. - let driver = PodmanComputeDriver::new( - PodmanComputeConfig { - allow_driver_config: args.admission_config_json.allow_driver_config, - resource_admission: args.admission_config_json.resource_admission.clone(), - socket_path: args.podman_socket, - default_image: args.sandbox_image.unwrap_or_default(), - image_pull_policy: args.sandbox_image_pull_policy, - grpc_endpoint: args.grpc_endpoint.unwrap_or_default(), - supervisor_otlp, - supervisor_gateway_name: args.gateway_name.clone(), - gateway_port: args.gateway_port, - host_gateway_ip: args - .host_gateway_ip - .unwrap_or_else(PodmanComputeConfig::default_host_gateway_ip), - ssh_socket_path: args.sandbox_ssh_socket_path, - network_name: args.network_name, - stop_timeout_secs: args.stop_timeout, - sandbox_runtime_image: args - .sandbox_runtime_image - .unwrap_or_else(openshell_core::config::default_sandbox_runtime_image), - supervisor_image: args - .supervisor_image - .unwrap_or_else(openshell_core::config::default_supervisor_image), - guest_tls_ca: args.podman_tls_ca, - guest_tls_cert: args.podman_tls_cert, - guest_tls_key: args.podman_tls_key, - provider_spiffe_workload_api_socket: args.provider_spiffe_workload_api_socket, - app_armor_profile: args.app_armor_profile, - sandbox_pids_limit: args.sandbox_pids_limit, - health_check_interval_secs: args.health_check_interval_secs, - https_proxy: args.sandbox_https_proxy, - no_proxy: args.sandbox_no_proxy, - proxy_auth_file: args.sandbox_proxy_auth_file, - proxy_auth_allow_insecure: args.sandbox_proxy_auth_allow_insecure, - proxy_connect_by_hostname: args.sandbox_proxy_connect_by_hostname, - proxy_ca_bundle: args.sandbox_proxy_ca_bundle, - additional_ca_bundle: args.sandbox_additional_ca_bundle, - policy_dns_ipv6_egress: args.sandbox_policy_dns_ipv6_egress, - nat64_prefixes: args.sandbox_nat64_prefixes, - userns: args.userns, - uidmap: args.uidmap, - gidmap: args.gidmap, - enable_bind_mounts: args.enable_bind_mounts, - }, - None, - ) - .await - .into_diagnostic()?; - - let service = ComputeDriverServer::new(ComputeDriverService::new(driver)); - if let Some(socket_path) = args.bind_socket { - let listener = openshell_core::external_driver_socket::bind_private(&socket_path) - .map_err(|err| miette::miette!("{err}"))?; - let _cleanup = - openshell_core::external_driver_socket::SocketCleanup::new(socket_path.clone()); - info!(socket = %socket_path.display(), "Starting Podman compute driver"); - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(service) - .serve_with_incoming_shutdown( - openshell_core::external_driver_socket::SameUidUnixIncoming::new(listener), - shutdown_signal(), - ) - .await - .into_diagnostic() - } else { - info!(address = %args.bind_address, "Starting Podman compute driver"); - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(service) - .serve_with_shutdown(args.bind_address, shutdown_signal()) - .await - .into_diagnostic() - } -} - -async fn select_shutdown_signal( - ctrl_c: impl Future, - terminate: impl Future, -) { - tokio::select! { - () = ctrl_c => {} - () = terminate => {} - } -} - -async fn ctrl_c_signal() { - if let Err(error) = tokio::signal::ctrl_c().await { - tracing::warn!(%error, "Failed to install Ctrl-C signal handler"); - std::future::pending::<()>().await; - } -} - -#[cfg(unix)] -async fn terminate_signal() { - let Ok(mut signal) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) - else { - tracing::warn!("Failed to install SIGTERM signal handler"); - std::future::pending::<()>().await; - return; - }; - let _ = signal.recv().await; -} - -async fn shutdown_signal() { - #[cfg(unix)] - select_shutdown_signal(ctrl_c_signal(), terminate_signal()).await; - - #[cfg(not(unix))] - ctrl_c_signal().await; - - info!("Received shutdown signal, draining in-flight requests"); -} - -#[cfg(test)] -mod tests { - use super::*; - - #[tokio::test] - async fn shutdown_completes_when_termination_signal_arrives() { - select_shutdown_signal(std::future::pending(), std::future::ready(())).await; - } - - #[test] - fn accepts_gateway_otlp_configuration() { - let args = Args::try_parse_from([ - "openshell-driver-podman", - "--otlp-endpoint", - "http://collector.internal:4317", - "--gateway-name", - "production-us-west", - ]) - .expect("OTLP configuration should be accepted"); - - assert_eq!( - args.otlp.endpoint.as_deref(), - Some("http://collector.internal:4317") - ); - assert_eq!(args.gateway_name.as_deref(), Some("production-us-west")); - } - - #[test] - fn standalone_defaults_preserve_health_checks_and_reject_zero_limits() { - let defaults = Args::try_parse_from(["openshell-driver-podman"]) - .expect("standalone driver defaults should parse"); - assert_eq!( - defaults.health_check_interval_secs.map(NonZeroU64::get), - Some(10) - ); - assert_eq!( - defaults.sandbox_pids_limit.map(NonZeroI64::get), - Some(openshell_core::config::DEFAULT_SANDBOX_PIDS_LIMIT) - ); - - for flag in ["--sandbox-pids-limit", "--health-check-interval-secs"] { - let result = Args::try_parse_from(["openshell-driver-podman", flag, "0"]); - assert!(result.is_err(), "zero must be rejected for {flag}"); - let error = result.err().expect("error was asserted above"); - assert!(error.to_string().contains("invalid value"), "flag: {flag}"); - } - } -} diff --git a/crates/openshell-driver-podman/src/otel_tracing.rs b/crates/openshell-driver-podman/src/otel_tracing.rs deleted file mode 100644 index 8d3314f821..0000000000 --- a/crates/openshell-driver-podman/src/otel_tracing.rs +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! OpenTelemetry tracing identity for the Podman compute driver. - -pub const TRACING: openshell_otel::ComputeDriverTracing = openshell_otel::compute_driver_tracing!(); - -#[cfg(test)] -mod tests { - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn driver_spans_reach_otlp_collector_with_resource_identity() { - openshell_otel_test_support::assert_compute_driver_tracing( - super::TRACING, - openshell_core::VERSION, - "podman.create", - ) - .await; - } -} diff --git a/crates/openshell-driver-podman/src/serve.rs b/crates/openshell-driver-podman/src/serve.rs deleted file mode 100644 index 4350badcdc..0000000000 --- a/crates/openshell-driver-podman/src/serve.rs +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! The launched-driver commands: `serve` and `preflight`. -//! -//! The gateway starts `serve` with bootstrap arguments only and the operator's -//! `[openshell.drivers.podman]` table on stdin, then delivers gateway-owned -//! metadata with the `Configure` RPC. Until `Configure` succeeds the driver -//! creates no Podman networks, volumes or secrets. - -use std::path::PathBuf; - -use clap::Parser; -use openshell_core::VERSION; -use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; -use openshell_driver_podman::config::settings_from_table; -use openshell_driver_podman::driver::check_backend; -use openshell_driver_podman::{ComputeDriverService, PodmanComputeConfig, PodmanComputeDriver}; -use openshell_driver_sdk::launch::{ConfigureRequest, Deferred, Launch, LaunchInfo}; -use openshell_driver_sdk::{GatewayContext, StartResult}; -use tonic::Status; -use tracing::info; - -/// Bootstrap arguments the gateway passes to `serve`. They are frozen for -/// protocol version 1. -#[derive(Parser, Debug)] -#[command(name = "openshell-driver-podman serve")] -struct ServeArgs { - #[arg(long)] - bind_socket: PathBuf, - - #[arg(long)] - expected_peer_pid: u32, - - #[arg(long, default_value = "info")] - log_level: String, -} - -/// Run `serve` or `preflight` when that is the first argument and return the -/// process exit code. Any other invocation returns `None` and takes the -/// standalone path. -pub async fn dispatch() -> Option { - let args: Vec = std::env::args().collect(); - match args.get(1)?.as_str() { - "serve" => { - let parsed = ServeArgs::parse_from( - std::iter::once("openshell-driver-podman serve".to_string()) - .chain(args.into_iter().skip(2)), - ); - Some(serve(parsed).await) - } - "preflight" => Some(preflight()), - _ => None, - } -} - -fn read_settings() -> Result { - let table = openshell_driver_sdk::read_stdin_table() - .map_err(|error| StartResult::invalid_config(format!("read driver table: {error}")))?; - let mut config = settings_from_table(&table).map_err(StartResult::invalid_config)?; - // The environment variable wins over the table, as it always has. - if let Ok(path) = std::env::var("OPENSHELL_PODMAN_SOCKET") { - config.socket_path = Some(path.into()); - } - Ok(config) -} - -fn preflight() -> i32 { - match read_settings() { - Ok(_) => 0, - Err(result) => result.report(), - } -} - -async fn serve(args: ServeArgs) -> i32 { - let tracing = openshell_otel::install_deferred_driver_tracing( - openshell_driver_podman::otel_tracing::TRACING, - &args.log_level, - openshell_core::color::stdout_ansi(), - ); - match run(args, tracing).await { - Ok(()) => 0, - Err(result) => result.report(), - } -} - -async fn run( - args: ServeArgs, - tracing: openshell_otel::DeferredDriverTracing, -) -> Result<(), StartResult> { - let settings = read_settings()?; - openshell_driver_sdk::check_backend_within("Podman", check_backend(&settings)).await?; - - let listener = openshell_core::external_driver_socket::bind_private(&args.bind_socket) - .map_err(StartResult::error)?; - let _cleanup = - openshell_core::external_driver_socket::SocketCleanup::new(args.bind_socket.clone()); - - let launch = Launch::new( - LaunchInfo { - driver_name: "podman".to_string(), - driver_version: VERSION.to_string(), - features: Vec::new(), - }, - move |request| { - let settings = settings.clone(); - let tracing = tracing.clone(); - async move { apply_configure(settings, &tracing, request).await } - }, - ); - let shutdown = launch.shutdown(); - #[cfg(unix)] - openshell_driver_sdk::watch_parent(args.expected_peer_pid, shutdown.clone()); - let deferred = Deferred::new(launch.configured(), |service: &ComputeDriverService| { - ComputeDriverServer::new(service.clone()) - }); - - info!(socket = %args.bind_socket.display(), "Starting Podman compute driver"); - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(launch.into_server()) - .add_service(deferred) - .serve_with_incoming_shutdown( - openshell_core::external_driver_socket::SameUidUnixIncoming::new(listener) - .expecting_peer_pid(args.expected_peer_pid), - openshell_driver_sdk::stop_when_released( - shutdown, - crate::shutdown_signal(), - openshell_driver_sdk::EXTERNAL_STOP_GRACE, - ), - ) - .await - .map_err(|error| StartResult::error(format!("serve: {error}"))) -} - -/// Build the driver from the operator's settings and the gateway's metadata. -async fn apply_configure( - settings: PodmanComputeConfig, - tracing: &openshell_otel::DeferredDriverTracing, - request: ConfigureRequest, -) -> Result { - let gateway = GatewayContext::try_from(&request.gateway.clone().unwrap_or_default())?; - if let Some(export) = openshell_driver_sdk::deferred_export_config( - request.telemetry.as_ref(), - gateway.gateway_name.as_deref(), - VERSION, - )? && let Err(error) = tracing.enable_export(export) - { - tracing::error!(%error, "OTLP exporting could not be started"); - } - let supervisor_otlp = openshell_driver_sdk::supervisor_otlp(request.telemetry.as_ref())?; - let network_trust = openshell_driver_sdk::load_network_trust(request.network_trust.as_ref())?; - let admission = - openshell_driver_sdk::admission_from_json(&request.resource_admission_policy_json)?; - let mut config = driver_config( - settings, - &gateway, - request.image_overrides.as_ref(), - supervisor_otlp, - )?; - config.allow_driver_config = admission.allow_driver_config; - config.resource_admission = admission.resource_admission; - let driver = PodmanComputeDriver::new(config, network_trust) - .await - .map_err(|error| Status::internal(error.to_string()))?; - Ok(ComputeDriverService::new(driver)) -} - -/// The driver configuration for `settings` and the gateway's metadata. The -/// gateway supplies the port and the CA, which the table cannot set. The -/// image overrides win, as the environment did when the gateway built the -/// configuration itself. -fn driver_config( - mut settings: PodmanComputeConfig, - gateway: &GatewayContext, - images: Option<&openshell_driver_sdk::launch::ImageOverrides>, - supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, -) -> Result { - if let Some(port) = gateway.gateway_port { - settings.gateway_port = port; - } - settings.guest_tls_ca.clone_from(&gateway.tls_ca_path); - if openshell_driver_sdk::endpoint_uses_tls(&settings.grpc_endpoint) - && settings.guest_tls_ca.is_none() - { - return Err(Status::invalid_argument( - "grpc_endpoint uses https:// but the gateway supplied no CA path", - )); - } - if let Some(images) = images { - if let Some(image) = &images.sandbox_runtime_image { - settings.sandbox_runtime_image.clone_from(image); - } - if let Some(image) = &images.supervisor_image { - settings.supervisor_image.clone_from(image); - } - } - settings.supervisor_otlp = supervisor_otlp; - settings - .supervisor_gateway_name - .clone_from(&gateway.gateway_name); - Ok(settings) -} - -#[cfg(test)] -mod tests { - use openshell_driver_sdk::launch::ImageOverrides; - - use super::*; - - fn gateway(port: Option, ca: Option<&str>) -> GatewayContext { - GatewayContext { - gateway_port: port, - tls_ca_path: ca.map(PathBuf::from), - gateway_name: Some("gw".to_string()), - bind_address: None, - } - } - - fn build( - settings: PodmanComputeConfig, - gateway: &GatewayContext, - images: Option<&ImageOverrides>, - ) -> Result { - driver_config( - settings, - gateway, - images, - openshell_core::sandbox_env::SupervisorOtlp::default(), - ) - } - - #[test] - fn the_gateway_supplies_the_port_name_and_ca() { - let built = build( - PodmanComputeConfig::default(), - &gateway(Some(9000), Some("/gateway-ca.pem")), - None, - ) - .unwrap(); - assert_eq!(built.gateway_port, 9000); - assert_eq!(built.supervisor_gateway_name.as_deref(), Some("gw")); - assert_eq!(built.guest_tls_ca, Some("/gateway-ca.pem".into())); - - let plain = build(PodmanComputeConfig::default(), &gateway(None, None), None).unwrap(); - assert!(plain.guest_tls_ca.is_none()); - } - - #[test] - fn an_https_endpoint_needs_the_gateway_ca() { - let table = settings_from_table("grpc_endpoint = \"https://host.test:9\"").unwrap(); - let status = build(table.clone(), &gateway(Some(1), None), None).unwrap_err(); - assert_eq!(status.code(), tonic::Code::InvalidArgument); - build(table, &gateway(Some(1), Some("/ca.pem")), None).unwrap(); - } - - #[test] - fn image_overrides_win_over_the_table_as_the_environment_did() { - let table = settings_from_table( - "sandbox_runtime_image = \"table-runtime\"\nsupervisor_image = \"table-supervisor\"", - ) - .unwrap(); - let overrides = ImageOverrides { - sandbox_runtime_image: Some("env-runtime".to_string()), - supervisor_image: None, - }; - let built = build(table, &gateway(None, None), Some(&overrides)).unwrap(); - assert_eq!(built.sandbox_runtime_image, "env-runtime"); - assert_eq!(built.supervisor_image, "table-supervisor"); - } -} diff --git a/crates/openshell-driver-podman/src/test_utils.rs b/crates/openshell-driver-podman/src/test_utils.rs deleted file mode 100644 index 25cbcb4ac2..0000000000 --- a/crates/openshell-driver-podman/src/test_utils.rs +++ /dev/null @@ -1,145 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Shared test helpers for openshell-driver-podman unit tests. - -use http_body_util::{BodyExt as _, Full}; -use hyper::StatusCode; -use hyper::body::Bytes; -use hyper::server::conn::http1; -use hyper::service::service_fn; -use hyper_util::rt::TokioIo; -use std::collections::VecDeque; -use std::convert::Infallible; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use tokio::net::UnixListener; - -/// A canned HTTP response for the Podman stub server. -#[derive(Clone)] -pub struct StubResponse { - pub status: StatusCode, - pub body: Bytes, - pub delay: Duration, - pub archive_members: Option>, -} - -impl StubResponse { - pub fn new(status: StatusCode, body: impl Into) -> Self { - Self { - status, - body: body.into(), - delay: Duration::ZERO, - archive_members: None, - } - } - - pub fn with_delay(mut self, delay: Duration) -> Self { - self.delay = delay; - self - } - - pub fn with_archive_members(mut self, members: &[&str]) -> Self { - self.archive_members = Some(members.iter().map(PathBuf::from).collect()); - self - } -} - -/// Generate a unique Unix socket path for a test. -/// -/// Uses the current PID and nanosecond timestamp to avoid collisions between -/// concurrent test runs. -pub fn unique_socket_path(test_name: &str) -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("clock should be after unix epoch") - .as_nanos(); - PathBuf::from(format!( - "/tmp/openshell-podman-{test_name}-{}-{nanos}.sock", - std::process::id() - )) -} - -/// Spawn a Unix-socket HTTP stub that serves the given `responses` in order. -/// -/// Returns: -/// - the socket path (already bound and listening) -/// - a shared log of `"METHOD /path"` strings, one per request received -/// - a join handle that resolves once all expected requests have been served -pub fn spawn_podman_stub( - test_name: &str, - responses: Vec, -) -> ( - PathBuf, - Arc>>, - tokio::task::JoinHandle<()>, -) { - let socket_path = unique_socket_path(test_name); - let _ = std::fs::remove_file(&socket_path); - let listener = UnixListener::bind(&socket_path).expect("test socket should bind"); - let request_log = Arc::new(Mutex::new(Vec::new())); - let response_queue = Arc::new(Mutex::new(VecDeque::from(responses))); - let expected = response_queue - .lock() - .expect("response queue lock should not be poisoned") - .len(); - let socket_path_for_task = socket_path.clone(); - let log_for_task = request_log.clone(); - let queue_for_task = response_queue; - let handle = tokio::spawn(async move { - for _ in 0..expected { - let (stream, _) = listener.accept().await.expect("test stub should accept"); - let log = log_for_task.clone(); - let queue = queue_for_task.clone(); - let result = http1::Builder::new() - .serve_connection( - TokioIo::new(stream), - service_fn(move |req: hyper::Request| { - let log = log.clone(); - let queue = queue.clone(); - async move { - let path = req.uri().path_and_query().map_or_else( - || req.uri().path().to_string(), - |pq| pq.as_str().to_string(), - ); - log.lock() - .expect("request log lock should not be poisoned") - .push(format!("{} {}", req.method(), path)); - let response = queue - .lock() - .expect("response queue lock should not be poisoned") - .pop_front() - .expect("stub response should exist"); - if let Some(expected_members) = &response.archive_members { - assert_eq!(req.method(), hyper::Method::PUT); - let body = req.into_body().collect().await.unwrap().to_bytes(); - let mut archive = tar::Archive::new(body.as_ref()); - let members: Vec<_> = archive - .entries() - .unwrap() - .map(|entry| entry.unwrap().path().unwrap().into_owned()) - .collect(); - assert_eq!(&members, expected_members); - } - tokio::time::sleep(response.delay).await; - Ok::<_, Infallible>( - hyper::Response::builder() - .status(response.status) - .body(Full::new(response.body)) - .expect("stub response should build"), - ) - } - }), - ) - .await; - // The one-shot test client can close the Unix socket after the - // response, which Hyper reports as a shutdown error. Let the - // request log assertions below decide whether the stub served - // the expected API calls. - let _ = result; - } - let _ = std::fs::remove_file(&socket_path_for_task); - }); - (socket_path, request_log, handle) -} diff --git a/crates/openshell-driver-podman/src/watcher.rs b/crates/openshell-driver-podman/src/watcher.rs deleted file mode 100644 index 9a508e52c3..0000000000 --- a/crates/openshell-driver-podman/src/watcher.rs +++ /dev/null @@ -1,1071 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Maps Podman container events to the compute-driver watch protocol. - -use crate::client::{ - ContainerInspect, ContainerListEntry, ContainerState, HealthState, PodmanApiError, - PodmanClient, PodmanEvent, -}; -use crate::container::{ - LABEL_MANAGED_FILTER, LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, LABEL_SANDBOX_WORKSPACE, short_id, -}; -use futures::Stream; -use openshell_core::ComputeDriverError; -use openshell_core::proto::compute::v1::{ - DriverCondition, DriverSandbox, DriverSandboxStatus, WatchSandboxesDeletedEvent, - WatchSandboxesEvent, WatchSandboxesSandboxEvent, watch_sandboxes_event, -}; -use std::collections::HashMap; -use std::pin::Pin; -use std::sync::{Arc, Mutex}; -use tokio::sync::mpsc; -use tokio_stream::wrappers::ReceiverStream; -use tracing::{debug, info, warn}; - -// Condition reason constants shared across event-building paths. -const CONDITION_RUNNING: &str = "ContainerRunning"; -const CONDITION_STARTING: &str = "ContainerStarting"; -use openshell_core::driver_utils::{ - CONDITION_EXITED, CONDITION_RUNTIME_RESTART, CONDITION_STOPPED, - CONDITION_WORKSPACE_VALIDATION_FAILED, SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED, - WORKSPACE_VALIDATION_FAILED_MESSAGE, -}; - -pub type WatchStream = - Pin> + Send>>; - -/// Per-sandbox container exit timestamps that fence state changes from an earlier run. -/// -/// Podman can deliver a container's `die` or `stop` event after the stop API -/// has returned. If a restart is already in progress, inspecting the container -/// for that delayed event can report the previous exit and incorrectly regress -/// the sandbox from `Starting` to `Error`. -#[derive(Clone, Debug, Default)] -pub struct LifecycleEventFences { - previous_finished_at: Arc>>, -} - -impl LifecycleEventFences { - pub fn record_previous_exit(&self, sandbox_id: &str, finished_at: Option<&str>) { - let mut fences = self - .previous_finished_at - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - match finished_at.filter(|finished_at| !finished_at.is_empty()) { - Some(finished_at) => { - fences.insert(sandbox_id.to_string(), finished_at.to_string()); - } - None => { - fences.remove(sandbox_id); - } - } - } - - pub fn remove(&self, sandbox_id: &str) { - self.previous_finished_at - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .remove(sandbox_id); - } - - fn matches_previous_exit( - &self, - event: &PodmanEvent, - sandbox_id: &str, - state: &ContainerState, - ) -> bool { - if !matches!(event.action.as_str(), "die" | "stop") - || !matches!(state.status.as_str(), "exited" | "stopped") - { - return false; - } - - let Some(finished_at) = state.finished_at.as_deref() else { - return false; - }; - self.previous_finished_at - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .get(sandbox_id) - .is_some_and(|previous| previous == finished_at) - } -} - -/// Build a `WatchSandboxesEvent` carrying a sandbox snapshot. -fn sandbox_event(sandbox: DriverSandbox) -> WatchSandboxesEvent { - WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Sandbox( - WatchSandboxesSandboxEvent { - sandbox: Some(sandbox), - }, - )), - } -} - -/// Build a `WatchSandboxesEvent` for a deleted sandbox. -fn deleted_event(sandbox_id: String) -> WatchSandboxesEvent { - WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Deleted( - WatchSandboxesDeletedEvent { sandbox_id }, - )), - } -} - -/// Start a watch stream that emits current state and live events. -/// -/// The stream first emits a snapshot of all currently-running managed -/// sandboxes (initial state sync), then delivers live container events -/// as they arrive from the Podman event stream. -/// -/// # Reconnection contract -/// -/// The returned stream is **single-use**. When the Podman event connection -/// drops (daemon restart, socket error, or clean shutdown), the stream -/// terminates with a final error item and stops producing events. -/// -/// Callers are responsible for reconnecting by calling [`start_watch`] again -/// and re-synchronizing state. -/// -/// **Do not add reconnection logic inside this function.** A local reconnect -/// would race with the consumer's retry and produce duplicate initial-sync -/// events. -pub async fn start_watch( - client: PodmanClient, - lifecycle_event_fences: LifecycleEventFences, -) -> Result { - let (tx, rx) = mpsc::channel::>(256); - - // 1. Subscribe to events first so we don't miss any during the list. - let mut event_rx = client.events_stream(LABEL_MANAGED_FILTER).await?; - - // 2. List existing containers for initial state sync. - let existing = client - .list_containers(&[LABEL_MANAGED_FILTER, crate::isolation::WORKLOAD_FILTER]) - .await?; - - for entry in &existing { - // For running containers, use inspect to get full state including - // health check status — matching the same condition derivation used - // for live events. - if entry.state == "running" { - match inspect_workload(&client, &entry.id).await { - Ok(inspect) => { - if let Some(sandbox) = driver_sandbox_from_inspect(&inspect) { - if tx.send(Ok(sandbox_event(sandbox))).await.is_err() { - return Err(PodmanApiError::Connection( - "watch receiver dropped during initial sync".into(), - )); - } - continue; - } - } - Err(e) => { - warn!( - container_id = %entry.id, - error = %e, - "Failed to inspect running container during initial sync, falling back to list entry" - ); - } - } - } - if let Some(event) = driver_sandbox_from_list_entry(entry).map(sandbox_event) - && tx.send(Ok(event)).await.is_err() - { - return Err(PodmanApiError::Connection( - "watch receiver dropped during initial sync".into(), - )); - } - } - - // 3. Stream live events (buffered during the list operation above). - - tokio::spawn(async move { - while let Some(result) = event_rx.recv().await { - match result { - Ok(event) => { - if let Some(we) = - map_podman_event(&event, &client, &lifecycle_event_fences).await - && tx.send(Ok(we)).await.is_err() - { - return; - } - } - Err(e) => { - if tx - .send(Err(ComputeDriverError::Message(e.to_string()))) - .await - .is_err() - { - return; - } - } - } - } - // The Podman event stream has ended — either because the Podman - // daemon restarted, the Unix socket was closed, or the connection - // dropped. We do NOT reconnect here; see the doc-comment on - // start_watch() for the full reconnection contract. - // - // Sending this error terminates the WatchStream seen by the caller. - // The server's watch_loop detects the terminal error, waits 2 seconds, - // then calls watch_sandboxes() → start_watch() again, which re-lists - // all containers and re-subscribes to events. This ensures a full - // state resync after any Podman daemon interruption. - warn!("podman event stream ended unexpectedly; watch_loop will reconnect"); - let _ = tx - .send(Err(ComputeDriverError::Message( - "podman event stream ended unexpectedly".to_string(), - ))) - .await; - }); - - Ok(Box::pin(ReceiverStream::new(rx))) -} - -/// Map a Podman event to an optional watch event. -/// -/// Some events (like `remove`) produce a deletion event. State-change events -/// trigger a container inspect to build a full snapshot. -async fn map_podman_event( - event: &PodmanEvent, - client: &PodmanClient, - lifecycle_event_fences: &LifecycleEventFences, -) -> Option { - let container_id = &event.actor.id; - let sandbox_id = event - .actor - .attributes - .get(LABEL_SANDBOX_ID) - .cloned() - .unwrap_or_default(); - - if sandbox_id.is_empty() { - debug!( - container_id = %container_id, - action = %event.action, - "Ignoring event for container without sandbox-id label" - ); - return None; - } - - if event - .actor - .attributes - .get(crate::isolation::LABEL_ROLE) - .is_some_and(|role| role == "supervisor") - { - let id_filter = format!("{LABEL_SANDBOX_ID}={sandbox_id}"); - let workloads = client - .list_containers(&[ - LABEL_MANAGED_FILTER, - &id_filter, - crate::isolation::WORKLOAD_FILTER, - ]) - .await - .ok()?; - let workload = workloads.first()?; - return inspect_workload(client, &workload.id) - .await - .ok() - .and_then(|inspect| driver_sandbox_from_inspect(&inspect)) - .map(sandbox_event); - } - - match event.action.as_str() { - "remove" => Some(deleted_event(sandbox_id.clone())), - "create" | "start" | "stop" | "die" | "health_status" => { - // Inspect the container to get current state. - match inspect_workload(client, container_id).await { - Ok(inspect) => { - if lifecycle_event_fences.matches_previous_exit( - event, - &sandbox_id, - &inspect.state, - ) { - debug!( - sandbox_id, - container_id = %container_id, - action = %event.action, - finished_at = inspect.state.finished_at.as_deref().unwrap_or_default(), - "Ignoring container stop event from before the latest sandbox start" - ); - None - } else { - driver_sandbox_from_inspect(&inspect).map(sandbox_event) - } - } - Err(PodmanApiError::NotFound(_)) => { - // The container is already gone by the time we inspected - // it. This is a normal race between the `die`/`stop` event - // and the subsequent `remove` event: Podman fires `die` - // first, but the container may be fully removed before we - // can inspect it. Treat this as a deletion so the server - // does not see a spurious phase regression. - info!( - container_id = %container_id, - action = %event.action, - "Container already removed when inspecting after event, emitting deleted event" - ); - Some(deleted_event(sandbox_id.clone())) - } - Err(e) => { - warn!( - container_id = %container_id, - error = %e, - "Failed to inspect container after event" - ); - // Emit a synthetic event with the info we have so the - // server knows something happened. - let sandbox_name = event - .actor - .attributes - .get(LABEL_SANDBOX_NAME) - .cloned() - .unwrap_or_default(); - let workspace = event - .actor - .attributes - .get(LABEL_SANDBOX_WORKSPACE) - .cloned()?; - Some(sandbox_event(build_driver_sandbox( - sandbox_id.clone(), - sandbox_name, - workspace, - String::new(), - short_id(container_id), - DriverCondition { - r#type: "Ready".to_string(), - status: "Unknown".to_string(), - reason: "InspectFailed".to_string(), - message: format!("Container inspect failed: {e}"), - transition_time: None, - }, - false, - ))) - } - } - } - _ => { - debug!(action = %event.action, "Ignoring unhandled Podman event"); - None - } - } -} - -/// A workload is ready only when its independent supervisor is healthy. This -/// check runs both on watch reconciliation and on events, and contains a lost -/// supervisor even when the gateway missed the original exit event. -pub async fn inspect_workload( - client: &PodmanClient, - id: &str, -) -> Result { - let mut workload = client.inspect_container(id).await?; - if workload - .config - .labels - .get(crate::isolation::LABEL_ROLE) - .is_none_or(|role| role != "sandbox") - { - return Ok(workload); - } - let Some(sandbox_id) = workload.config.labels.get(LABEL_SANDBOX_ID) else { - return Ok(workload); - }; - let supervisor = client - .inspect_container(&crate::isolation::supervisor_name(sandbox_id)) - .await; - let supervisor_exit_code = supervisor - .as_ref() - .ok() - .and_then(|supervisor| exited_exit_code(&supervisor.state)); - if workload.state.running { - match supervisor { - Ok(supervisor) if supervisor.state.running => { - workload.state.health = supervisor.state.health; - } - Ok(supervisor) - if supervisor.state.status == "configured" - || supervisor.state.status == "created" => - { - workload.state.health = Some(HealthState { - status: "starting".into(), - }); - } - // Both containers exist before initial start. A missing or exited - // companion therefore requires containment, including after a - // gateway restart that missed the original Podman exit event. - Ok(_) | Err(PodmanApiError::NotFound(_)) => { - client.stop_container(&workload.id, 0).await?; - workload = client.inspect_container(&workload.id).await?; - } - Err(error) => return Err(error), - } - } else if matches!(workload.state.status.as_str(), "exited" | "stopped") { - workload.state.startup_diagnostic = client - .container_logs(&workload.id) - .await - .ok() - .and_then(|logs| boundary_startup_termination_marker(&logs)); - } - workload.state.supervisor_exit_code = supervisor_exit_code; - Ok(workload) -} - -fn exited_exit_code(state: &ContainerState) -> Option { - matches!(state.status.as_str(), "exited" | "stopped").then_some(state.exit_code) -} - -/// Extract only fixed, OpenShell-owned startup diagnostics from container -/// output. Workload and supervisor output may contain secrets, so it must not -/// be propagated to driver conditions or tracing. -fn boundary_startup_termination_marker(logs: &[u8]) -> Option { - const SIGTERM_MARKER: &str = "sandbox boundary received SIGTERM before supervisor confirmation"; - const SIGINT_MARKER: &str = "sandbox boundary received SIGINT before supervisor confirmation"; - - let logs = String::from_utf8_lossy(logs); - [SIGTERM_MARKER, SIGINT_MARKER] - .into_iter() - .find(|marker| logs.contains(marker)) - .map(str::to_string) -} - -/// Construct a `DriverSandbox` from common fields. -/// -/// Centralises the boilerplate that every event/inspect/list path shares: -/// `namespace`, `spec`, `agent_fd`, and `sandbox_fd` are always empty in -/// the Podman driver. -fn build_driver_sandbox( - sandbox_id: String, - sandbox_name: String, - workspace: String, - instance_name: String, - instance_id: String, - condition: DriverCondition, - deleting: bool, -) -> DriverSandbox { - DriverSandbox { - id: sandbox_id, - name: sandbox_name, - namespace: String::new(), - spec: None, - status: Some(DriverSandboxStatus { - name: instance_name, - instance_id, - agent_fd: String::new(), - sandbox_fd: String::new(), - conditions: vec![condition], - deleting, - ..Default::default() - }), - workspace, - } -} - -/// Build a `DriverSandbox` from a container inspection result. -pub fn driver_sandbox_from_inspect(inspect: &ContainerInspect) -> Option { - let sandbox_id = inspect.config.labels.get(LABEL_SANDBOX_ID)?.clone(); - let sandbox_name = inspect - .config - .labels - .get(LABEL_SANDBOX_NAME) - .cloned() - .unwrap_or_default(); - let workspace = inspect - .config - .labels - .get(LABEL_SANDBOX_WORKSPACE) - .cloned()?; - - let condition = condition_from_state(&inspect.state); - let deleting = inspect.state.status == "removing"; - - Some(build_driver_sandbox( - sandbox_id, - sandbox_name, - workspace, - inspect.name.trim_start_matches('/').to_string(), - short_id(&inspect.id), - condition, - deleting, - )) -} - -/// Build a `DriverSandbox` from a container list entry (no inspect needed). -pub fn driver_sandbox_from_list_entry(entry: &ContainerListEntry) -> Option { - let sandbox_id = entry.labels.get(LABEL_SANDBOX_ID)?.clone(); - let sandbox_name = entry - .labels - .get(LABEL_SANDBOX_NAME) - .cloned() - .unwrap_or_default(); - let workspace = entry.labels.get(LABEL_SANDBOX_WORKSPACE).cloned()?; - - let (reason, status_str, message) = match entry.state.as_str() { - "running" => ( - CONDITION_RUNNING, - "True", - "Container is running".to_string(), - ), - "created" => ("ContainerCreated", "False", String::new()), - "exited" => (CONDITION_EXITED, "False", String::new()), - "stopped" => (CONDITION_STOPPED, "False", String::new()), - "removing" => ("ContainerRemoving", "False", String::new()), - _ => ("Unknown", "Unknown", String::new()), - }; - - Some(build_driver_sandbox( - sandbox_id, - sandbox_name, - workspace, - entry.names.first().cloned().unwrap_or_default(), - short_id(&entry.id), - DriverCondition { - r#type: "Ready".to_string(), - status: status_str.to_string(), - reason: reason.to_string(), - message, - transition_time: None, - }, - entry.state == "removing", - )) -} - -/// Derive a `DriverCondition` from Podman container state. -fn condition_from_state(state: &ContainerState) -> DriverCondition { - let (status_val, reason, message) = match state.status.as_str() { - "running" => match &state.health { - Some(HealthState { status }) if status == "healthy" => { - ("True", "HealthCheckPassed", String::new()) - } - Some(HealthState { status }) if status == "unhealthy" => { - ("False", "HealthCheckFailed", String::new()) - } - Some(HealthState { status }) if status == "starting" => { - ("False", "HealthCheckStarting", String::new()) - } - None => ( - "True", - CONDITION_RUNNING, - "Container is running".to_string(), - ), - Some(_) => ("False", CONDITION_STARTING, String::new()), - }, - "created" => ("False", "ContainerCreated", String::new()), - "exited" | "stopped" => { - // Exit codes 137 (128+SIGKILL) and 143 (128+SIGTERM) mean the - // container was terminated by an external signal rather than - // exiting on its own — the signature of a machine/daemon restart - // killing running containers. Those are recoverable at gateway - // startup; ordinary application exits (0, non-zero, faults) are not. - let (reason, mut msg) = if state.oom_killed { - ( - "OOMKilled", - "Container was killed by the OOM killer".to_string(), - ) - } else if state.supervisor_exit_code - == Some(i64::from(SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED)) - { - ( - CONDITION_WORKSPACE_VALIDATION_FAILED, - WORKSPACE_VALIDATION_FAILED_MESSAGE.to_string(), - ) - } else if matches!(state.exit_code, 137 | 143) { - ( - CONDITION_RUNTIME_RESTART, - format!( - "Container terminated by signal (exit code {})", - state.exit_code - ), - ) - } else { - ( - CONDITION_EXITED, - format!("Container exited with code {}", state.exit_code), - ) - }; - if let Some(diagnostic) = &state.startup_diagnostic { - msg.push_str(": "); - msg.push_str(diagnostic); - } - ("False", reason, msg) - } - other => ( - "Unknown", - "Unknown", - format!("Unknown container state: {other}"), - ), - }; - - // Use Podman's state timestamps for transition_time: - // - Running/healthy states use started_at - // - Stopped/exited states use finished_at - let transition_time = match state.status.as_str() { - "running" => state.started_at.clone().unwrap_or_default(), - "exited" | "stopped" => state.finished_at.clone().unwrap_or_default(), - _ => String::new(), - } - .parse() - .ok(); - - DriverCondition { - r#type: "Ready".to_string(), - status: status_val.to_string(), - reason: reason.to_string(), - message, - transition_time, - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[tokio::test] - async fn missing_supervisor_stops_workload_during_reconciliation() { - use crate::test_utils::{StubResponse, spawn_podman_stub}; - use hyper::StatusCode; - let (path, requests, handle) = spawn_podman_stub( - "lost-supervisor", - vec![ - StubResponse::new( - StatusCode::OK, - r#"{"Id":"workload","Name":"workload","State":{"Status":"running","Running":true},"Config":{"Labels":{"openshell.ai/sandbox-id":"test","openshell.ai/isolation-role":"sandbox"}}}"#, - ), - StubResponse::new(StatusCode::NOT_FOUND, "missing companion"), - StubResponse::new(StatusCode::NO_CONTENT, ""), - StubResponse::new( - StatusCode::OK, - r#"{"Id":"workload","Name":"workload","State":{"Status":"exited","Running":false},"Config":{}}"#, - ), - ], - ); - let client = PodmanClient::new(path.clone()); - let inspected = inspect_workload(&client, "workload").await.unwrap(); - assert!(!inspected.state.running); - handle.await.unwrap(); - assert!( - requests - .lock() - .unwrap() - .iter() - .any(|request| request.ends_with("/libpod/containers/workload/stop?timeout=0")) - ); - let _ = std::fs::remove_file(path); - } - - #[tokio::test] - async fn created_supervisor_keeps_bootstrapping_workload_starting() { - use crate::test_utils::{StubResponse, spawn_podman_stub}; - use hyper::StatusCode; - let (path, requests, handle) = spawn_podman_stub( - "starting-supervisor", - vec![ - StubResponse::new( - StatusCode::OK, - r#"{"Id":"workload","Name":"workload","State":{"Status":"running","Running":true},"Config":{"Labels":{"openshell.ai/sandbox-id":"test","openshell.ai/isolation-role":"sandbox"}}}"#, - ), - StubResponse::new( - StatusCode::OK, - r#"{"Id":"supervisor","Name":"supervisor","State":{"Status":"configured","Running":false},"Config":{}}"#, - ), - ], - ); - let client = PodmanClient::new(path.clone()); - let inspected = inspect_workload(&client, "workload").await.unwrap(); - assert!(inspected.state.running); - assert_eq!(inspected.state.health.unwrap().status, "starting"); - handle.await.unwrap(); - assert_eq!(requests.lock().unwrap().len(), 2); - let _ = std::fs::remove_file(path); - } - - fn podman_event(action: &str, sandbox_id: &str, time_nano: i64) -> PodmanEvent { - podman_event_for_container(action, sandbox_id, "container-1", time_nano) - } - - fn podman_event_for_container( - action: &str, - sandbox_id: &str, - container_id: &str, - time_nano: i64, - ) -> PodmanEvent { - PodmanEvent { - event_type: "container".to_string(), - action: action.to_string(), - actor: crate::client::EventActor { - id: container_id.to_string(), - attributes: HashMap::from([(LABEL_SANDBOX_ID.to_string(), sandbox_id.to_string())]), - }, - time_nano, - } - } - - #[tokio::test] - async fn unrelated_remove_deletes_the_sandbox() { - let fences = LifecycleEventFences::default(); - let client = PodmanClient::new(crate::test_utils::unique_socket_path("watch-removals")); - - let event = map_podman_event( - &podman_event_for_container("remove", "sandbox-1", "external-container", 2), - &client, - &fences, - ) - .await - .expect("an unrelated remove must still delete the sandbox"); - assert!(matches!( - event.payload, - Some(watch_sandboxes_event::Payload::Deleted(_)) - )); - } - - #[test] - fn lifecycle_fence_rejects_delayed_stop_events_from_before_restart() { - let fences = LifecycleEventFences::default(); - fences.record_previous_exit("sandbox-1", Some("2026-08-12T16:39:13Z")); - let previous_exit = ContainerState { - status: "exited".to_string(), - running: false, - exit_code: 137, - oom_killed: false, - health: None, - started_at: Some("2026-08-12T16:38:58Z".to_string()), - finished_at: Some("2026-08-12T16:39:13Z".to_string()), - supervisor_exit_code: None, - startup_diagnostic: None, - }; - - assert!(fences.matches_previous_exit( - &podman_event("die", "sandbox-1", 199), - "sandbox-1", - &previous_exit, - )); - assert!(fences.matches_previous_exit( - &podman_event("stop", "sandbox-1", 200), - "sandbox-1", - &previous_exit, - )); - - let mut new_exit = previous_exit.clone(); - new_exit.finished_at = Some("2026-08-12T16:40:00Z".to_string()); - assert!(!fences.matches_previous_exit( - &podman_event("die", "sandbox-1", 201), - "sandbox-1", - &new_exit, - )); - - let mut running = previous_exit.clone(); - running.status = "running".to_string(); - running.finished_at = None; - assert!(!fences.matches_previous_exit( - &podman_event("die", "sandbox-1", 201), - "sandbox-1", - &running, - )); - assert!(!fences.matches_previous_exit( - &podman_event("start", "sandbox-1", 199), - "sandbox-1", - &previous_exit, - )); - } - - #[test] - fn condition_healthy_container() { - let state = ContainerState { - status: "running".to_string(), - running: true, - exit_code: 0, - oom_killed: false, - health: Some(HealthState { - status: "healthy".to_string(), - }), - started_at: Some("2026-04-14T10:00:00Z".to_string()), - finished_at: None, - supervisor_exit_code: None, - startup_diagnostic: None, - }; - let cond = condition_from_state(&state); - assert_eq!(cond.r#type, "Ready"); - assert_eq!(cond.status, "True"); - assert_eq!(cond.reason, "HealthCheckPassed"); - assert_eq!(cond.transition_time, "2026-04-14T10:00:00Z".parse().ok()); - } - - #[test] - fn condition_running_without_healthcheck_is_ready() { - let state = ContainerState { - status: "running".to_string(), - running: true, - exit_code: 0, - oom_killed: false, - health: None, - started_at: Some("2026-04-14T10:00:00Z".to_string()), - finished_at: None, - supervisor_exit_code: None, - startup_diagnostic: None, - }; - let cond = condition_from_state(&state); - assert_eq!(cond.r#type, "Ready"); - assert_eq!(cond.status, "True"); - assert_eq!(cond.reason, CONDITION_RUNNING); - assert_eq!(cond.message, "Container is running"); - assert_eq!(cond.transition_time, "2026-04-14T10:00:00Z".parse().ok()); - } - - #[test] - fn condition_running_with_pending_healthcheck_is_not_ready() { - let state = ContainerState { - status: "running".to_string(), - running: true, - exit_code: 0, - oom_killed: false, - health: Some(HealthState { - status: "starting".to_string(), - }), - started_at: Some("2026-04-14T10:00:00Z".to_string()), - finished_at: None, - supervisor_exit_code: None, - startup_diagnostic: None, - }; - let condition = condition_from_state(&state); - assert_eq!(condition.r#type, "Ready"); - assert_eq!(condition.status, "False"); - assert_eq!(condition.reason, "HealthCheckStarting"); - } - - #[test] - fn condition_oom_killed() { - let state = ContainerState { - status: "exited".to_string(), - running: false, - exit_code: 137, - oom_killed: true, - health: None, - started_at: None, - finished_at: Some("2026-04-14T11:00:00Z".to_string()), - supervisor_exit_code: None, - startup_diagnostic: None, - }; - let cond = condition_from_state(&state); - assert_eq!(cond.status, "False"); - assert_eq!(cond.reason, "OOMKilled"); - assert_eq!(cond.transition_time, "2026-04-14T11:00:00Z".parse().ok()); - } - - #[test] - fn condition_normal_exit() { - let state = ContainerState { - status: "exited".to_string(), - running: false, - exit_code: 1, - oom_killed: false, - health: None, - started_at: None, - finished_at: Some("2026-04-14T12:00:00Z".to_string()), - supervisor_exit_code: None, - startup_diagnostic: None, - }; - let cond = condition_from_state(&state); - assert_eq!(cond.status, "False"); - assert_eq!(cond.reason, "ContainerExited"); - assert!(cond.message.contains("code 1")); - } - - #[test] - fn condition_includes_allow_listed_boundary_startup_diagnostic() { - let state = ContainerState { - status: "exited".to_string(), - running: false, - exit_code: 1, - oom_killed: false, - health: None, - started_at: None, - finished_at: Some("2026-04-14T12:00:00Z".to_string()), - supervisor_exit_code: None, - startup_diagnostic: boundary_startup_termination_marker( - b"untrusted workload output\nsandbox boundary received SIGTERM before supervisor confirmation\n", - ), - }; - - let condition = condition_from_state(&state); - - assert_eq!(condition.reason, CONDITION_EXITED); - assert_eq!( - condition.message, - "Container exited with code 1: sandbox boundary received SIGTERM before supervisor confirmation" - ); - } - - #[test] - fn boundary_startup_diagnostic_does_not_forward_unrecognized_logs() { - assert_eq!( - boundary_startup_termination_marker(b"token=not-for-the-driver"), - None - ); - } - - #[test] - fn condition_workspace_validation_exit_is_reported_explicitly() { - // The supervisor exits with the reserved status and the watcher then - // stops the workload, so the workload itself reports SIGKILL. - let mut state = ContainerState { - status: "exited".to_string(), - running: false, - exit_code: 137, - oom_killed: false, - health: None, - started_at: None, - finished_at: Some("2026-04-14T12:00:00Z".to_string()), - supervisor_exit_code: Some(i64::from(SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED)), - startup_diagnostic: None, - }; - - let cond = condition_from_state(&state); - - assert_eq!(cond.reason, CONDITION_WORKSPACE_VALIDATION_FAILED); - assert_eq!(cond.message, WORKSPACE_VALIDATION_FAILED_MESSAGE); - - // A workload's own exit with the reserved status is not a supervisor - // workspace rejection. - state.exit_code = i64::from(SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED); - state.supervisor_exit_code = Some(1); - assert_eq!(condition_from_state(&state).reason, CONDITION_EXITED); - } - - #[test] - fn condition_signal_kill_is_runtime_restart() { - // 137 (128+SIGKILL) and 143 (128+SIGTERM) are external terminations — - // the signature of a machine/daemon restart. They classify as - // recoverable `ContainerRuntimeRestart`, distinct from an ordinary - // application exit. - for exit_code in [137, 143] { - let state = ContainerState { - status: "exited".to_string(), - running: false, - exit_code, - oom_killed: false, - health: None, - started_at: None, - finished_at: Some("2026-04-14T12:30:00Z".to_string()), - supervisor_exit_code: None, - startup_diagnostic: None, - }; - let cond = condition_from_state(&state); - assert_eq!(cond.status, "False"); - assert_eq!( - cond.reason, "ContainerRuntimeRestart", - "exit code {exit_code} should classify as runtime restart" - ); - assert!(cond.message.contains(&format!("code {exit_code}"))); - } - } - - #[test] - fn short_id_truncates() { - assert_eq!(short_id("abc123def456789"), "abc123def456"); - assert_eq!(short_id("short"), "short"); - } - - #[test] - fn sandbox_event_from_list_entry_running() { - let mut labels = HashMap::new(); - labels.insert(LABEL_SANDBOX_ID.to_string(), "test-id".to_string()); - labels.insert(LABEL_SANDBOX_NAME.to_string(), "test-name".to_string()); - labels.insert(LABEL_SANDBOX_WORKSPACE.to_string(), "default".to_string()); - - let entry = ContainerListEntry { - id: "abc123def456789".to_string(), - names: vec!["openshell-sandbox-test-name".to_string()], - state: "running".to_string(), - labels, - ports: None, - networks: None, - exit_code: 0, - }; - - let sandbox = driver_sandbox_from_list_entry(&entry).expect("should produce a sandbox"); - let status = sandbox.status.expect("should have status"); - assert_eq!(status.conditions.len(), 1); - let cond = &status.conditions[0]; - assert_eq!(cond.status, "True"); - assert_eq!(cond.reason, "ContainerRunning"); - assert!(!status.deleting); - } - - #[test] - fn synthetic_inspect_failed_event_structure() { - // Verify the structure of an inspect-failure event by constructing one - // using the same pattern as the production code. - let condition = DriverCondition { - r#type: "Ready".to_string(), - status: "Unknown".to_string(), - reason: "InspectFailed".to_string(), - message: "Container inspect failed: connection refused".to_string(), - transition_time: None, - }; - - let sandbox = DriverSandbox { - id: "sandbox-123".to_string(), - name: "test-sandbox".to_string(), - namespace: String::new(), - spec: None, - status: Some(DriverSandboxStatus { - name: String::new(), - instance_id: short_id("container-id-full"), - agent_fd: String::new(), - sandbox_fd: String::new(), - conditions: vec![condition], - deleting: false, - ..Default::default() - }), - workspace: String::new(), - }; - - let event = WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Sandbox( - WatchSandboxesSandboxEvent { - sandbox: Some(sandbox), - }, - )), - }; - - let payload = event.payload.unwrap(); - let watch_sandboxes_event::Payload::Sandbox(sandbox_event) = payload else { - panic!("expected Sandbox payload") - }; - let status = sandbox_event.sandbox.unwrap().status.unwrap(); - assert_eq!(status.conditions.len(), 1); - let cond = &status.conditions[0]; - assert_eq!(cond.reason, "InspectFailed"); - assert_eq!(cond.status, "Unknown"); - assert!(cond.message.contains("inspect failed")); - } - - #[test] - fn not_found_inspect_produces_deleted_event() { - // When inspect_container returns NotFound (404) after a `die` or - // `stop` event, the container is already gone. The watcher should emit - // a deleted_event rather than a synthetic InspectFailed sandbox event, - // preventing the server from regressing the sandbox phase back to - // Provisioning. - // - // We verify the shape of a deleted_event directly since - // map_podman_event is async and requires a live Podman client. The - // production code path is: - // Err(PodmanApiError::NotFound(_)) => Some(deleted_event(sandbox_id)) - let sandbox_id = "sandbox-abc-123".to_string(); - let event = deleted_event(sandbox_id.clone()); - - let payload = event.payload.expect("deleted event must have a payload"); - match payload { - watch_sandboxes_event::Payload::Deleted(d) => { - assert_eq!(d.sandbox_id, sandbox_id); - } - other => { - panic!( - "expected Deleted payload, got {other:?} — a NotFound inspect must not produce a sandbox or platform event" - ); - } - } - } -} diff --git a/crates/openshell-driver-podman/tests/podman_preflight.rs b/crates/openshell-driver-podman/tests/podman_preflight.rs deleted file mode 100644 index 439cb95d98..0000000000 --- a/crates/openshell-driver-podman/tests/podman_preflight.rs +++ /dev/null @@ -1,89 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Podman driver daemon-unavailable integration tests. -//! -//! These tests verify that `openshell-driver-podman` fails fast with an -//! actionable error when it cannot reach a Podman API socket, instead of -//! hanging or silently serving gRPC against a dead connection. -//! -//! They do NOT require a running Podman daemon or gateway — they point -//! `--podman-socket` at a path that is guaranteed not to exist to simulate -//! the daemon being unavailable. As a plain Cargo integration test in this -//! crate, this runs via the normal `cargo test -p openshell-driver-podman` -//! lane with no special CI wiring: Cargo provides `CARGO_BIN_EXE_` for -//! this crate's own `[[bin]]` target automatically. - -use std::path::PathBuf; -use std::time::{Duration, Instant}; - -/// Run `openshell-driver-podman` pointed at a Podman socket that does not -/// exist, and wait for it to exit. -/// -/// The driver retries a handful of times before giving up (to tolerate the -/// socket briefly re-activating), so this can take several seconds. -async fn run_with_unreachable_podman_socket() -> (String, i32, Duration, PathBuf) { - let tmpdir = tempfile::tempdir().expect("create isolated socket dir"); - // Use a short relative path so miette cannot insert a line-wrap gutter - // inside it on platforms with long temporary-directory paths. - let missing_socket = PathBuf::from("missing-podman.sock"); - - let start = Instant::now(); - let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell-driver-podman")); - cmd.arg("--podman-socket") - .arg(&missing_socket) - .current_dir(tmpdir.path()) - .kill_on_drop(true) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()); - - let output = tokio::time::timeout(Duration::from_mins(1), cmd.output()) - .await - .expect("openshell-driver-podman should exit instead of hanging") - .expect("spawn openshell-driver-podman"); - let elapsed = start.elapsed(); - let stdout = String::from_utf8_lossy(&output.stdout).to_string(); - let stderr = String::from_utf8_lossy(&output.stderr).to_string(); - let combined = format!("{stdout}{stderr}"); - let code = output.status.code().unwrap_or(-1); - (combined, code, elapsed, missing_socket) -} - -/// `openshell-driver-podman` should exit non-zero, not hang, when its -/// configured Podman socket does not exist. -#[tokio::test] -async fn driver_exits_when_podman_socket_unreachable() { - let (output, code, elapsed, _) = run_with_unreachable_podman_socket().await; - - assert_ne!( - code, 0, - "driver should exit non-zero when Podman is unreachable, output:\n{output}" - ); - - assert!( - elapsed < Duration::from_secs(30), - "driver should give up retrying and exit within its bounded retry \ - window (took {}s), output:\n{output}", - elapsed.as_secs() - ); -} - -/// The error surfaced when the Podman socket is unreachable should name the -/// configured socket path and describe a connection failure, not a generic -/// panic or timeout with no actionable detail. -#[tokio::test] -async fn driver_error_names_unreachable_socket() { - let (output, code, _, missing_socket) = run_with_unreachable_podman_socket().await; - - assert_ne!(code, 0); - - assert!( - output.contains("connection error"), - "driver error should describe a connection failure:\n{output}" - ); - assert!( - output.contains(missing_socket.to_str().expect("socket path is utf-8")), - "driver error should name the unreachable socket path {}:\n{output}", - missing_socket.display() - ); -} diff --git a/crates/openshell-driver-podman/tests/serve_configure.rs b/crates/openshell-driver-podman/tests/serve_configure.rs deleted file mode 100644 index 896f790739..0000000000 --- a/crates/openshell-driver-podman/tests/serve_configure.rs +++ /dev/null @@ -1,303 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Runs the real `openshell-driver-podman` binary through `serve` and -//! `preflight` against a fake Podman API socket. - -#![cfg(unix)] - -use std::io::{Read as _, Write as _}; -use std::os::unix::net::UnixListener; -use std::path::Path; -use std::process::{Child, Command, Output, Stdio}; -use std::time::{Duration, Instant}; - -use hyper_util::rt::TokioIo; -use openshell_core::proto::compute::v1::GetCapabilitiesRequest; -use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; -use openshell_driver_sdk::launch::proto::driver_launch_client::DriverLaunchClient; -use openshell_driver_sdk::launch::{ - ConfigureRequest, GetLaunchInfoRequest, PROTOCOL_VERSION, ShutdownRequest, -}; -use tonic::Code; -use tonic::transport::{Channel, Endpoint}; - -const BIN: &str = env!("CARGO_BIN_EXE_openshell-driver-podman"); - -fn command(args: &[&str], table: &str, dir: &Path) -> Command { - // The table is a file, as the gateway provides it, so it always ends. - let stdin = dir.join("table.toml"); - std::fs::write(&stdin, table).unwrap(); - let mut command = Command::new(BIN); - command - .args(args) - .env_remove("OPENSHELL_PODMAN_SOCKET") - .stdin(std::fs::File::open(stdin).unwrap()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()); - command -} - -fn run(args: &[&str], table: &str) -> Output { - let dir = tempfile::tempdir().unwrap(); - command(args, table, dir.path()).output().unwrap() -} - -/// A Podman API that answers every request with `200 OK`. -fn fake_podman(path: &Path) { - let listener = UnixListener::bind(path).unwrap(); - std::thread::spawn(move || { - for stream in listener.incoming() { - let Ok(mut stream) = stream else { continue }; - let mut buffer = [0_u8; 4096]; - let _ = stream.read(&mut buffer); - let _ = stream - .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK"); - } - }); -} - -struct Serving { - child: Child, - channel: Channel, - _dir: tempfile::TempDir, -} - -impl Drop for Serving { - fn drop(&mut self) { - let _ = self.child.kill(); - let _ = self.child.wait(); - } -} - -async fn connect(path: &Path) -> Option { - let path = path.to_path_buf(); - Endpoint::try_from("http://localhost") - .unwrap() - .connect_with_connector(tower::service_fn(move |_| { - let path = path.clone(); - async move { - Ok::<_, std::io::Error>(TokioIo::new(tokio::net::UnixStream::connect(path).await?)) - } - })) - .await - .ok() -} - -async fn serve() -> Serving { - let dir = tempfile::tempdir().unwrap(); - let podman = dir.path().join("podman.sock"); - fake_podman(&podman); - let socket = dir.path().join("driver.sock"); - let table = format!("socket_path = \"{}\"\n", podman.display()); - let mut child = command( - &[ - "serve", - "--bind-socket", - socket.to_str().unwrap(), - "--expected-peer-pid", - &std::process::id().to_string(), - ], - &table, - dir.path(), - ) - .spawn() - .unwrap(); - let deadline = Instant::now() + Duration::from_mins(1); - loop { - if let Some(status) = child.try_wait().unwrap() { - panic!("driver exited early: {status}"); - } - if let Some(channel) = connect(&socket).await { - return Serving { - child, - channel, - _dir: dir, - }; - } - assert!( - Instant::now() < deadline, - "driver never accepted a connection" - ); - tokio::time::sleep(Duration::from_millis(50)).await; - } -} - -fn configure(version: u32) -> ConfigureRequest { - ConfigureRequest { - protocol_version: version, - ..Default::default() - } -} - -#[tokio::test] -async fn launch_info_answers_and_compute_calls_wait_for_configure() { - let serving = serve().await; - - let info = DriverLaunchClient::new(serving.channel.clone()) - .get_launch_info(GetLaunchInfoRequest {}) - .await - .unwrap() - .into_inner(); - assert_eq!(info.driver_name, "podman"); - assert_eq!(info.protocol_versions, [PROTOCOL_VERSION]); - - let status = ComputeDriverClient::new(serving.channel.clone()) - .get_capabilities(GetCapabilitiesRequest::default()) - .await - .unwrap_err(); - assert_eq!(status.code(), Code::Unavailable); -} - -#[tokio::test] -async fn a_failed_configure_leaves_the_driver_running_for_a_retry() { - let mut serving = serve().await; - let mut client = DriverLaunchClient::new(serving.channel.clone()); - - let unsupported = client - .configure(configure(PROTOCOL_VERSION + 1)) - .await - .unwrap_err(); - assert_eq!(unsupported.code(), Code::FailedPrecondition); - - // The fake Podman cannot describe itself, so construction fails here. - let failed = client - .configure(configure(PROTOCOL_VERSION)) - .await - .unwrap_err(); - assert_ne!(failed.code(), Code::Ok); - assert!(serving.child.try_wait().unwrap().is_none()); - - let retried = client - .configure(configure(PROTOCOL_VERSION)) - .await - .unwrap_err(); - assert_ne!(retried.code(), Code::FailedPrecondition, "{retried}"); - let still_unavailable = ComputeDriverClient::new(serving.channel.clone()) - .get_capabilities(GetCapabilitiesRequest::default()) - .await - .unwrap_err(); - assert_eq!(still_unavailable.code(), Code::Unavailable); -} - -fn report_of(output: &Output) -> openshell_driver_sdk::StartReport { - let stdout = String::from_utf8_lossy(&output.stdout); - openshell_driver_sdk::StartReport::from_output(&stdout) - .unwrap_or_else(|| panic!("no report line in: {stdout}")) -} - -const SERVE_ARGS: [&str; 5] = [ - "serve", - "--bind-socket", - "/nonexistent/driver.sock", - "--expected-peer-pid", - "1", -]; - -#[test] -fn an_invalid_table_exits_with_the_config_code_and_one_json_line() { - let output = run(&SERVE_ARGS, "no_such_key = 1"); - assert_eq!(output.status.code(), Some(78)); - let report = report_of(&output); - assert_eq!(report.kind, openshell_driver_sdk::StartKind::InvalidConfig); - assert!(report.reason.contains("no_such_key"), "{}", report.reason); -} - -#[test] -fn an_unreachable_socket_exits_as_unavailable() { - let output = run(&SERVE_ARGS, "socket_path = \"/nonexistent/podman.sock\""); - assert_eq!(output.status.code(), Some(69)); - assert_eq!( - report_of(&output).kind, - openshell_driver_sdk::StartKind::Unavailable - ); -} - -#[test] -fn preflight_accepts_a_valid_table_without_contacting_podman() { - let table = "socket_path = \"/nonexistent/podman.sock\"\nnetwork_name = \"example\"\n"; - let output = run(&["preflight"], table); - assert_eq!(output.status.code(), Some(0), "{:?}", output.stdout); - assert_eq!(run(&["preflight"], "").status.code(), Some(0)); -} - -#[test] -fn preflight_rejects_an_unknown_key() { - let output = run(&["preflight"], "no_such_key = 1"); - assert_eq!(output.status.code(), Some(78)); - assert_eq!( - report_of(&output).kind, - openshell_driver_sdk::StartKind::InvalidConfig - ); -} - -#[test] -fn the_podman_socket_variable_is_honoured_before_the_table() { - let dir = tempfile::tempdir().unwrap(); - let podman = dir.path().join("podman.sock"); - fake_podman(&podman); - let socket = dir.path().join("driver.sock"); - let mut child = command( - &[ - "serve", - "--bind-socket", - socket.to_str().unwrap(), - "--expected-peer-pid", - &std::process::id().to_string(), - ], - "socket_path = \"/nonexistent/podman.sock\"", - dir.path(), - ) - .env("OPENSHELL_PODMAN_SOCKET", &podman) - .spawn() - .unwrap(); - let deadline = Instant::now() + Duration::from_secs(30); - while !socket.exists() { - assert!( - child.try_wait().unwrap().is_none(), - "the driver should have found the socket from the environment" - ); - assert!(Instant::now() < deadline, "driver never bound its socket"); - std::thread::sleep(Duration::from_millis(50)); - } - let _ = child.kill(); - let _ = child.wait(); -} - -#[tokio::test] -async fn a_stop_signal_waits_for_the_gateway_to_release_the_driver() { - let mut serving = serve().await; - let signalled = Command::new("kill") - .args(["-TERM", &serving.child.id().to_string()]) - .status() - .unwrap(); - assert!(signalled.success()); - - // The driver defers the signal, so the gateway can still use it. - tokio::time::sleep(Duration::from_millis(500)).await; - assert!( - serving.child.try_wait().unwrap().is_none(), - "the driver stopped on SIGTERM before the gateway released it" - ); - DriverLaunchClient::new(serving.channel.clone()) - .get_launch_info(GetLaunchInfoRequest {}) - .await - .unwrap(); - - DriverLaunchClient::new(serving.channel.clone()) - .shutdown(ShutdownRequest {}) - .await - .unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - let status = loop { - if let Some(status) = serving.child.try_wait().unwrap() { - break status; - } - assert!( - Instant::now() < deadline, - "the driver did not stop after Shutdown" - ); - tokio::time::sleep(Duration::from_millis(50)).await; - }; - assert!(status.success(), "{status}"); -} diff --git a/crates/openshell-driver-vm/Cargo.toml b/crates/openshell-driver-vm/Cargo.toml deleted file mode 100644 index 7ef0c7e351..0000000000 --- a/crates/openshell-driver-vm/Cargo.toml +++ /dev/null @@ -1,140 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -[package] -name = "openshell-driver-vm" -description = "MicroVM compute driver for OpenShell" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true - -[lib] -name = "openshell_driver_vm" -path = "src/lib.rs" - -[[bin]] -name = "openshell-driver-vm" -path = "src/main.rs" -required-features = ["compute-driver"] - -[[bin]] -name = "openshell-vm-init" -path = "src/bin/openshell-vm-init.rs" - -[dependencies] -openshell-core = { path = "../openshell-core", default-features = false, features = ["clap"] } -openshell-isolation-interface = { path = "../openshell-isolation-interface" } -openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } -openshell-driver-launch = { path = "../openshell-driver-launch", optional = true } -openshell-container-runtime = { path = "../openshell-container-runtime", optional = true } -openshell-driver-sdk = { path = "../openshell-driver-sdk", optional = true } -openshell-otel = { path = "../openshell-otel", optional = true } -openshell-policy = { path = "../openshell-policy", optional = true } -openshell-vfio = { path = "../openshell-vfio", optional = true } - -base64 = { workspace = true, optional = true } -bollard = { version = "0.20", features = ["ssh"], optional = true } -tokio = { workspace = true } -tonic = { workspace = true, features = ["transport"], optional = true } -tower-http = { workspace = true, optional = true } -http = { workspace = true, optional = true } -prost = { workspace = true, optional = true } -prost-types = { workspace = true, optional = true } -futures = { workspace = true, optional = true } -tokio-stream = { workspace = true, features = ["net"], optional = true } -nix = { workspace = true, optional = true, features = ["resource"] } -clap = { workspace = true, optional = true } -tracing = { workspace = true, optional = true } -tracing-subscriber = { workspace = true, optional = true } -opentelemetry = { workspace = true, optional = true } -opentelemetry_sdk = { workspace = true, optional = true } -tracing-opentelemetry = { workspace = true, optional = true } -miette = { workspace = true, optional = true } -openshell-crypto = { workspace = true, optional = true } -url = { workspace = true, optional = true } -serde = { workspace = true } -serde_json = { workspace = true } -oci-client = { version = "0.16", optional = true } -libc = "0.2" -rustix = { workspace = true, features = ["fs"] } -libloading = { version = "0.8", optional = true } -tar = { version = "0.4", optional = true } -flate2 = { version = "1", optional = true } -sha2 = { version = "0.10", optional = true } -toml = { workspace = true, optional = true } -zstd = { version = "0.14", optional = true } - -[features] -default = ["compute-driver", "telemetry"] -## Build the standalone compute driver and its host runtime implementation. -compute-driver = [ - "dep:base64", - "dep:bollard", - "dep:clap", - "dep:flate2", - "dep:futures", - "dep:http", - "dep:libloading", - "dep:miette", - "dep:nix", - "dep:oci-client", - "dep:openshell-driver-launch", - "dep:openshell-container-runtime", - "dep:openshell-driver-sdk", - "dep:openshell-otel", - "dep:toml", - "openshell-core/otel", - "dep:openshell-policy", - "dep:openshell-vfio", - "dep:opentelemetry", - "dep:opentelemetry_sdk", - "dep:polling", - "dep:prost", - "dep:prost-types", - "dep:openshell-crypto", - "dep:sha2", - "dep:tar", - "dep:tokio-stream", - "dep:tonic", - "dep:tower-http", - "dep:tracing", - "dep:tracing-opentelemetry", - "dep:tracing-subscriber", - "dep:url", - "dep:zstd", -] -## Compile in telemetry support (forwards to openshell-core/telemetry). On by -## default; build with `--no-default-features` for a telemetry-free VM driver -## that reports telemetry disabled to the sandboxes it launches. -telemetry = ["openshell-core/telemetry"] -## Convenience alias: every default feature except `telemetry`. Build a -## telemetry-free VM driver with -## `--no-default-features --features defaults-without-telemetry` and stay -## correct as new default features are added. Cargo cannot subtract a single -## default feature, so this alias must be paired with `--no-default-features`; -## enabling it alongside `telemetry` is a compile error rather than a silent -## telemetry-on build. Kept in sync with `default` by -## `rust:verify:defaults-without-telemetry`. -defaults-without-telemetry = ["compute-driver"] - -[dev-dependencies] -hyper-util = { workspace = true } -tower = { workspace = true } -openshell-otel-test-support = { path = "../openshell-otel-test-support" } -temp-env = "0.3" -tempfile = "3" -rcgen = { workspace = true } -opentelemetry_sdk = { workspace = true, features = ["testing"] } - -# smol-rs/polling drives the BSD/macOS parent-death detection in -# procguard via kqueue's EVFILT_PROC / NOTE_EXIT filter. We could use -# it on Linux too (via epoll + pidfd) but sticking with -# nix::sys::prctl::set_pdeathsig there keeps the Linux path a single -# syscall with no helper thread. -[target.'cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "dragonfly"))'.dependencies] -polling = { version = "3.11", optional = true } - -[lints] -workspace = true diff --git a/crates/openshell-driver-vm/README.md b/crates/openshell-driver-vm/README.md deleted file mode 100644 index ff2ed322e2..0000000000 --- a/crates/openshell-driver-vm/README.md +++ /dev/null @@ -1,351 +0,0 @@ -# openshell-driver-vm - -> Status: Experimental. The VM compute driver is under active development. - -Standalone libkrun-backed [`ComputeDriver`](../../proto/compute_driver.proto) for OpenShell. The gateway spawns this binary as `serve`, passes the `[openshell.drivers.vm]` table on stdin and gateway metadata in a `Configure` call (`proto/driver_launch.proto`), and talks to it over the `openshell.compute.v1.ComputeDriver` Unix-socket surface. `openshell-supervisor` runs as a native host process, while `openshell-sandbox` runs as capability-free PID 1 inside each microVM and applies guest-local isolation over virtio-vsock. - -New VM generations initiate the control connection to host CID 2 over vsock. -Libkrun forwards that guest connection to the supervisor's protected Unix -socket; QEMU uses a host vsock listener on a per-guest port and checks the guest -CID before TLS authentication. Existing protocol roles and authorization stay -unchanged. Running legacy generations retain their original descriptors; -newly booted generations require matching embedded runtime and supervisor -binaries. - -The driver embeds libkrun, libkrunfw, the guest OCI unpacker, the portable guest sandbox, and the custom kernel runtime. Each sandbox boots from a cached immutable bootstrap ext4 root disk plus a per-sandbox writable overlay disk. When the requested sandbox image differs from the bootstrap image, the driver prepares a read-only image ext4 disk inside a bootstrap VM and mounts that unpacked rootfs as the sandbox lowerdir. - -## How it fits together - -Caller driver config is disabled by default, including upload workflows -encoded in driver JSON. GPU devices and their trusted VFIO plumbing are -temporarily exempt from approval labels; existing GPU selection validation -still applies. Private rootfs staging does not authorize arbitrary host paths. -The gateway's table, which holds the common policy, reaches the managed VM subprocess unparsed on stdin. -See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission). - -```mermaid -flowchart LR - subgraph host["Host"] - gateway["openshell-gateway
(launcher)"] - driver["openshell-driver-vm
libkrun"] - supervisor["openshell-supervisor
host policy supervisor"] - gateway <-->|"gRPC over a
private UDS"| driver - supervisor <-->|"authenticated gRPC
policy + relay"| gateway - end - - subgraph guest["Per-sandbox microVM"] - init["/srv/openshell-vm-
sandbox-init.sh"] - sandbox["openshell-sandbox
capability-free guest PID 1"] - workload["sandbox workload"] - init --> sandbox --> workload - end - - driver -->|"CreateSandbox
boots via libkrun"| guest - supervisor <-->|"mutual TLS RFC 0012
over virtio-vsock"| sandbox - - client["openshell-cli"] -->|"connect / exec / forward"| gateway - client -->|"CreateSandbox / Watch"| gateway -``` - -The supervisor owns gateway credentials, admitted policy, provider resolution, middleware, the network proxy, and relay registration. The sandbox receives no gateway JWT. Each VM generation receives distinct sandbox and supervisor channel keys; the guest consumes and unlinks its private bootstrap files before launching the workload. - -VM-specific RFC 0012 code under `src/isolation/` only chooses the vsock transport and binds immutable VM generation and image claims into the protected guest config and host descriptor. Lifecycle, authentication, process control, binary identity, forwarding, and streaming come from `openshell-isolation-interface` and `openshell-sandbox`. - -## Quick start (recommended) - -```shell -mise run gateway:vm -``` - -First run takes a few minutes while `mise run vm:setup` stages libkrun/libkrunfw/umoci and `mise run vm:supervisor` builds the portable Linux guest sandbox plus its small static guest-init helper. The development task also builds the native host supervisor. Subsequent runs are cached. - -By default `mise run gateway:vm`: - -- Listens on plaintext HTTP at `127.0.0.1:18081`. -- Uses `nvcr.io/nvidia/base/ubuntu:24.04` as the sandbox and bootstrap image. -- Configures the gateway installation name as `vm-dev` and registers the same - name with the CLI by writing - `~/.config/openshell/gateways/vm-dev/metadata.json`. It does not modify the - workspace `.env`. -- Persists the gateway SQLite DB under `.cache/gateway-vm/gateway.db`. -- Places the VM driver state (per-sandbox `overlay.ext4`, image cache, and the private `run/` socket directories) under `/tmp/openshell-vm-driver-$USER-vm-dev/` so the AF_UNIX socket path stays under macOS `SUN_LEN`. -- Writes `.cache/gateway-vm/gateway.toml` with `[openshell.gateway].driver_dir = "$PWD/target/debug"` so the freshly built `openshell-driver-vm` is used instead of an older installed copy from `~/.local/libexec/openshell`, `/usr/libexec/openshell`, or `/usr/local/libexec`. -- Enables OTLP trace export, OCSF log export, and the agent trace relay only when `OPENSHELL_DEV_OTLP_ENDPOINT` names a collector, for example `http://127.0.0.1:4317`. Otherwise, it omits the OTLP configuration. - -For GPU passthrough (VFIO), pass `-- --gpu` and run with root privileges: - -```shell -sudo -E env "PATH=$PATH" mise run gateway:vm -- --gpu -``` - -GPU passthrough uses VFIO and requires host support for IOMMU, root privileges -for bind/unbind operations, and a compatible sandbox image. The public GPU -overview lives in the repository `README.md`. - -Point the CLI at the gateway with one of: - -```shell -openshell --gateway vm-dev status -openshell gateway select vm-dev # then plain `openshell ` -``` - -Override defaults via environment: - -```shell -# custom port (fails fast if in use) -OPENSHELL_SERVER_PORT=18091 mise run gateway:vm - -# custom gateway installation/CLI name + namespace -OPENSHELL_VM_GATEWAY_NAME=vm-feature-a \ -OPENSHELL_SANDBOX_NAMESPACE=vm-feature-a \ -mise run gateway:vm - -# custom sandbox image -OPENSHELL_SANDBOX_IMAGE=ghcr.io/example/sandbox:latest mise run gateway:vm - -# custom bootstrap image for the VM runtime used to prepare/boot target images -OPENSHELL_VM_BOOTSTRAP_IMAGE=ghcr.io/example/bootstrap:latest mise run gateway:vm -``` - -Teardown: - -```shell -rm -rf /tmp/openshell-vm-driver-$USER-vm-dev .cache/gateway-vm -rm -rf "${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/vm-dev" -``` - -## Manual equivalent - -If you want to drive the launch yourself instead of using `mise run gateway:vm` (i.e. `tasks/scripts/gateway-vm.sh`): - -```shell -# 1. Stage runtime artifacts + guest sandbox into target/vm-runtime-compressed/ -mise run vm:setup -mise run vm:supervisor # builds the Linux guest sandbox and static guest-init helper - -# 2. Build gateway, native host supervisor, and driver -OPENSHELL_VM_RUNTIME_COMPRESSED_DIR=$PWD/target/vm-runtime-compressed \ - cargo build -p openshell-gateway -p openshell-supervisor -p openshell-driver-vm - -# 3. macOS only: codesign the driver for Hypervisor.framework -codesign \ - --entitlements crates/openshell-driver-vm/entitlements.plist \ - --force -s - target/debug/openshell-driver-vm - -# 4. Start the gateway with the VM driver -mkdir -p /tmp/openshell-vm-driver-$USER-vm-dev .cache/gateway-vm -cat > .cache/gateway-vm/gateway.toml <` is valid. Legacy guest aliases are normalized to host loopback. This endpoint is never sent into the VM. | -| `state_dir` | `target/openshell-vm-driver` | Per-sandbox overlay disks, console logs, image cache, and the private `run//driver.sock` UDS, one directory per launch. Relative paths are resolved to absolute paths at driver startup. | -| `driver_dir` | unset | Deprecated in this table: set `driver_dir` in `[openshell.gateway]`. The directory is searched before the standard locations. | -| `default_image` | OpenShell base image | Sandbox image used when a create request omits one. | -| `bootstrap_image` | unset | VM runtime image used as the immutable bootstrap root disk. Falls back only to the operator-configured `default_image`; the driver refuses to start when both are empty. | -| `vcpus` | `2` | vCPUs per sandbox. | -| `mem_mib` | `2048` | Memory per sandbox, in MiB. | -| `overlay_disk_mib` | `4096` | Sparse writable overlay disk size per sandbox, in MiB. | -| `krun_log_level` | `1` | libkrun verbosity (0-5). | -| `guest_tls_ca` | unset | Historical key name for the host supervisor's gateway CA certificate. Required when `grpc_endpoint` uses `https://`; never copied into the guest. | -| `https_proxy` | unset | Corporate forward proxy (`http://host:port` or `https://host:port`) that host control chains policy-approved TLS CONNECT egress through. Host-loopback proxy URLs work because control runs on the gateway host. | -| `no_proxy` | unset | Comma-separated bypass list for the corporate proxy only. OpenShell policy evaluation still applies. | -| `proxy_auth_file` | unset | Gateway-host path to a validated `user:pass` credential file. Staged root-only into the per-sandbox overlay and removed with the sandbox; credentials never enter logs or process arguments. | -| `proxy_auth_allow_insecure` | unset | Required with `proxy_auth_file` against an `http://` proxy: acknowledges that Basic auth is cleartext on the connection to the proxy. | -| `proxy_connect_by_hostname` | unset | Send hostnames rather than validated IPs in CONNECT. Last resort for proxies whose ACLs reject IP CONNECT targets. | -| `proxy_ca_bundle` | unset | Gateway-host PEM CA bundle trusted for the corporate proxy and TLS-intercepted server certificates. The driver validates it and stages it at a fixed non-secret guest path in the protected overlay. Requires `https_proxy`. | -| `provider_spiffe_workload_api_tcp_endpoint` | unset | Explicit guest-reachable `tcp:IP:port` SPIFFE Workload API listener for provider token exchange. It requires `provider_spiffe_allow_guest_tcp = true`; a host UNIX socket is never silently exposed to a VM guest. | -| `enable_bind_mounts` | `false` | Allow per-sandbox `driver_config.vm.mounts` host directory shares (libkrun virtiofs only). The driver writes a `tag\ttarget\tmode` manifest to `/.openshell/mounts.manifest` in the overlay, and guest init mounts each share after `/sandbox` ownership fixups. Rejected while resource admission is enabled. | - -The proxy settings are operator-owned and deployment-level: they are not accepted through `template.driver_config.vm`, and the driver passes them only to native host control. Every present-but-invalid value is fatal at gateway or sandbox startup rather than degrading to a direct dial. - -See [`openshell-gateway --help`](../openshell-server/src/cli.rs) for the gateway process flag surface. - -## Verifying the gateway - -The gateway is auto-registered by `mise run gateway:vm`. In another terminal: - -```shell -./scripts/bin/openshell status -./scripts/bin/openshell sandbox create --name demo --from -./scripts/bin/openshell sandbox connect demo -``` - -First sandbox takes 10–30 seconds to boot (image fetch/prepare/cache + libkrun + guest init). If `--from` is omitted, the VM driver uses the gateway's configured default sandbox image. Without either `--from` or `--sandbox-image`, VM sandbox creation fails. Subsequent creates reuse the prepared image cache and create only a sparse per-sandbox `overlay.ext4` before boot. - -`CreateSandbox` accepts the sandbox quickly and continues VM provisioning in the -background. The driver publishes platform events for image resolution, cache -hits/misses, layer pulls, rootfs preparation, overlay creation, and VM launcher -startup so the CLI can show progress through the existing sandbox watch stream. - -The VM driver keeps two image caches. The bootstrap cache is a controlled -`rootfs.ext4` used to boot the guest init and OpenShell supervisor. The prepared -image cache is used when the requested sandbox image differs from the bootstrap -image: the host downloads registry layers into a valid OCI layout, attaches that -payload to a temporary bootstrap VM, and guest init runs `umoci raw unpack` onto -Linux-owned ext4 storage. The resulting disk is cached under -`/images//rootfs.ext4` and attached read-only to later -sandboxes. Local Docker images are still exported as rootfs tar archives and -prepared inside the bootstrap VM. The driver checks that a prepared disk -contains the unpacked rootfs before caching it; on failure it caches nothing -and reports the image-prep console tail. Set `OPENSHELL_VM_IMAGE_PULL_CONCURRENCY` to -tune registry layer download parallelism (default `4`, maximum `16`). -Registry pulls in both caches use the resolved digest as an immutable reference. -The driver verifies the downloaded manifest against that digest before downloading -layers. For multi-platform images, it verifies the index and then the selected -platform manifest. Digest-pinned requests retain the caller's digest. -Cache keys hash source identities to keep cache and staging filenames bounded. -Bootstrap cache layout v6 and prepared-image layout v4 rebuild older entries on -first use; older cache files remain on disk but are not reused for registry images. -Both caches are scoped by source image identity and OpenShell version, so an -OpenShell upgrade builds a fresh guest rootfs instead of reusing one with an old -embedded supervisor. Host-side bootstrap layer assembly preserves relative -symlinks that remain inside the rootfs, but rejects absolute or escaping -cross-layer symlink traversal before applying later files or whiteouts. The -layer applier performs rootfs mutations relative to opened directory handles -and creates destination files without following symlinks. -The requested sandbox image is never selected as the bootstrap image. Operators -must configure either `bootstrap_image` or `default_image`; when both are empty, -the driver fails during startup. - -Image and writable-overlay preparation run in owned worker processes. Stopping or deleting a sandbox cancels its worker and formatter processes, waits for them to exit, then removes the attempt's temporary files under `/images/preparations/`. New overlays, including retries after an interrupted first start, are built there and renamed into sandbox state only after completion. A file lock inherited by the worker's children keeps cleanup from deleting files that a process still owns. If cleanup cannot establish that the processes have stopped, the operation returns an error and retains both temporary files and sandbox state. - -At startup, the driver reclaims inactive attempts in this directory. It preserves active attempts, committed image caches, and unmarked staging from older releases. Concurrent preparations serialize image-cache publication; an interrupted attempt cannot publish a partial disk over an existing cache entry. Gateway upload slots for `rootfs_tar_path` keep their existing, separate lifecycle. - -Each sandbox gets its own sparse writable -`/sandboxes//overlay.ext4`. Guest init mounts overlayfs as `/` -with the prepared image rootfs as lowerdir when present, otherwise the bootstrap -rootfs is used directly. Writes to `/sandbox` and other mutable paths land in -the overlay while cached image disks remain unchanged. The overlay disk must be -large enough to hold the compressed payload, unpacked rootfs, and sandbox writes -during the first prepare. - -The driver also writes the accepted `DriverSandbox` launch request to -`/sandboxes//sandbox.pb`. If the gateway restarts, it starts a -new VM driver process. During graceful shutdown, the gateway first sends the -shared `StopSandbox` request for each persisted running-intent sandbox, which -stops its launcher while retaining the launch request and `overlay.ext4`. -After driver initialization, the gateway sends the idempotent `StartSandbox` -request for that retained intent. Explicitly stopped sandboxes remain excluded. - -Stop writes a marker in the sandbox state directory before terminating -the launcher and releasing host GPU and network allocations. It retains -`sandbox.pb`, `overlay.ext4`, and lifecycle-extension state. Startup registers -marked sandboxes without launching compute. Start removes the marker and uses -the normal persisted restore path with the existing overlay. Delete removes the -entire sandbox state directory, including a stop marker and overlay. - -The host control writes and syncs a terminal tombstone when the canonical main -process exits, before it reports completion and while it retains the boundary -for exec and forwarding. Driver startup reports that sandbox as terminal -instead of relaunching the VM, even when the process exited successfully. - -The driver embeds a platform-native host supervisor and extracts it into -`/host-runtime`. It accepts a cached binary only when its SHA-256 -content matches the embedded supervisor and it remains an executable regular -file. Replacement is written and synced under a temporary name, then atomically -renamed into place. `OPENSHELL_VM_SUPERVISOR_BIN` remains an explicit -development override. - -## Logs and debugging - -Raise log verbosity for both processes: - -```shell -RUST_LOG=openshell_server=debug,openshell_driver_vm=debug \ - mise run gateway:vm -``` - -The VM guest's serial console is appended to `//console.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `/run//driver.sock`; each launch gets its own directory under `run/`, created with owner-only permissions and removed with the driver's handle. On clean shutdown, the gateway finishes its work through the driver, releases it with the launch protocol's `Shutdown` call, and waits up to ten seconds for it to flush telemetry and exit. It then falls back to `SIGTERM`, waits five seconds, force-kills the driver if necessary, and removes the socket. A stop signal that reaches the driver from elsewhere, such as a service manager signalling every process of the gateway's unit, is deferred until the gateway releases the driver, the gateway exits, or 30 seconds pass. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development. -The VM serial console is appended to `/sandboxes//rootfs-console.log`. Host-supervisor stdout and stderr are written beside it as `supervisor.log` and `supervisor.err.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `/run//driver.sock`; each launch gets its own directory under `run/`, created with owner-only permissions, and the gateway removes it on clean shutdown via `ManagedDriverProcess::drop`. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development. - -## Network isolation - -VM sandboxes boot without a virtual NIC. The guest exposes only the protected -vsock channel used by `openshell-sandbox`; `openshell-supervisor` performs DNS, -policy evaluation, and external networking on the host. The driver does not -create TAP devices or install nftables/iptables rules. - -## Prerequisites - -- macOS on Apple Silicon, or Linux on aarch64/x86_64 with KVM -- Rust toolchain -- e2fsprogs (`mke2fs` or `mkfs.ext4`, plus `debugfs`) for root and overlay disk image creation and QEMU environment injection -- Guest-sandbox cross-compile toolchain (needed on macOS, and on Linux when host arch differs from the guest): - - Matching static guest target: `rustup target add aarch64-unknown-linux-musl` (or `x86_64-unknown-linux-musl` for an amd64 guest) - - `cargo install --locked cargo-zigbuild` and `brew install zig` (or distro equivalent). `vm:supervisor` cross-compiles the Linux guest `openshell-sandbox` and its matching `openshell-supervisor`. -- [mise](https://mise.jdx.dev/) task runner -- Docker or Podman socket on the local CLI/gateway host when building an image - before `openshell sandbox create --from `; the VM driver exports the - image via the local container engine. - Docker is tried first; if unavailable, the driver falls back to the Podman - socket. On Linux, enable the Podman API socket with - `systemctl --user start podman.socket` -- `gh` CLI (used by `mise run vm:setup` to download pre-built runtime artifacts) - -## Releases - -`openshell-driver-vm` is published as a normal OpenShell release artifact: - -- development builds: the rolling `dev` release -- tagged builds: the corresponding `v*` release -- runtime tarballs: the rolling `vm-runtime` release, rebuilt on demand by - `release-vm-kernel.yml` - -On Debian-family Linux amd64 and arm64 systems, `install.sh` installs the -Debian package from the selected `OPENSHELL_VERSION` release tag. That package -includes `openshell-gateway` and `openshell-driver-vm`, but leaves -`OPENSHELL_COMPUTE_DRIVER` unset so the gateway uses its normal runtime -auto-detection. Set `OPENSHELL_COMPUTE_DRIVER=vm` to force the VM driver. - -On RPM-family Linux x86_64 and aarch64 systems, `install.sh` installs the -`openshell` and `openshell-gateway` RPM packages from the selected release tag. -The RPM gateway package is configured for the Podman driver. - -On Apple Silicon macOS, `install.sh` stages the generated `openshell.rb` -formula from the selected release in the `nvidia/openshell` Homebrew tap. -Homebrew installs `openshell`, `openshell-gateway`, and the self-contained -`openshell-driver-vm` with its embedded native supervisor. It ad-hoc signs the -driver with the Hypervisor entitlement in `post_install` and owns the `brew -services` gateway lifecycle. The service also leaves `OPENSHELL_DRIVERS` unset -so driver choice remains automatic unless the user explicitly overrides it. - -## TODOs - -- macOS local builds are codesigned by `tasks/scripts/gateway-vm.sh`; the generated Homebrew formula signs the release tarball driver for local installs. - -## Launched mode - -```text -openshell-driver-vm serve --bind-socket --expected-peer-pid --log-level < table.toml -openshell-driver-vm preflight < table.toml -``` - -`settings_from_table` in `src/settings.rs` is the only place the table is parsed and validated. `serve` exits 78 on an invalid table. A setting the table leaves unset still falls back to the driver's environment variable (for example `OPENSHELL_VM_UPSTREAM_PROXY`), as it did when the gateway passed flags. A `false` or an empty list in the table counts as unset for `enable_bind_mounts`, `provider_spiffe_allow_guest_tcp` and `nat64_prefixes`, so the environment can still enable them; an environment `false` for the two proxy acknowledgements means unset. The table rejects `guest_tls_ca`, `gateway_port` and the admission keys, which the gateway supplies in `Configure`. The driver binds its socket and answers `GetLaunchInfo` at once, but `ComputeDriver` calls return `UNAVAILABLE` and no VM state is created until `Configure` succeeds. `preflight` validates the table and exits. diff --git a/crates/openshell-driver-vm/build.rs b/crates/openshell-driver-vm/build.rs deleted file mode 100644 index 92525927d8..0000000000 --- a/crates/openshell-driver-vm/build.rs +++ /dev/null @@ -1,153 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Build script for openshell-driver-vm. -//! -//! This crate embeds the sandbox, host supervisor, and minimal libkrun runtime -//! artifacts it needs to boot VMs without a separate VM runtime binary. - -use std::path::{Path, PathBuf}; -use std::{env, fs}; - -fn main() { - if env::var_os("CARGO_FEATURE_COMPUTE_DRIVER").is_none() { - return; - } - - println!("cargo:rerun-if-env-changed=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR"); - - if let Ok(dir) = env::var("OPENSHELL_VM_RUNTIME_COMPRESSED_DIR") { - println!("cargo:rerun-if-changed={dir}"); - for name in &[ - "libkrun.so.zst", - "libkrunfw.so.5.zst", - "libkrun.dylib.zst", - "libkrunfw.5.dylib.zst", - "openshell-sandbox.zst", - "openshell-supervisor.zst", - "openshell-vm-init.zst", - "umoci.zst", - ] { - println!("cargo:rerun-if-changed={dir}/{name}"); - } - } - - let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")); - let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); - let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); - - let (libkrun_name, libkrunfw_name) = match target_os.as_str() { - "macos" => ("libkrun.dylib", "libkrunfw.5.dylib"), - "linux" => ("libkrun.so", "libkrunfw.so.5"), - _ => { - println!("cargo:warning=VM runtime not available for {target_os}-{target_arch}"); - generate_stub_resources( - &out_dir, - &[ - "libkrun", - "libkrunfw", - "openshell-sandbox.zst", - "openshell-supervisor.zst", - "openshell-vm-init.zst", - "umoci.zst", - ], - ); - return; - } - }; - - let compressed_dir = if let Ok(dir) = env::var("OPENSHELL_VM_RUNTIME_COMPRESSED_DIR") { - PathBuf::from(dir) - } else { - println!("cargo:warning=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR not set"); - println!("cargo:warning=Run: mise run vm:setup && mise run vm:supervisor"); - generate_stub_resources( - &out_dir, - &[ - &format!("{libkrun_name}.zst"), - &format!("{libkrunfw_name}.zst"), - "openshell-sandbox.zst", - "openshell-supervisor.zst", - "openshell-vm-init.zst", - "umoci.zst", - ], - ); - return; - }; - - assert!( - compressed_dir.is_dir(), - "Compressed runtime dir not found: {}. Run: mise run vm:setup && mise run vm:supervisor", - compressed_dir.display() - ); - - let files = [ - (format!("{libkrun_name}.zst"), format!("{libkrun_name}.zst")), - ( - format!("{libkrunfw_name}.zst"), - format!("{libkrunfw_name}.zst"), - ), - ( - "openshell-sandbox.zst".to_string(), - "openshell-sandbox.zst".to_string(), - ), - ( - "openshell-supervisor.zst".to_string(), - "openshell-supervisor.zst".to_string(), - ), - ( - "openshell-vm-init.zst".to_string(), - "openshell-vm-init.zst".to_string(), - ), - ("umoci.zst".to_string(), "umoci.zst".to_string()), - ]; - - for (src_name, _) in &files { - let src_path = compressed_dir.join(src_name); - let metadata = fs::metadata(&src_path).unwrap_or_else(|e| { - panic!( - "Required compressed artifact unavailable: {}: {e}", - src_path.display() - ) - }); - assert!( - metadata.is_file(), - "Required compressed artifact is not a file: {}", - src_path.display() - ); - assert!( - metadata.len() != 0, - "Required compressed artifact is empty: {}", - src_path.display() - ); - } - - for (src_name, dst_name) in &files { - let src_path = compressed_dir.join(src_name); - let dst_path = out_dir.join(dst_name); - - if dst_path.exists() { - let _ = fs::remove_file(&dst_path); - } - fs::copy(&src_path, &dst_path).unwrap_or_else(|e| { - panic!( - "Failed to copy {} to {}: {}", - src_path.display(), - dst_path.display(), - e - ) - }); - let size = fs::metadata(&dst_path).map_or(0, |m| m.len()); - println!("cargo:warning=Embedded {src_name}: {size} bytes"); - } -} - -fn generate_stub_resources(out_dir: &Path, names: &[&str]) { - for name in names { - let path = out_dir.join(name); - if !path.exists() { - fs::write(&path, b"") - .unwrap_or_else(|e| panic!("Failed to write stub {}: {}", path.display(), e)); - } - } -} diff --git a/crates/openshell-driver-vm/entitlements.plist b/crates/openshell-driver-vm/entitlements.plist deleted file mode 100644 index 154f3308ef..0000000000 --- a/crates/openshell-driver-vm/entitlements.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - com.apple.security.hypervisor - - - diff --git a/crates/openshell-driver-vm/runtime/README.md b/crates/openshell-driver-vm/runtime/README.md deleted file mode 100644 index de17519c6d..0000000000 --- a/crates/openshell-driver-vm/runtime/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# VM Driver Runtime - -> Status: Experimental. VM support is under active development and may change. - -This directory owns the pinned runtime inputs for `openshell-driver-vm`: - -```text -runtime/ - pins.env - kernel/ - openshell.kconfig -``` - -`openshell-driver-vm` embeds libkrun, libkrunfw, umoci for guest-side OCI image -unpacking, and the portable capability-free `openshell-sandbox` role. -VMs do not attach a guest NIC. The boundary carries control, mediated network, -and DNS streams over the authenticated vsock channel. - -## Why - -The stock `libkrunfw` kernel does not include every cgroup, seccomp, and -Landlock feature the sandbox needs inside each microVM. -`kernel/openshell.kconfig` extends the libkrunfw kernel so VM sandboxes retain -guest-local process, network-syscall, and filesystem enforcement while the -supervisor runs on the host. - -## Build Scripts - -| Script | Platform | Purpose | -|---|---|---| -| `tasks/scripts/vm/build-libkrun.sh` | Linux | Builds libkrunfw and libkrun from source with the custom kernel config | -| `tasks/scripts/vm/build-libkrun-macos.sh` | macOS | Builds portable libkrunfw and libkrun from a prebuilt `kernel.c` | -| `tasks/scripts/vm/package-vm-runtime.sh` | Any | Packages `vm-runtime-.tar.zst` with libraries, umoci, and provenance | -| `tasks/scripts/vm/download-kernel-runtime.sh` | Any | Downloads runtime tarballs from the `vm-runtime` release and stages compressed files | - -## Local Flow - -```shell -# Download the current pre-built runtime and stage compressed artifacts -mise run vm:setup - -# Build the portable Linux guest sandbox and static guest-init helper -mise run vm:supervisor - -# Build the gateway, native host supervisor, and VM driver -OPENSHELL_VM_RUNTIME_COMPRESSED_DIR=$PWD/target/vm-runtime-compressed \ - cargo build -p openshell-gateway -p openshell-supervisor -p openshell-driver-vm -``` - -Use `FROM_SOURCE=1 mise run vm:setup` to build the runtime from source instead -of downloading `vm-runtime-.tar.zst`. - -## CI Ownership - -`release-vm-kernel.yml` is the on-demand producer for: - -- `vm-runtime-linux-aarch64.tar.zst` -- `vm-runtime-linux-x86_64.tar.zst` -- `vm-runtime-darwin-aarch64.tar.zst` - -Those artifacts stay on the rolling `vm-runtime` release. Normal `dev` and `v*` -release workflows download them, embed them into `openshell-driver-vm`, and -publish the driver binary next to `openshell-gateway`. - -## Provenance - -`package-vm-runtime.sh` writes `provenance.json` into each runtime tarball with -the platform, libkrunfw commit, kernel version, final kernel config SHA-256, -umoci version, GitHub SHA, and build time. The driver logs this metadata when it -extracts and loads a runtime bundle. - -The release workflow also publishes GitHub artifact attestations for each -runtime tarball. Verify a downloaded runtime with: - -```bash -gh attestation verify vm-runtime-linux-x86_64.tar.zst -R ai-openshell/openshell -``` - -Runtimes built before the repository moved from `NVIDIA/OpenShell` are attested -under the NVIDIA account, and GitHub no longer finds those attestations through -the repository. Verify them by the old owner: - -```bash -gh attestation verify vm-runtime-linux-x86_64.tar.zst --owner NVIDIA --signer-repo NVIDIA/OpenShell -``` diff --git a/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig b/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig deleted file mode 100644 index c3573759f1..0000000000 --- a/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig +++ /dev/null @@ -1,51 +0,0 @@ -# Custom kernel config fragment for libkrunfw (OpenShell VM) -# -# This fragment is applied on top of libkrunfw's base kernel config. VM -# sandboxes have no virtual NIC; the base loopback, TCP/UDP, Unix-socket, -# route-netlink, and vsock support is enough for the capability-free sandbox. -# -# Apply with: scripts/merge-kconfig.sh -# -# See also: check-vm-capabilities.sh for runtime verification. - -# Root disk transport and filesystem. -CONFIG_BLOCK=y -CONFIG_BLK_DEV=y -CONFIG_VIRTIO_BLK=y -CONFIG_EXT4_FS=y -CONFIG_EXT4_USE_FOR_EXT2=y - -# Host-directory sharing via virtiofs (used for VM driver bind mounts). -# The pinned libkrunfw base config already enables both; they are listed here -# because bind mounts depend on them. -CONFIG_FUSE_FS=y -CONFIG_VIRTIO_FS=y - -# Cgroups used for process supervision and resource limits. -CONFIG_CGROUPS=y -CONFIG_CGROUP_DEVICE=y -CONFIG_CGROUP_CPUACCT=y -CONFIG_CGROUP_PIDS=y -CONFIG_MEMCG=y - -# Disable the kernel headers archive to avoid cpio issues in CI. -# CONFIG_IKHEADERS is not set - -# POSIX message queues used by OCI workloads. -CONFIG_POSIX_MQUEUE=y -CONFIG_POSIX_MQUEUE_SYSCTL=y - -# Capability-free sandbox enforcement. -CONFIG_SECURITY=y -CONFIG_SECURITY_LANDLOCK=y -CONFIG_LSM="landlock,lockdown,yama,loadpin,safesetid,ipe,bpf" -CONFIG_SECCOMP=y -CONFIG_SECCOMP_FILTER=y - -# Kernel memory hardening. Keep init-on-free disabled because its runtime cost -# is too high for sandbox workloads. -CONFIG_HARDENED_USERCOPY=y -CONFIG_INIT_STACK_ALL_ZERO=y -CONFIG_INIT_ON_ALLOC_DEFAULT_ON=y -# CONFIG_INIT_ON_FREE_DEFAULT_ON is not set -CONFIG_SLAB_FREELIST_RANDOM=y diff --git a/crates/openshell-driver-vm/runtime/pins.env b/crates/openshell-driver-vm/runtime/pins.env deleted file mode 100644 index 38babc48f5..0000000000 --- a/crates/openshell-driver-vm/runtime/pins.env +++ /dev/null @@ -1,33 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Pinned dependency versions for the openshell-driver-vm runtime. -# -# This file is sourced by VM runtime packaging scripts. It centralises version -# pins so that builds are reproducible and auditable. -# -# Environment variables override these defaults — CI and local dev workflows -# can still set the runtime dependency versions below. -# -# To update a dependency: -# 1. Change the version/digest below. -# 2. Run the relevant build script to verify. -# 3. Commit pins.env alongside any script changes. - -# SERVER_IMAGE is intentionally NOT pinned here — it changes frequently -# during local development. Override via IMAGE_REPO_BASE and IMAGE_TAG -# environment variables (defaults: openshell/gateway:dev). - -# ── umoci (guest OCI unpacker) ─────────────────────────────────────── -# Repo: https://github.com/opencontainers/umoci -UMOCI_VERSION="${UMOCI_VERSION:-v0.6.0}" - -# ── libkrunfw upstream (commit-pinned) ──────────────────────────────── -# Repo: https://github.com/libkrun/libkrunfw -# Pinned: v5.6.2 (Linux 6.12.109, 2026-09-25) -LIBKRUNFW_REF="${LIBKRUNFW_REF:-f14ac64ca8a04c6c9d76cac1c61ee050809c88c9}" - -# ── libkrun upstream (commit-pinned) ───────────────────────────────── -# Repo: https://github.com/libkrun/libkrun -# Pinned: v1.19.6 (2026-09-29) -LIBKRUN_REF="${LIBKRUN_REF:-227b2de6ed323fe180e02f871c5f325a90c13cc2}" diff --git a/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh b/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh deleted file mode 100644 index 37950675b0..0000000000 --- a/crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh +++ /dev/null @@ -1,751 +0,0 @@ -#!/bin/bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Minimal init for sandbox VMs. Runs as PID 1 inside the guest, mounts the -# essential filesystems, optionally loads NVIDIA GPU drivers, then execs the -# portable VM sandbox. Workload networking crosses the authenticated -# boundary channel; the VM does not receive a network interface. - -set -euo pipefail - -# libkrun consumes this driver-owned switch before exec'ing this script as -# PID 1. Do not leak the runtime control into the supervisor or workloads. -unset KRUN_INIT_PID1 - -BOOT_START=$(date +%s%3N 2>/dev/null || date +%s) -SANDBOX_OWNER_NORMALIZED_MARKER="/opt/openshell/.sandbox-owner-normalized" - -GPU_ENABLED="${GPU_ENABLED:-false}" - -ts() { - local now - now=$(date +%s%3N 2>/dev/null || date +%s) - local elapsed=$((now - BOOT_START)) - printf "[%d.%03ds] %s\n" $((elapsed / 1000)) $((elapsed % 1000)) "$*" -} - -mount_initial_fs() { - mount -t proc proc /proc 2>/dev/null || true - mount -t sysfs sysfs /sys 2>/dev/null || true - mount -t tmpfs tmpfs /tmp 2>/dev/null || true - mount -t tmpfs tmpfs /run 2>/dev/null || true - mount -t devtmpfs devtmpfs /dev 2>/dev/null || true -} - -bind_mount_into_newroot() { - local source="$1" - local target="/newroot${source}" - - mkdir -p "$target" 2>/dev/null || true - mount --rbind "$source" "$target" 2>/dev/null \ - || mount --bind "$source" "$target" 2>/dev/null \ - || true -} - -root_path() { - local path="$1" - printf '%s%s\n' "${ROOT_PREFIX:-}" "$path" -} - -sandbox_owner() { - sandbox_owner_from_passwd "$(root_path /etc/passwd)" -} - -sandbox_owner_for_root() { - local root="$1" - sandbox_owner_from_passwd "$root/etc/passwd" -} - -sandbox_owner_from_passwd() { - local passwd_path name uid gid rest - passwd_path="$1" - if [ -f "$passwd_path" ]; then - while IFS=: read -r name _ uid gid rest; do - _="${rest:-}" - if [ "$name" = "sandbox" ] \ - && [[ "$uid" =~ ^[0-9]+$ ]] \ - && [[ "$gid" =~ ^[0-9]+$ ]]; then - printf '%s:%s\n' "$uid" "$gid" - return - fi - done < "$passwd_path" - fi - - # New images use the conventional sandbox UID. Existing images retain the - # sandbox account read above, including the legacy 10001:10001 identity. - printf '1000:1000\n' -} - -source_overlay_env_if_present() { - local env_file="/overlay/upper/srv/openshell-env.sh" - if [ -f "$env_file" ]; then - # shellcheck source=/dev/null - source "$env_file" - fi -} - -ensure_target_runtime() { - local image_root="$1" - local sandbox_uid="${OPENSHELL_VM_SANDBOX_UID:-}" - local sandbox_gid="${OPENSHELL_VM_SANDBOX_GID:-}" - local replace_account=0 - - # An omitted identity means the image owns its sandbox account contract. - # Fall back to 1000 only when the image has no sandbox account at all. - if [ -n "$sandbox_uid" ] || [ -n "$sandbox_gid" ]; then - sandbox_uid="${sandbox_uid:-1000}" - sandbox_gid="${sandbox_gid:-$sandbox_uid}" - replace_account=1 - elif ! grep -q '^sandbox:' "$image_root/etc/passwd" 2>/dev/null; then - sandbox_uid=1000 - sandbox_gid=1000 - replace_account=1 - fi - - mkdir -p \ - "$image_root/srv" \ - "$image_root/opt/openshell/bin" \ - "$image_root/sandbox" \ - "$image_root/etc" - - cp /srv/openshell-vm-sandbox-init.sh "$image_root/srv/openshell-vm-sandbox-init.sh" - chmod 0755 "$image_root/srv/openshell-vm-sandbox-init.sh" - - if [ -x /opt/openshell/bin/openshell-sandbox ]; then - cp /opt/openshell/bin/openshell-sandbox "$image_root/opt/openshell/bin/openshell-sandbox" - chmod 0755 "$image_root/opt/openshell/bin/openshell-sandbox" - fi - if [ -x /opt/openshell/bin/openshell-vm-init ]; then - cp /opt/openshell/bin/openshell-vm-init "$image_root/opt/openshell/bin/openshell-vm-init" - chmod 0755 "$image_root/opt/openshell/bin/openshell-vm-init" - fi - - touch "$image_root/etc/passwd" "$image_root/etc/group" "$image_root/etc/shadow" "$image_root/etc/gshadow" - if [ "$replace_account" -eq 1 ]; then - if grep -q '^sandbox:' "$image_root/etc/group" 2>/dev/null; then - sed -i "s|^sandbox:.*|sandbox:x:${sandbox_gid}:|" "$image_root/etc/group" - else - printf 'sandbox:x:%s:\n' "$sandbox_gid" >> "$image_root/etc/group" - fi - if ! grep -q '^sandbox:' "$image_root/etc/gshadow" 2>/dev/null; then - printf 'sandbox:!::\n' >> "$image_root/etc/gshadow" - fi - if grep -q '^sandbox:' "$image_root/etc/passwd" 2>/dev/null; then - sed -i "s|^sandbox:.*|sandbox:x:${sandbox_uid}:${sandbox_gid}:OpenShell Sandbox:/sandbox:/bin/sh|" "$image_root/etc/passwd" - else - printf 'sandbox:x:%s:%s:OpenShell Sandbox:/sandbox:/bin/sh\n' "$sandbox_uid" "$sandbox_gid" >> "$image_root/etc/passwd" - fi - if ! grep -q '^sandbox:' "$image_root/etc/shadow" 2>/dev/null; then - printf 'sandbox:!:20123:0:99999:7:::\n' >> "$image_root/etc/shadow" - fi - fi - local owner - owner="$(sandbox_owner_for_root "$image_root")" - if ! chown -R "$owner" "$image_root/sandbox" 2>/dev/null; then - ts "FATAL: failed to apply sandbox image ownership (${owner})" - exit 1 - fi - chmod 0755 "$image_root/sandbox" -} - -prepare_guest_image_rootfs() { - local payload_dir="/overlay/config/openshell-image" - local image_root="/overlay/image-rootfs" - local partial_root="/overlay/image-rootfs.partial" - local source - - [ -d "$payload_dir" ] || return 0 - - source="$(cat "$payload_dir/source" 2>/dev/null || true)" - ts "preparing sandbox image rootfs in guest (${source:-unknown})" - - rm -rf "$image_root" "$partial_root" - - # Build the rootfs under $partial_root and rename it into place last. The - # host only caches a prepared disk that has $image_root, and guest exit - # codes do not reach the host, so $image_root must not exist until every - # step has succeeded. - case "$source" in - local-docker) - mkdir -p "$partial_root" - tar -xpf "$payload_dir/source-rootfs.tar" -C "$partial_root" - ;; - oci-layout) - if [ ! -x /opt/openshell/bin/umoci ]; then - ts "FATAL: umoci not found in VM bootstrap image" - exit 1 - fi - # `umoci raw unpack` extracts the image filesystem directly into - # the target directory; unlike `umoci unpack`, it does not create - # a bundle with a rootfs/ subdirectory. - /opt/openshell/bin/umoci raw unpack \ - --image "$payload_dir/oci:openshell" \ - "$partial_root" - if [ ! -d "$partial_root" ]; then - ts "FATAL: umoci unpack did not produce a rootfs directory" - exit 1 - fi - ;; - *) - ts "FATAL: unknown guest image payload source: ${source:-missing}" - exit 1 - ;; - esac - - ensure_target_runtime "$partial_root" - if [ -f "$payload_dir/identity" ]; then - cp "$payload_dir/identity" "$partial_root/.openshell-rootfs-variant" - fi - rm -rf "$payload_dir" - mv "$partial_root" "$image_root" -} - -exec_supervisor_in_newroot() { - local chroot_bin - local supervisor="/.openshell-bootstrap/opt/openshell/bin/openshell-sandbox" - - for chroot_bin in /usr/sbin/chroot /usr/bin/chroot /sbin/chroot /bin/chroot; do - [ -x "$chroot_bin" ] || continue - - if [ -x "/newroot${supervisor}" ]; then - exec "$chroot_bin" /newroot "$supervisor" "$@" - fi - done - - ts "FATAL: unable to exec openshell-sandbox in guest rootfs" - exit 1 -} - -setup_overlay_root() { - ts "setting up writable overlay root" - mount_initial_fs - - if [ ! -b /dev/vdb ]; then - ts "FATAL: writable overlay disk /dev/vdb not found" - exit 1 - fi - - mkdir -p /overlay /lower /newroot /image-cache - mount -o remount,ro / 2>/dev/null || true - mount -t ext4 -o rw /dev/vdb /overlay - mkdir -p /overlay/upper /overlay/work - source_overlay_env_if_present - - if [ "${OPENSHELL_VM_INIT_MODE:-sandbox}" = "image-prep" ]; then - prepare_guest_image_rootfs - sync - if ! umount /overlay; then - ts "FATAL: failed to unmount /overlay cleanly after image-prep; refusing to produce a dirty image-cache disk" - exit 1 - fi - ts "image-prep complete" - exit 0 - fi - - mount --bind / /lower - mount -o remount,bind,ro /lower 2>/dev/null || true - - local lower_root="/lower" - if [ -b /dev/vdc ]; then - mount -t ext4 -o ro,noload /dev/vdc /image-cache - if [ -d /image-cache/image-rootfs ]; then - lower_root="/image-cache/image-rootfs" - ts "using prepared image rootfs lowerdir" - else - ts "FATAL: prepared image disk missing /image-rootfs" - exit 1 - fi - fi - - # The host makes upper under the gateway's umask and uid, and it becomes /. - chown 0:0 /overlay/upper - chmod 0755 /overlay/upper - - mount -t overlay overlay \ - -o lowerdir="$lower_root",upperdir=/overlay/upper,workdir=/overlay/work \ - /newroot - mkdir -p /newroot/.openshell-bootstrap - mount --bind /lower /newroot/.openshell-bootstrap - - # GPU setup runs against the bootstrap runtime and its mounted /dev, /proc, - # and /run before those filesystems are mirrored into the target root. - if [ "${GPU_ENABLED}" = "true" ]; then - setup_gpu || ts "WARNING: GPU init failed; continuing without GPU" - fi - - bind_mount_into_newroot /proc - bind_mount_into_newroot /sys - bind_mount_into_newroot /tmp - bind_mount_into_newroot /dev - bind_mount_into_newroot /run - - ROOT_PREFIX="/newroot" - run_post_overlay_setup -} - -create_gpu_device_nodes_mknod() { - # Mode 666 is intentional: single-tenant microVM with the VM itself as the - # isolation boundary. The sandbox user is the only non-root user. - local nv_major - nv_major=$(awk '$2 == "nvidia" {print $1}' /proc/devices 2>/dev/null || true) - if [ -n "$nv_major" ]; then - mknod -m 666 /dev/nvidiactl c "$nv_major" 255 2>/dev/null || true - - local gpu_count=0 - if [ -d /proc/driver/nvidia/gpus ]; then - for gpu_dir in /proc/driver/nvidia/gpus/*/; do - [ -d "$gpu_dir" ] || continue - mknod -m 666 "/dev/nvidia${gpu_count}" c "$nv_major" "$gpu_count" 2>/dev/null || true - gpu_count=$((gpu_count + 1)) - done - fi - if [ "$gpu_count" -eq 0 ]; then - mknod -m 666 /dev/nvidia0 c "$nv_major" 0 2>/dev/null || true - fi - - local modeset_major - modeset_major=$(awk '$2 == "nvidia-modeset" {print $1}' /proc/devices 2>/dev/null || true) - if [ -n "$modeset_major" ]; then - mknod -m 666 /dev/nvidia-modeset c "$modeset_major" 254 2>/dev/null || true - fi - - local uvm_major - uvm_major=$(awk '$2 == "nvidia-uvm" {print $1}' /proc/devices 2>/dev/null || true) - if [ -n "$uvm_major" ]; then - mknod -m 666 /dev/nvidia-uvm c "$uvm_major" 0 2>/dev/null || true - mknod -m 666 /dev/nvidia-uvm-tools c "$uvm_major" 1 2>/dev/null || true - fi - - local caps_major - caps_major=$(awk '$2 == "nvidia-caps" {print $1}' /proc/devices 2>/dev/null || true) - if [ -n "$caps_major" ]; then - mkdir -p /dev/nvidia-caps 2>/dev/null || true - mknod -m 666 /dev/nvidia-caps/nvidia-cap1 c "$caps_major" 1 2>/dev/null || true - mknod -m 666 /dev/nvidia-caps/nvidia-cap2 c "$caps_major" 2 2>/dev/null || true - fi - - ts "GPU device nodes created via mknod (${gpu_count} GPU(s), major=${nv_major})" - else - ts "WARNING: 'nvidia' not in /proc/devices; device nodes unavailable" - fi -} - -setup_gpu() { - ts "GPU_ENABLED=true — initializing GPU passthrough" - - if ! command -v modprobe >/dev/null 2>&1; then - ts "FATAL: modprobe not found; cannot load nvidia kernel modules" - return 1 - fi - - # Stage GSP firmware to tmpfs so module loading reads it from a stable - # early-boot path. - if [ -d /lib/firmware/nvidia ]; then - ts "staging GPU firmware to tmpfs" - mkdir -p /run/firmware/nvidia - cp -a /lib/firmware/nvidia/* /run/firmware/nvidia/ 2>/dev/null || true - if [ -e /sys/module/firmware_class/parameters/path ]; then - echo /run/firmware > /sys/module/firmware_class/parameters/path - fi - fi - - ts "loading nvidia kernel modules" - modprobe nvidia || { ts "FATAL: modprobe nvidia failed"; return 1; } - modprobe nvidia_uvm 2>/dev/null || true - modprobe nvidia_modeset 2>/dev/null || true - - rm -rf /run/firmware 2>/dev/null || true - - if command -v nvidia-smi >/dev/null 2>&1; then - ts "running nvidia-smi to create device nodes and validate GPU" - local smi_rc=0 - nvidia-smi >/dev/null 2>&1 || smi_rc=$? - if [ "$smi_rc" -eq 0 ]; then - nvidia-smi -L 2>/dev/null | while read -r line; do ts " $line"; done - ts "GPU initialization successful" - else - ts "WARNING: nvidia-smi failed (exit ${smi_rc}); falling back to mknod" - create_gpu_device_nodes_mknod - fi - else - ts "nvidia-smi not found; creating device nodes via mknod" - create_gpu_device_nodes_mknod - fi -} - -reconcile_sandbox_account() { - local sandbox_uid="${OPENSHELL_VM_SANDBOX_UID:-}" - local sandbox_gid="${OPENSHELL_VM_SANDBOX_GID:-}" - local etc - - [ -n "$sandbox_uid" ] && [ -n "$sandbox_gid" ] || return 0 - [[ "$sandbox_uid" =~ ^[0-9]+$ ]] && [[ "$sandbox_gid" =~ ^[0-9]+$ ]] || { - ts "FATAL: invalid requested sandbox identity" - exit 1 - } - etc="$(root_path /etc)" - mkdir -p "$etc" - touch "$etc/passwd" "$etc/group" "$etc/shadow" "$etc/gshadow" - if grep -q '^sandbox:' "$etc/group"; then - if ! awk -F: -v OFS=: -v gid="$sandbox_gid" \ - '$1 == "sandbox" { $3 = gid } { print }' \ - "$etc/group" >"$etc/group.openshell"; then - rm -f "$etc/group.openshell" - ts "FATAL: failed to reconcile sandbox group" - exit 1 - fi - mv "$etc/group.openshell" "$etc/group" - else - printf 'sandbox:x:%s:\n' "$sandbox_gid" >> "$etc/group" - fi - if grep -q '^sandbox:' "$etc/passwd"; then - # Preserve image-owned account metadata (home, shell, and description) - # while restoring the UID/GID contract recorded for this overlay. - if ! awk -F: -v OFS=: -v uid="$sandbox_uid" -v gid="$sandbox_gid" \ - '$1 == "sandbox" { $3 = uid; $4 = gid } { print }' \ - "$etc/passwd" >"$etc/passwd.openshell"; then - rm -f "$etc/passwd.openshell" - ts "FATAL: failed to reconcile sandbox account" - exit 1 - fi - mv "$etc/passwd.openshell" "$etc/passwd" - else - printf 'sandbox:x:%s:%s:OpenShell Sandbox:/sandbox:/bin/sh\n' "$sandbox_uid" "$sandbox_gid" >> "$etc/passwd" - fi - grep -q '^sandbox:' "$etc/gshadow" || printf 'sandbox:!::\n' >> "$etc/gshadow" - grep -q '^sandbox:' "$etc/shadow" || printf 'sandbox:!:20123:0:99999:7:::\n' >> "$etc/shadow" - ts "reconciled sandbox account (${sandbox_uid}:${sandbox_gid})" -} - -setup_sandbox_workdir() { - local sandbox_dir - local owner - local current_owner - sandbox_dir="$(root_path /sandbox)" - owner="$(sandbox_owner)" - mkdir -p "$sandbox_dir" - current_owner="$(stat -c '%u:%g' "$sandbox_dir" 2>/dev/null || true)" - if [ "$owner" = "10001:10001" ]; then - ts "preserving legacy sandbox ownership (10001:10001)" - fi - if [ "$current_owner" != "$owner" ]; then - if ! chown -R "$owner" "$sandbox_dir" 2>/dev/null; then - ts "FATAL: failed to apply sandbox ownership (${owner})" - exit 1 - fi - fi - chmod 0755 "$sandbox_dir" - ts "prepared /sandbox ownership (${owner})" -} - -configure_hostname() { - local sandbox_hostname="${OPENSHELL_SANDBOX:-openshell-sandbox-vm}" - sandbox_hostname="$(printf '%s' "$sandbox_hostname" | tr -c 'A-Za-z0-9.-' '-')" - sandbox_hostname="$(printf '%s' "$sandbox_hostname" | sed 's/^[.-][.-]*//; s/[.-][.-]*$//')" - sandbox_hostname="$(printf '%.63s' "$sandbox_hostname")" - if [ -z "$sandbox_hostname" ]; then - sandbox_hostname="openshell-sandbox-vm" - fi - - hostname "$sandbox_hostname" 2>/dev/null || true - printf '%s\n' "$sandbox_hostname" >"$(root_path /etc/hostname)" 2>/dev/null || true - ts "hostname=${sandbox_hostname}" -} - -# OCI images commonly ship an empty /etc/hosts and rely on the container -# runtime to bind-mount a generated one. No runtime does that here, and /etc is -# read-only once the supervisor applies policy, so init supplies the loopback -# names when the file is missing or empty. A non-empty file is the image -# author's and is kept as is. Without these entries `localhost` fails to -# resolve: the guest resolver is the loopback relay, which has no record for it. -configure_hosts() { - local hosts_file - hosts_file="$(root_path /etc/hosts)" - - # An absolute symlink target resolves against init's own root, not the - # workload root, so following one could write outside the workload. Leave - # an image-authored link alone. - if [ -L "$hosts_file" ]; then - ts "WARN: ${hosts_file} is a symlink; leaving it unchanged" - return 0 - fi - if [ -s "$hosts_file" ]; then - return 0 - fi - - # Missing loopback names degrade the workload but do not make the sandbox - # unsafe, so a write failure is reported and boot continues. The shell's - # own error stays visible on the console to explain the failure. - if ! printf '%s\n' \ - '127.0.0.1 localhost' \ - '::1 localhost ip6-localhost ip6-loopback' \ - >"$hosts_file"; then - ts "WARN: could not write ${hosts_file}; localhost will not resolve" - return 0 - fi - ts "populated empty /etc/hosts with loopback names" -} - -run_openshell_init_dropins() { - # Run executable drop-ins from /opt/openshell/init.d in deterministic - # ASCII-sorted order. Drop-ins are *executed* in a child shell rather - # than sourced, so they cannot mutate parent shell state or exit the - # caller. They inherit `OPENSHELL_VM_INIT_PHASE`, `ROOT_PREFIX`, and - # any `OPENSHELL_VM_DATA_*` env vars set by lifecycle extensions. - # - # Security: this runs as root before the supervisor enforces policy, so - # it executes *only* the drop-ins the VM driver explicitly injected this - # launch, as enumerated in the driver-authored manifest. Anything else - # found under init.d (e.g. files baked into a user-controlled guest - # image) is ignored. The manifest lives in the overlay upperdir, which - # the driver owns, so a guest image cannot forge or shadow it. A missing - # manifest is treated as "run nothing" (fail-closed). - local init_dir manifest - init_dir="$(root_path /opt/openshell/init.d)" - manifest="$(root_path /opt/openshell/init.d.manifest)" - - if [ ! -f "$manifest" ]; then - if [ -d "$init_dir" ]; then - ts "no OpenShell VM init drop-in manifest present; skipping init.d" - fi - return 0 - fi - - export OPENSHELL_VM_INIT_PHASE="before-supervisor" - export ROOT_PREFIX="${ROOT_PREFIX:-}" - - # Fail closed on any inconsistency: every drop-in below is trusted, - # required setup the driver injected on purpose, so we abort the boot - # rather than run a half-configured sandbox. Aborting exits this init - # non-zero; the VM helper then exits and the driver runs - # lifecycle-extension cleanup, so a failed init does not leak resources. - # The loop runs in the main shell (process substitution, not a pipe), so - # `exit` here terminates init as intended. - local name dropin rc - while IFS= read -r name; do - [ -n "$name" ] || continue - # Manifest entries are bare file names that the driver already - # validated. A separator or traversal here means the manifest was - # tampered with after the driver wrote it. - case "$name" in - */* | . | ..) - ts "FATAL: unsafe init drop-in manifest entry '${name}'" - exit 1 - ;; - esac - - # The driver writes each entry's file and marks it 0755 in the same - # operation, so a missing or non-executable entry means the overlay - # was tampered with or provisioning is broken. - dropin="${init_dir}/${name}" - if [ ! -f "$dropin" ]; then - ts "FATAL: init drop-in '${name}' listed in manifest but not found" - exit 1 - fi - if [ ! -x "$dropin" ]; then - ts "FATAL: init drop-in '${name}' is not executable" - exit 1 - fi - - ts "running OpenShell VM init drop-in ${name}" - rc=0 - set +e - "$dropin" - rc=$? - set -e - if [ "$rc" -ne 0 ]; then - ts "FATAL: OpenShell VM init drop-in ${name} failed with exit code ${rc}" - exit 1 - fi - done < <(LC_ALL=C sort -u "$manifest") -} - -# Create a virtiofs mount point under ROOT_PREFIX without following symlinks, -# so an image cannot redirect a validated target onto another guest path. -# Directories created under /sandbox are handed to the sandbox user. -prepare_virtiofs_target() { - local target="$1" owner="$2" - local path="${ROOT_PREFIX:-}" component - local -a components - IFS=/ read -r -a components <<<"${target#/}" - for component in "${components[@]}"; do - [ -n "$component" ] || continue - path="${path}/${component}" - if [ -L "$path" ]; then - ts >&2 "FATAL: virtiofs mount target ${target} traverses symlink ${path#"${ROOT_PREFIX:-}"}" - exit 1 - fi - if [ ! -e "$path" ]; then - if ! mkdir "$path"; then - ts >&2 "FATAL: failed to create virtiofs mount point ${target}" - exit 1 - fi - case "${path#"${ROOT_PREFIX:-}"}" in - /sandbox/*) - if ! chown "$owner" "$path"; then - ts >&2 "FATAL: failed to hand virtiofs mount point parent ${path#"${ROOT_PREFIX:-}"} to ${owner}" - exit 1 - fi - ;; - esac - elif [ ! -d "$path" ]; then - ts >&2 "FATAL: virtiofs mount target ${target} is not a directory" - exit 1 - fi - done - printf '%s\n' "$path" -} - -# Runs after every /sandbox ownership fixup and the root-run init drop-ins so -# nothing in init walks into host-backed shares. -mount_virtiofs_shares() { - local manifest - manifest="$(root_path /.openshell/mounts.manifest)" - # The driver always writes the manifest; it is empty without mounts. - [ -s "$manifest" ] || return 0 - - ts "mounting virtiofs shares" - local tag target mode mount_opts guest_target owner - owner="$(sandbox_owner)" - while IFS=$'\t' read -r tag target mode; do - [ -n "$tag" ] || continue - case "$mode" in - ro) mount_opts="-o ro" ;; - rw) mount_opts="" ;; - *) - ts "FATAL: unknown virtiofs mount mode '${mode}' for tag ${tag}" - exit 1 - ;; - esac - guest_target="$(prepare_virtiofs_target "$target" "$owner")" || exit 1 - # shellcheck disable=SC2086 - if mount -t virtiofs $mount_opts "$tag" "$guest_target"; then - ts " mounted virtiofs ${tag} -> ${target} (${mode})" - else - ts "FATAL: failed to mount virtiofs ${tag} at ${target}" - exit 1 - fi - done < "$manifest" -} - -run_post_overlay_setup() { - # Source QEMU-injected environment variables if present. The file lives in - # the overlay upperdir so the cached bootstrap rootfs remains immutable. - local env_file - env_file="$(root_path /srv/openshell-env.sh)" - if [ -f "$env_file" ]; then - # shellcheck source=/dev/null - source "$env_file" - fi - - if [ -z "${ROOT_PREFIX:-}" ]; then - mount -t proc proc /proc 2>/dev/null & - mount -t sysfs sysfs /sys 2>/dev/null & - mount -t tmpfs tmpfs /tmp 2>/dev/null & - mount -t tmpfs tmpfs /run 2>/dev/null & - mount -t devtmpfs devtmpfs /dev 2>/dev/null & - wait - fi - - mkdir -p "$(root_path /dev/pts)" "$(root_path /dev/shm)" "$(root_path /sys/fs/cgroup)" - mount -t devpts devpts "$(root_path /dev/pts)" 2>/dev/null & - mount -t tmpfs tmpfs "$(root_path /dev/shm)" 2>/dev/null & - mount -t cgroup2 cgroup2 "$(root_path /sys/fs/cgroup)" 2>/dev/null & - wait - - reconcile_sandbox_account - setup_sandbox_workdir - - configure_hostname - configure_hosts - if ! /opt/openshell/bin/openshell-vm-init prepare-network; then - ts "FATAL: failed to bring up the loopback interface" - exit 1 - fi - - # The capability-free sandbox owns a loopback-only DNS relay. Guest init - # grants the low port before handing control to the zero-capability UID. - if ! echo 0 > /proc/sys/net/ipv4/ip_unprivileged_port_start; then - ts "FATAL: failed to permit the unprivileged DNS relay to bind port 53" - exit 1 - fi - cat >"$(root_path /etc/resolv.conf)" <<'EOF' -nameserver 127.0.0.53 -options timeout:2 attempts:2 -EOF - -# The boundary transport mediates network and DNS requests. Only loopback is -# configured in the guest; no public resolver or guest NIC is needed. - -export HOME=/sandbox -export USER=sandbox - -# Fix /sandbox ownership. The host-side CLI extracts OCI layers as a non-root -# user (e.g. UID 501 on macOS), so /sandbox may be owned by the host UID. -# -# On macOS (Hypervisor.framework), guest root has real root privileges and -# chown succeeds. On Linux non-root hosts with virtiofs, guest root maps to -# the host user, so chown is denied — this is non-fatal because the -# supervisor's own filesystem preparation handles the paths that matter. -if [ -d /sandbox ]; then - _sb_uid=$(id -u sandbox 2>/dev/null || true) - _sb_gid=$(id -g sandbox 2>/dev/null || true) - if [ -n "$_sb_uid" ] && [ -n "$_sb_gid" ]; then - _cur_uid=$(stat -c '%u' /sandbox 2>/dev/null || true) - if [ -n "$_cur_uid" ] && [ "$_cur_uid" != "$_sb_uid" ]; then - ts "fixing /sandbox ownership (was uid=${_cur_uid}, setting to sandbox=${_sb_uid}:${_sb_gid})" - chown -R "${_sb_uid}:${_sb_gid}" /sandbox 2>/dev/null || \ - ts "chown /sandbox denied (virtiofs rootless host), continuing" - fi - fi -fi - -run_openshell_init_dropins - -mount_virtiofs_shares - -if [ -n "${OPENSHELL_SANDBOX_ID:-}" ]; then - ts "OPENSHELL_SANDBOX_ID=${OPENSHELL_SANDBOX_ID}" -fi - -ts "starting OpenShell VM sandbox" -_sandbox_owner="$(sandbox_owner)" -_sandbox_uid="${_sandbox_owner%%:*}" -_sandbox_gid="${_sandbox_owner##*:}" -_sandbox_bootstrap_guest="${OPENSHELL_VM_SANDBOX_BOOTSTRAP:-/.openshell/state/bootstrap.json}" -_sandbox_bootstrap="$(root_path "$_sandbox_bootstrap_guest")" -_sandbox_state_dir="${_sandbox_bootstrap%/*}" -if [ ! -f "$_sandbox_bootstrap" ]; then - ts "FATAL: capability-free sandbox bootstrap is missing" - exit 1 -fi -chown "${_sandbox_uid}:${_sandbox_gid}" "$_sandbox_state_dir" -chmod 0700 "$_sandbox_state_dir" -for _sandbox_private_file in "$_sandbox_state_dir"/*; do - [ -f "$_sandbox_private_file" ] || continue - chown "${_sandbox_uid}:${_sandbox_gid}" "$_sandbox_private_file" - chmod 0600 "$_sandbox_private_file" -done -if [ "${OPENSHELL_VM_INIT_MODE:-sandbox}" = "capability-probe" ]; then - ts "starting capability-free VM qualification as ${_sandbox_uid}:${_sandbox_gid}" - if [ "${ROOT_PREFIX:-}" = "/newroot" ]; then - exec_supervisor_in_newroot capability-probe-launch "$_sandbox_uid" "$_sandbox_gid" - fi - exec /opt/openshell/bin/openshell-sandbox \ - capability-probe-launch "$_sandbox_uid" "$_sandbox_gid" -fi -if [ "${ROOT_PREFIX:-}" = "/newroot" ]; then - exec_supervisor_in_newroot \ - launch-capability-free "$_sandbox_uid" "$_sandbox_gid" "$_sandbox_bootstrap_guest" -fi -exec /opt/openshell/bin/openshell-sandbox \ - launch-capability-free "$_sandbox_uid" "$_sandbox_gid" "$_sandbox_bootstrap_guest" -} - -if [ "${1:-}" != "--post-overlay" ]; then - setup_overlay_root -fi - -shift || true -run_post_overlay_setup diff --git a/crates/openshell-driver-vm/src/bin/openshell-vm-init.rs b/crates/openshell-driver-vm/src/bin/openshell-vm-init.rs deleted file mode 100644 index 649c4ccf01..0000000000 --- a/crates/openshell-driver-vm/src/bin/openshell-vm-init.rs +++ /dev/null @@ -1,240 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Narrow, one-shot guest preparation used by the VM compute driver. - -use std::ffi::OsString; -use std::fmt; -#[cfg(target_os = "linux")] -use std::mem::size_of; -#[cfg(target_os = "linux")] -use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd}; -use std::process::ExitCode; - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum Command { - PrepareNetwork, - Version, -} - -#[cfg(target_os = "linux")] -#[derive(Clone, Copy)] -enum InterfaceFlagOperation { - Read, - Write, -} - -#[derive(Debug)] -struct InitError(String); - -impl fmt::Display for InitError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str(&self.0) - } -} - -fn main() -> ExitCode { - match run(std::env::args_os().skip(1)) { - Ok(()) => ExitCode::SUCCESS, - Err(error) => { - eprintln!("openshell-vm-init: {error}"); - ExitCode::FAILURE - } - } -} - -fn run(args: impl IntoIterator) -> Result<(), InitError> { - match parse_command(args)? { - Command::PrepareNetwork => prepare_network(), - Command::Version => { - println!("openshell-vm-init {}", env!("CARGO_PKG_VERSION")); - Ok(()) - } - } -} - -fn parse_command(args: impl IntoIterator) -> Result { - let mut args = args.into_iter(); - let command = args - .next() - .ok_or_else(|| InitError("expected the prepare-network command".to_string()))?; - if args.next().is_some() { - return Err(InitError("command does not accept arguments".to_string())); - } - match command.to_str() { - Some("prepare-network") => Ok(Command::PrepareNetwork), - Some("--version") => Ok(Command::Version), - _ => Err(InitError(format!( - "unknown command '{}'; expected prepare-network or --version", - command.to_string_lossy() - ))), - } -} - -#[cfg(target_os = "linux")] -#[allow(unsafe_code)] -fn prepare_network() -> Result<(), InitError> { - // The helper is only invoked by trusted VM guest init, before it hands the - // workload to the capability-free sandbox identity. - if rustix::process::geteuid().as_raw() != 0 { - return Err(InitError( - "prepare-network must run as the VM guest root user".to_string(), - )); - } - - // SAFETY: socket returns a fresh descriptor or -1 and does not borrow any - // caller-owned memory. - let raw_fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) }; - if raw_fd < 0 { - return Err(last_os_error("open loopback control socket")); - } - // SAFETY: raw_fd was returned successfully above and ownership transfers - // exactly once to OwnedFd. - let socket = unsafe { OwnedFd::from_raw_fd(raw_fd) }; - - let mut request = InterfaceRequest::loopback(); - ioctl_interface_flags( - socket.as_raw_fd(), - InterfaceFlagOperation::Read, - &mut request, - ) - .map_err(|error| InitError(format!("read loopback flags: {error}")))?; - let up_flag = libc::c_short::try_from(libc::IFF_UP) - .map_err(|_| InitError("platform IFF_UP value does not fit in ifreq flags".to_string()))?; - let flags = request.flags(); - if flags & up_flag == 0 { - request.set_flags(flags | up_flag); - ioctl_interface_flags( - socket.as_raw_fd(), - InterfaceFlagOperation::Write, - &mut request, - ) - .map_err(|error| InitError(format!("enable loopback: {error}")))?; - } - - request.set_flags(0); - ioctl_interface_flags( - socket.as_raw_fd(), - InterfaceFlagOperation::Read, - &mut request, - ) - .map_err(|error| InitError(format!("verify loopback flags: {error}")))?; - if request.flags() & up_flag == 0 { - return Err(InitError( - "loopback remained down after successful configuration".to_string(), - )); - } - Ok(()) -} - -#[cfg(not(target_os = "linux"))] -fn prepare_network() -> Result<(), InitError> { - Err(InitError( - "prepare-network is only supported in Linux VM guests".to_string(), - )) -} - -#[cfg(target_os = "linux")] -#[repr(C)] -union InterfaceRequestData { - flags: libc::c_short, - // Linux's ifreq union is 24 bytes on the supported 64-bit guest targets. - storage: [u8; 24], -} - -#[cfg(target_os = "linux")] -#[repr(C)] -struct InterfaceRequest { - name: [libc::c_char; libc::IFNAMSIZ], - data: InterfaceRequestData, -} - -#[cfg(target_os = "linux")] -const _: () = assert!(size_of::() == size_of::()); - -#[cfg(target_os = "linux")] -impl InterfaceRequest { - fn loopback() -> Self { - let mut request = Self { - name: [0; libc::IFNAMSIZ], - data: InterfaceRequestData { storage: [0; 24] }, - }; - request.name[0] = 108; - request.name[1] = 111; - request - } - - #[allow(unsafe_code)] - fn flags(&self) -> libc::c_short { - // SAFETY: the request was most recently populated by SIOCGIFFLAGS or - // set_flags, both of which initialize the flags union member. - unsafe { self.data.flags } - } - - fn set_flags(&mut self, flags: libc::c_short) { - self.data.flags = flags; - } -} - -#[cfg(target_os = "linux")] -#[allow(unsafe_code)] -fn ioctl_interface_flags( - fd: std::os::fd::RawFd, - operation: InterfaceFlagOperation, - interface: &mut InterfaceRequest, -) -> std::io::Result<()> { - let request = match operation { - InterfaceFlagOperation::Read => libc::SIOCGIFFLAGS, - InterfaceFlagOperation::Write => libc::SIOCSIFFLAGS, - }; - let request = libc::Ioctl::try_from(request).map_err(|_| { - std::io::Error::new( - std::io::ErrorKind::InvalidInput, - "interface flag ioctl request does not fit the platform ABI", - ) - })?; - let interface_pointer: *mut InterfaceRequest = interface; - // SAFETY: interface points to an ifreq-compatible buffer that remains - // valid and exclusively borrowed for the duration of ioctl. - if unsafe { libc::ioctl(fd, request, interface_pointer) } < 0 { - Err(std::io::Error::last_os_error()) - } else { - Ok(()) - } -} - -#[cfg(target_os = "linux")] -fn last_os_error(operation: &str) -> InitError { - InitError(format!("{operation}: {}", std::io::Error::last_os_error())) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn accepts_only_prepare_network_without_arguments() { - assert_eq!( - parse_command([OsString::from("prepare-network")]).expect("valid command"), - Command::PrepareNetwork - ); - assert_eq!( - parse_command([OsString::from("--version")]).expect("valid version command"), - Command::Version - ); - assert!(parse_command(Vec::::new()).is_err()); - assert!(parse_command([OsString::from("other")]).is_err()); - assert!( - parse_command([OsString::from("prepare-network"), OsString::from("eth0")]).is_err() - ); - } - - #[cfg(target_os = "linux")] - #[test] - fn loopback_request_has_a_fixed_interface_name() { - let request = InterfaceRequest::loopback(); - assert_eq!(request.name[0], 108); - assert_eq!(request.name[1], 111); - assert!(request.name[2..].iter().all(|byte| *byte == 0)); - } -} diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs deleted file mode 100644 index 69a0f766ad..0000000000 --- a/crates/openshell-driver-vm/src/driver.rs +++ /dev/null @@ -1,15154 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![allow(unsafe_code)] - -#[path = "preparation.rs"] -mod preparation; - -#[cfg(test)] -#[path = "registry_cache_tests.rs"] -mod registry_cache_tests; - -use crate::gpu::{GpuInventory, allocate_vsock_cid}; - -use crate::isolation::VmBoundarySpec; -use crate::layer_applier::BootstrapExtractionBudget; -use crate::lifecycle::{ - BackendFeature, GuestInitDropin, LaunchAbortReason, LaunchPlan, LifecycleExtensionRegistry, - RestoreContext, extension_state_dir, -}; -use crate::rootfs::{ - clone_or_copy_sparse_file, create_ext4_image_from_dir_with_size, create_rootfs_image_from_dir, - ext4_image_has_directory, extract_host_supervisor, extract_rootfs_archive_to, - prepare_sandbox_rootfs_from_image_root, recover_rootfs_image, remove_rootfs_image_file, - sandbox_guest_init_path, sandbox_guest_runtime_identity, sandbox_guest_user_ids_from_image, - sandbox_guest_user_ids_from_overlay_image, set_rootfs_image_file_mode, - validate_host_supervisor, write_rootfs_image_file, -}; -use crate::runtime::VmBackend; -use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; -use bollard::Docker; -use bollard::errors::Error as BollardError; -use bollard::models::ContainerCreateBody; -use bollard::query_parameters::{CreateContainerOptionsBuilder, RemoveContainerOptionsBuilder}; -use flate2::read::MultiGzDecoder; -use futures::{Stream, StreamExt, TryStreamExt}; -use nix::errno::Errno; -use nix::sys::signal::{Signal, kill}; -use nix::unistd::Pid; -use oci_client::client::{Client as OciClient, ClientConfig}; -use oci_client::errors::{OciDistributionError, OciErrorCode}; -use oci_client::manifest::{ - ImageIndexEntry, OCI_IMAGE_MEDIA_TYPE, OciDescriptor, OciImageManifest, -}; -use oci_client::secrets::RegistryAuth; -use oci_client::{Reference, RegistryOperation}; -use openshell_core::UpstreamProxyConfig; -use openshell_core::config::DEFAULT_STOP_TIMEOUT_SECS; -use openshell_core::driver_mounts; -use openshell_core::gpu::{ - driver_gpu_requirements, effective_driver_gpu_count, validate_specific_gpu_device_request, -}; -use openshell_core::progress::{ - PROGRESS_STEP_PULLING_IMAGE, PROGRESS_STEP_REQUESTING_SANDBOX, PROGRESS_STEP_STARTING_SANDBOX, - format_bytes, mark_progress_active, mark_progress_complete, mark_progress_detail, -}; -use openshell_core::proto::compute::v1::{ - CpuResourceCapabilities, CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, - DeleteSandboxResponse, DeleteWorkspaceRequest, DeleteWorkspaceResponse, - DriverCondition as SandboxCondition, DriverPlatformEvent as PlatformEvent, - DriverSandbox as Sandbox, DriverSandboxStatus as SandboxStatus, - DriverSandboxTemplate as SandboxTemplate, EnsureWorkspaceRequest, EnsureWorkspaceResponse, - GetCapabilitiesRequest, GetCapabilitiesResponse, GetSandboxRequest, GetSandboxResponse, - GpuResourceCapabilities, ListSandboxesRequest, ListSandboxesResponse, - MemoryResourceCapabilities, ResolvedWorkloadIdentity, ResourceCapabilities, - StartSandboxRequest, StartSandboxResponse, StopSandboxRequest, StopSandboxResponse, - SuspendSandboxRequest, SuspendSandboxResponse, ValidateSandboxCreateRequest, - ValidateSandboxCreateResponse, WatchSandboxesDeletedEvent, WatchSandboxesEvent, - WatchSandboxesPlatformEvent, WatchSandboxesRequest, WatchSandboxesSandboxEvent, - WorkloadIdentityRequest, compute_driver_server::ComputeDriver, watch_sandboxes_event, -}; -use openshell_core::proto_struct::{deserialize_optional_non_empty_string_list, from_struct}; -use openshell_core::{ - NetworkSupervisorTrustBundle, network_trust::MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES, -}; -use openshell_sandbox_backend::boundary_protocol::{ - BoundaryConfig, BoundaryListener, GatewayVerificationKey, SandboxRuntimeDescriptor, - SandboxTlsClientConfig, SandboxTlsMaterial, SandboxTlsServerConfig, SandboxTransport, - generate_sandbox_tls_material, -}; -use openshell_vfio::SysfsRoot; -use opentelemetry::trace::TraceContextExt as _; -use prost::Message; -use sha2::{Digest, Sha256}; -use std::collections::{HashMap, HashSet}; -use std::fmt::Write as _; -use std::fs; -use std::future::Future; -use std::io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write}; -#[cfg(unix)] -use std::os::fd::{AsRawFd as _, OwnedFd}; -#[cfg(unix)] -use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt}; -#[cfg(unix)] -use std::os::unix::process::ExitStatusExt as _; -use std::path::{Component, Path, PathBuf}; -use std::pin::Pin; -use std::process::{ExitStatus, Stdio}; -use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::Duration; -use tokio::io::{AsyncBufReadExt, AsyncWriteExt}; -use tokio::process::{Child, Command}; -use tokio::sync::{Mutex, broadcast, mpsc}; -use tokio::task::JoinHandle; -use tokio_stream::wrappers::ReceiverStream; -use tonic::{Request, Response, Status}; -use tracing::{Instrument as _, info, warn}; -use tracing_opentelemetry::OpenTelemetrySpanExt as _; -use url::{Host, Url}; - -const DRIVER_NAME: &str = "openshell-driver-vm"; -const WATCH_BUFFER: usize = 256; -const DEFAULT_VCPUS: u8 = 2; -const DEFAULT_MEM_MIB: u32 = 2048; -const DEFAULT_OVERLAY_DISK_MIB: u64 = 4096; -const DEFAULT_BOOTSTRAP_EXTRACTION_MAX_BYTES: u64 = 10 * 1024 * 1024 * 1024; -const DEFAULT_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY: usize = 4; -const MAX_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY: usize = 16; -const REGISTRY_REQUEST_MAX_ATTEMPTS: usize = 4; -const REGISTRY_RETRY_INITIAL_DELAY: Duration = Duration::from_millis(250); -const REGISTRY_RETRY_MAX_DELAY: Duration = Duration::from_secs(1); -/// 10 GiB — configurable via `rootfs_tar_max_bytes`. -const DEFAULT_ROOTFS_TAR_MAX_BYTES: u64 = 10 * 1024 * 1024 * 1024; -const ROOTFS_TAR_STAGING_DIR: &str = "rootfs-tar-staging"; -const VM_CONSOLE_DIAGNOSTIC_BYTES: u64 = 8 * 1024; - -/// Mirrors the Docker/Podman `type` tag so their bind entries parse -/// unchanged; virtiofs can only share host directories. -#[derive(Debug, Clone, Copy, serde::Deserialize)] -#[serde(rename_all = "lowercase")] -enum VmMountType { - Bind, -} - -#[derive(Debug, Clone, serde::Deserialize)] -#[serde(deny_unknown_fields)] -struct VmMountConfig { - #[serde(default, rename = "type")] - #[allow(dead_code)] - mount_type: Option, - source: String, - target: String, - #[serde(default = "default_read_only")] - read_only: bool, -} - -impl VmMountConfig { - /// Source without trailing slashes. A trailing slash makes both the - /// symlink check and libkrun's `O_NOFOLLOW` open resolve a final symlink. - fn host_source(&self) -> &str { - match self.source.trim_end_matches('/') { - "" => "/", - trimmed => trimmed, - } - } -} - -fn default_read_only() -> bool { - true -} - -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(default, deny_unknown_fields)] -struct VmSandboxDriverConfig { - #[serde( - default, - deserialize_with = "deserialize_optional_non_empty_string_list" - )] - gpu_device_ids: Option>, - rootfs_tar_path: Option, - #[serde(default)] - mounts: Vec, -} - -impl VmSandboxDriverConfig { - fn from_sandbox(sandbox: &Sandbox) -> Result { - let Some(template) = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - else { - return Ok(Self::default()); - }; - - Self::from_template(template) - } - - fn from_template(template: &SandboxTemplate) -> Result { - let Some(config) = template.driver_config.as_ref() else { - return Ok(Self::default()); - }; - - from_struct(config).map_err(|err| format!("invalid vm driver_config: {err}")) - } -} - -const OPENSHELL_HOST_GATEWAY_ALIAS: &str = "host.openshell.internal"; -const HOST_LOOPBACK_ALIASES: &[&str] = &[ - OPENSHELL_HOST_GATEWAY_ALIAS, - "host.containers.internal", - "host.docker.internal", -]; -#[allow(dead_code)] -const GUEST_SSH_SOCKET_PATH: &str = openshell_core::container_paths::SSH_SOCKET_PATH; -#[allow(dead_code)] -const GUEST_TLS_CA_PATH: &str = openshell_core::container_paths::VM_GUEST_TLS_CA_PATH; -#[allow(dead_code)] -const GUEST_SANDBOX_TOKEN_PATH: &str = openshell_core::container_paths::VM_GUEST_SANDBOX_TOKEN_PATH; -const GUEST_INIT_DROPIN_DIR: &str = openshell_core::container_paths::VM_GUEST_INIT_DROPIN_DIR; -const GUEST_BOUNDARY_CONFIG_DIR: &str = "/.openshell/state"; -const GUEST_BOUNDARY_CONFIG_ENV: &str = "OPENSHELL_VM_SANDBOX_BOOTSTRAP"; -const HOST_AUTH_BUNDLE_FILE: &str = "supervisor-auth.json"; -const HOST_RUNTIME_DESCRIPTOR_FILE: &str = "runtime-descriptor.json"; -const HOST_BOUNDARY_GENERATION_FILE: &str = "boundary-generation"; -/// Per-sandbox host-only copy of the gateway-normalized destination trust. -/// -/// This file is deliberately outside the VM disks. The host supervisor is the -/// only process which receives its path; the guest runs `openshell-sandbox` -/// and must never receive this material through its overlay, rootfs, argv, or -/// environment. -const HOST_ADDITIONAL_CA_FILE: &str = "additional-ca.crt"; -const HOST_ADDITIONAL_CA_TEMP_PREFIX: &str = ".additional-ca."; -const HOST_ADDITIONAL_CA_TEMP_SUFFIX: &str = ".tmp"; -/// The backend this driver admits. VM-specific placement remains inside the -/// opaque runtime descriptor. -const DRIVER_ADMITTED_BACKEND: &str = openshell_sandbox_backend::BACKEND_NAME; -const HOST_SUPERVISOR_BINARY: &str = "host-runtime/openshell-supervisor"; -const VM_CONTROL_SOCKET: &str = "control.sock"; -const VM_CONTROL_PORT: u32 = 5500; -/// Guest path of the driver-authored manifest enumerating which -/// `init.d` drop-ins the guest init script is allowed to execute. -/// -/// The guest runs *only* the entries listed here (fail-closed): anything -/// else found under `init.d` — e.g. files baked into a user-controlled -/// guest image — is ignored. The driver writes this file into the overlay -/// upperdir on every launch, so the image cannot forge or shadow it. -const GUEST_INIT_DROPIN_MANIFEST: &str = - openshell_core::container_paths::VM_GUEST_INIT_DROPIN_MANIFEST; -const IMAGE_CACHE_ROOT_DIR: &str = "images"; -const IMAGE_CACHE_ROOTFS_IMAGE: &str = "rootfs.ext4"; -const OVERLAY_TEMPLATE_CACHE_DIR: &str = "overlay-templates"; -const OVERLAY_TEMPLATE_CACHE_LAYOUT_VERSION: &str = "sandbox-overlay-ext4-v1"; -const SANDBOX_OVERLAY_IMAGE: &str = "overlay.ext4"; -const SANDBOX_OWNER_STATE_FILE: &str = "sandbox-owner-state"; -const SANDBOX_OWNER_STATE_V1: &str = "sandbox-owner-v1"; -const SANDBOX_OWNER_STATE_V2: &str = "sandbox-owner-v2"; -const SANDBOX_REQUEST_FILE: &str = "sandbox.pb"; -const SANDBOX_STOPPED_FILE: &str = "stopped"; -/// Durable tombstone preventing driver restart from relaunching a sandbox -/// whose canonical main process already terminated. -const MAIN_PROCESS_EXITED_FILE: &str = "main-process-exited"; -const GUEST_IMAGE_CONFIG_DIR: &str = "openshell-image"; -const GUEST_IMAGE_OCI_LAYOUT_DIR: &str = "oci"; -const GUEST_IMAGE_OCI_REF: &str = "openshell"; -const IMAGE_EXPORT_ROOTFS_ARCHIVE: &str = "source-rootfs.tar"; -// Older registry cache entries were not bound to the downloaded manifest. -const BOOTSTRAP_IMAGE_CACHE_LAYOUT_VERSION: &str = "sandbox-bootstrap-rootfs-ext4-v6"; -const PREPARED_IMAGE_CACHE_LAYOUT_VERSION: &str = "sandbox-prepared-rootfs-ext4-umoci-v4"; -const IMAGE_IDENTITY_FILE: &str = "image-identity"; -const IMAGE_REFERENCE_FILE: &str = "image-reference"; -const IMAGE_PREP_INIT_MODE: &str = "image-prep"; -const IMAGE_PREP_CONSOLE_LOG: &str = "image-prep-console.log"; -/// Directory the guest image-prep init writes at the root of the prepared disk -/// once preparation succeeds (`image_root` in `openshell-vm-sandbox-init.sh`). -pub(crate) const PREPARED_IMAGE_ROOTFS_DIR: &str = "/image-rootfs"; -static IMAGE_CACHE_BUILD_COUNTER: AtomicU64 = AtomicU64::new(0); -static OWNER_STATE_WRITE_COUNTER: AtomicU64 = AtomicU64::new(0); -static NETWORK_TRUST_WRITE_COUNTER: AtomicU64 = AtomicU64::new(0); - -#[derive(Debug, Clone)] -struct VmDriverTlsPaths { - ca: PathBuf, -} - -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -struct RuntimeImagePlan { - root_disk: PathBuf, - image_disk: Option, - image_identity: String, - bootstrap_image_identity: String, -} - -#[derive(Debug, Clone)] -struct PreparedImageDisk { - image_identity: String, - disk_path: PathBuf, -} - -#[derive(Debug, Clone)] -struct GuestImagePayload { - image_ref: String, - image_identity: String, - source: GuestImagePayloadSource, -} - -#[derive(Debug, Clone)] -enum GuestImagePayloadSource { - RegistryOciLayout { layout_dir: PathBuf }, - LocalDocker { rootfs_archive: PathBuf }, -} - -/// Driver-owned immutable copy of gateway-normalized destination trust. -/// -/// This is public only because [`VmDriverConfig`] is public. Its contents are -/// intentionally not constructible outside this module, and -/// [`VmDriver::new`] rejects a value supplied by a caller. The VM driver alone -/// creates it after reading and verifying the gateway artifact once. -#[derive(Clone)] -pub struct VmNetworkSupervisorTrustSnapshot { - bundle: NetworkSupervisorTrustBundle, -} - -impl VmNetworkSupervisorTrustSnapshot { - fn normalized_pem(&self) -> &[u8] { - self.bundle.normalized_pem() - } - - fn digest(&self) -> &str { - self.bundle.digest() - } - - fn certificate_count(&self) -> usize { - self.bundle.certificate_count() - } -} - -/// Redact PEM bytes and their original gateway artifact path from diagnostics. -impl std::fmt::Debug for VmNetworkSupervisorTrustSnapshot { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("VmNetworkSupervisorTrustSnapshot") - .field("certificate_count", &self.certificate_count()) - .field("digest", &self.digest()) - .finish_non_exhaustive() - } -} - -#[derive(Clone, serde::Serialize, serde::Deserialize)] -#[serde(deny_unknown_fields)] -#[allow(clippy::struct_excessive_bools)] -pub struct VmDriverConfig { - /// Permit caller-supplied driver JSON. Does not waive resource admission. - #[serde(default)] - pub allow_driver_config: bool, - /// Operator-owned external attachment approval policy. - #[serde(default)] - pub resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig, - pub grpc_endpoint: String, - /// OTLP exports passed to supervisors. The gateway supplies them from - /// `[otlp]`; driver TOML cannot set them. - #[serde(skip)] - pub supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, - /// Gateway name passed to supervisors for their telemetry. - pub supervisor_gateway_name: Option, - pub state_dir: PathBuf, - pub launcher_bin: Option, - pub default_image: String, - pub bootstrap_image: String, - /// Per-image byte limit for host extraction of registry bootstrap layers. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub bootstrap_extraction_max_bytes: Option, - pub log_level: String, - pub krun_log_level: u32, - pub vcpus: u8, - pub mem_mib: u32, - pub overlay_disk_mib: u64, - pub guest_tls_ca: Option, - pub guest_tls_cert: Option, - pub guest_tls_key: Option, - /// Gateway-owned, normalized destination-trust artifact path received on - /// the private gateway-to-driver argv. It is consumed exactly once during - /// driver initialization and then cleared. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub additional_ca_bundle: Option, - /// SHA-256 generation expected for `additional_ca_bundle`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub additional_ca_digest: Option, - /// Number of canonical certificate blocks expected in the artifact. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub additional_ca_certificate_count: Option, - /// Internal immutable trust state. Callers must leave this unset; it is - /// deliberately excluded from all serialized configuration input/output. - #[serde(skip)] - pub additional_ca_snapshot: Option, - /// Corporate forward proxy settings delivered to the host supervisor. - #[serde(flatten)] - pub upstream_proxy: UpstreamProxyConfig, - /// Policy DNS IPv6 egress mode and NAT64 prefixes for host control. - #[serde(flatten)] - pub ipv6_egress: openshell_core::SupervisorIpv6EgressConfig, - /// Gateway-host PEM CA bundle staged into the guest overlay for the - /// corporate proxy and TLS-intercepted server certificates. - pub proxy_ca_bundle: Option, - /// Guest-reachable SPIFFE Workload API TCP endpoint. A VM cannot safely - /// project a host UNIX socket; this must be a deliberately exposed TCP - /// listener and requires `provider_spiffe_allow_guest_tcp`. - pub provider_spiffe_workload_api_tcp_endpoint: Option, - #[serde(default)] - pub provider_spiffe_allow_guest_tcp: bool, - pub gpu_enabled: bool, - pub gpu_mem_mib: u32, - pub gpu_vcpus: u8, - /// Optional UID override for the sandbox account in newly prepared rootfs images. - /// When both identity fields are empty, an image-provided sandbox account is preserved. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub sandbox_uid: Option, - /// Optional GID override for rootfs `/etc/passwd` and `/etc/group` entries. - /// When one override is supplied, its missing counterpart defaults to the UID. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub sandbox_gid: Option, - - /// Directory where rootfs tar files must be staged before they can be - /// referenced in a `CreateSandbox` request. Defaults to `/rootfs-tar-staging`. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub rootfs_tar_staging_dir: Option, - /// Maximum rootfs tar file size in bytes. Defaults to 10 GiB. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub rootfs_tar_max_bytes: Option, - - #[serde(default)] - pub enable_bind_mounts: bool, -} - -/// Redacting `Debug` so a proxy URL or credential path never reaches a log. -/// -/// A validated proxy URL cannot embed credentials, but `Debug` can be emitted -/// before validation runs, so presence is logged rather than the value. -impl std::fmt::Debug for VmDriverConfig { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("VmDriverConfig") - .field("grpc_endpoint", &self.grpc_endpoint) - .field("supervisor_otlp", &self.supervisor_otlp) - .field("supervisor_gateway_name", &self.supervisor_gateway_name) - .field("state_dir", &self.state_dir) - .field("launcher_bin", &self.launcher_bin) - .field("default_image", &self.default_image) - .field("bootstrap_image", &self.bootstrap_image) - .field( - "bootstrap_extraction_max_bytes", - &self.bootstrap_extraction_max_bytes, - ) - .field("log_level", &self.log_level) - .field("krun_log_level", &self.krun_log_level) - .field("vcpus", &self.vcpus) - .field("mem_mib", &self.mem_mib) - .field("overlay_disk_mib", &self.overlay_disk_mib) - .field("guest_tls_ca", &self.guest_tls_ca) - .field("guest_tls_cert", &self.guest_tls_cert) - .field("guest_tls_key", &self.guest_tls_key) - .field( - "additional_ca_configured", - &(self.additional_ca_bundle.is_some() || self.additional_ca_snapshot.is_some()), - ) - .field("gpu_enabled", &self.gpu_enabled) - .field("gpu_mem_mib", &self.gpu_mem_mib) - .field("gpu_vcpus", &self.gpu_vcpus) - .field("sandbox_uid", &self.sandbox_uid) - .field("sandbox_gid", &self.sandbox_gid) - .field( - "upstream_proxy_configured", - &self.upstream_proxy.https_proxy.is_some(), - ) - .field( - "no_proxy_configured", - &self.upstream_proxy.no_proxy.is_some(), - ) - .field( - "proxy_auth_file_configured", - &self.upstream_proxy.proxy_auth_file.is_some(), - ) - .field( - "proxy_auth_allow_insecure", - &self.upstream_proxy.proxy_auth_allow_insecure, - ) - .field( - "proxy_connect_by_hostname", - &self.upstream_proxy.proxy_connect_by_hostname, - ) - .field( - "proxy_ca_bundle_configured", - &self.proxy_ca_bundle.is_some(), - ) - .field("ipv6_egress", &self.ipv6_egress) - .field( - "provider_spiffe_workload_api_tcp_endpoint_configured", - &self.provider_spiffe_workload_api_tcp_endpoint.is_some(), - ) - .field( - "provider_spiffe_allow_guest_tcp", - &self.provider_spiffe_allow_guest_tcp, - ) - .field("rootfs_tar_staging_dir", &self.rootfs_tar_staging_dir) - .field("rootfs_tar_max_bytes", &self.rootfs_tar_max_bytes) - .field("enable_bind_mounts", &self.enable_bind_mounts) - .finish() - } -} - -/// Fallback sandbox UID for images without a `sandbox` account and partial -/// operator identity overrides. -pub const DEFAULT_SANDBOX_UID: u32 = 1000; - -impl Default for VmDriverConfig { - fn default() -> Self { - Self { - grpc_endpoint: String::new(), - supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp::default(), - supervisor_gateway_name: None, - allow_driver_config: false, - resource_admission: - openshell_core::resource_admission::ResourceAdmissionConfig::default(), - state_dir: PathBuf::from("target/openshell-vm-driver"), - launcher_bin: None, - default_image: String::new(), - bootstrap_image: String::new(), - bootstrap_extraction_max_bytes: None, - log_level: "info".to_string(), - krun_log_level: 1, - vcpus: DEFAULT_VCPUS, - mem_mib: DEFAULT_MEM_MIB, - overlay_disk_mib: DEFAULT_OVERLAY_DISK_MIB, - guest_tls_ca: None, - guest_tls_cert: None, - guest_tls_key: None, - additional_ca_bundle: None, - additional_ca_digest: None, - additional_ca_certificate_count: None, - additional_ca_snapshot: None, - upstream_proxy: UpstreamProxyConfig::default(), - ipv6_egress: openshell_core::SupervisorIpv6EgressConfig::default(), - proxy_ca_bundle: None, - provider_spiffe_workload_api_tcp_endpoint: None, - provider_spiffe_allow_guest_tcp: false, - gpu_enabled: false, - gpu_mem_mib: 8192, - gpu_vcpus: 4, - sandbox_uid: None, - sandbox_gid: None, - rootfs_tar_staging_dir: None, - rootfs_tar_max_bytes: None, - enable_bind_mounts: false, - } - } -} - -impl VmDriverConfig { - /// Resolve a fallback sandbox UID for an image that has no sandbox account. - pub fn resolve_sandbox_uid(&self) -> u32 { - self.sandbox_uid.unwrap_or(DEFAULT_SANDBOX_UID) - } - - /// Resolve a fallback sandbox GID from the selected UID. - pub fn resolve_sandbox_gid(&self, resolved_uid: u32) -> u32 { - self.sandbox_gid.unwrap_or(resolved_uid) - } - - pub fn validate_runtime_security_config(&self) -> Result<(), String> { - self.upstream_proxy.validate()?; - self.ipv6_egress.validate()?; - if let Some(path) = self.proxy_ca_bundle.as_ref() { - if path.as_os_str().is_empty() { - return Err("proxy_ca_bundle must not be empty when set".to_string()); - } - if self.upstream_proxy.https_proxy.is_none() { - return Err("proxy_ca_bundle is set but no https_proxy is configured".to_string()); - } - } - if let Some(endpoint) = self.provider_spiffe_workload_api_tcp_endpoint.as_deref() { - openshell_core::driver_utils::validate_guest_spiffe_tcp_endpoint( - endpoint, - self.provider_spiffe_allow_guest_tcp, - )?; - } else if self.provider_spiffe_allow_guest_tcp { - return Err("provider_spiffe_allow_guest_tcp is set but no provider_spiffe_workload_api_tcp_endpoint is configured".to_string()); - } - Ok(()) - } - - pub fn validate_bootstrap_image_config(&self) -> Result<(), String> { - if self.bootstrap_image.trim().is_empty() && self.default_image.trim().is_empty() { - return Err( - "vm driver requires bootstrap_image or default_image; the sandbox image cannot be used as the VM bootstrap image" - .to_string(), - ); - } - Ok(()) - } - - pub fn validate_rootfs_tar_config(&self) -> Result<(), String> { - if self - .rootfs_tar_staging_dir - .as_ref() - .is_some_and(|path| path.as_os_str().is_empty()) - { - return Err("rootfs_tar_staging_dir must not be empty when set".to_string()); - } - if self.rootfs_tar_max_bytes == Some(0) { - return Err("rootfs_tar_max_bytes must be greater than zero when set".to_string()); - } - Ok(()) - } - - pub fn validate_sandbox_identity(&self) -> Result<(), String> { - let range = openshell_policy::MIN_SANDBOX_UID..=openshell_policy::MAX_SANDBOX_UID; - if let Some(uid) = self.sandbox_uid - && !range.contains(&uid) - { - return Err(format!( - "sandbox_uid {uid} is outside the allowed range [{}, {}]", - openshell_policy::MIN_SANDBOX_UID, - openshell_policy::MAX_SANDBOX_UID, - )); - } - if let Some(gid) = self.sandbox_gid - && !range.contains(&gid) - { - return Err(format!( - "sandbox_gid {gid} is outside the allowed range [{}, {}]", - openshell_policy::MIN_SANDBOX_UID, - openshell_policy::MAX_SANDBOX_UID, - )); - } - Ok(()) - } - - fn rootfs_tar_staging_dir(&self) -> PathBuf { - self.rootfs_tar_staging_dir - .clone() - .unwrap_or_else(|| self.state_dir.join(ROOTFS_TAR_STAGING_DIR)) - } - - fn rootfs_tar_max_bytes(&self) -> u64 { - self.rootfs_tar_max_bytes - .unwrap_or(DEFAULT_ROOTFS_TAR_MAX_BYTES) - } - - fn requires_tls_materials(&self) -> bool { - self.grpc_endpoint.starts_with("https://") - } - - fn tls_paths(&self) -> Result, String> { - if self.guest_tls_cert.is_some() || self.guest_tls_key.is_some() { - return Err( - "sandbox client certificates are no longer supported; remove OPENSHELL_VM_TLS_CERT and OPENSHELL_VM_TLS_KEY" - .to_string(), - ); - } - if self.guest_tls_ca.is_none() { - return if self.requires_tls_materials() { - Err( - "https:// openshell endpoint requires OPENSHELL_VM_TLS_CA so the host supervisor can authenticate the gateway" - .to_string(), - ) - } else { - Ok(None) - }; - } - - let Some(ca) = self.guest_tls_ca.clone() else { - return Err( - "OPENSHELL_VM_TLS_CA is required when TLS materials are configured".to_string(), - ); - }; - for path in [&ca] { - if !path.is_file() { - return Err(format!( - "TLS material '{}' does not exist or is not a file", - path.display() - )); - } - } - - Ok(Some(VmDriverTlsPaths { ca })) - } -} - -/// Consume the gateway's private launch metadata and retain only a -/// driver-owned immutable trust snapshot. -/// -/// The standalone VM driver cannot receive the bundle bytes over the gateway -/// RPC, so the in-process gateway passes a path, digest, and count on its -/// authenticated child-process argv. Treat those three values as one atomic -/// contract: accepting a partial set would make it possible to read a mutable -/// path without an authenticated generation or to silently lose a trust -/// anchor. The source is read only here; launches use the resulting bytes and -/// never re-open the gateway artifact. -fn initialize_additional_ca_snapshot(config: &mut VmDriverConfig) -> Result<(), String> { - if config.additional_ca_snapshot.is_some() { - return Err( - "additional CA snapshot is driver-owned and must not be supplied by callers" - .to_string(), - ); - } - - let snapshot = match ( - config.additional_ca_bundle.as_ref(), - config.additional_ca_digest.as_deref(), - config.additional_ca_certificate_count, - ) { - (None, None, None) => None, - (Some(path), Some(expected_digest), Some(expected_certificate_count)) => { - if path.as_os_str().is_empty() { - return Err("additional CA artifact path must not be empty".to_string()); - } - if expected_certificate_count == 0 { - return Err("additional CA certificate count must be greater than zero".to_string()); - } - let expected_digest = normalized_additional_ca_digest(expected_digest)?; - let pem = read_gateway_additional_ca_artifact(path)?; - // Deterministic destination-trust generation label, not an - // authenticity proof: the equality check below only detects - // staged-artifact drift; trust comes from the gateway's - // normalization and TLS verification. Classified as a non-security - // identity hash in openshell-crypto/README.md. - let actual_digest = format!("sha256:{:x}", Sha256::digest(&pem)); - if actual_digest != expected_digest { - return Err(format!( - "additional CA artifact '{}' does not match expected digest {}", - path.display(), - expected_digest - )); - } - let actual_certificate_count = normalized_additional_ca_certificate_count(&pem) - .map_err(|error| { - format!( - "additional CA artifact '{}' is not a normalized certificate bundle: {error}", - path.display() - ) - })?; - if actual_certificate_count != expected_certificate_count { - return Err(format!( - "additional CA artifact '{}' has certificate count {}, expected {}", - path.display(), - actual_certificate_count, - expected_certificate_count - )); - } - Some(VmNetworkSupervisorTrustSnapshot { - // The bundle's artifact path records provenance only. Never - // call `verify_artifact` on this retained value: all later - // launches must use these captured immutable bytes rather - // than rereading the mutable gateway-host source path. - bundle: NetworkSupervisorTrustBundle::new( - pem, - actual_certificate_count, - expected_digest, - path.clone(), - ), - }) - } - _ => { - return Err( - "additional CA artifact path, digest, and certificate count must be supplied together" - .to_string(), - ); - } - }; - - // Do not retain the mutable gateway artifact path or metadata after the - // authenticated, bounded startup read. In particular this makes a later - // sandbox launch incapable of accidentally rereading it. - config.additional_ca_bundle = None; - config.additional_ca_digest = None; - config.additional_ca_certificate_count = None; - config.additional_ca_snapshot = snapshot; - Ok(()) -} - -/// Require the generation form emitted by gateway normalization. -fn normalized_additional_ca_digest(digest: &str) -> Result { - let Some(hex) = digest.strip_prefix("sha256:") else { - return Err("additional CA digest must use the sha256: prefix".to_string()); - }; - if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { - return Err("additional CA digest must be a SHA-256 digest".to_string()); - } - if hex.bytes().any(|byte| byte.is_ascii_uppercase()) { - return Err("additional CA digest must use normalized lowercase hexadecimal".to_string()); - } - Ok(format!("sha256:{hex}")) -} - -/// Read a normalized gateway artifact once without following symlinks. -fn read_gateway_additional_ca_artifact(path: &Path) -> Result, String> { - let metadata = fs::symlink_metadata(path).map_err(|error| { - format!( - "inspect additional CA artifact '{}': {error}", - path.display() - ) - })?; - if !metadata.file_type().is_file() { - return Err(format!( - "additional CA artifact '{}' is not a regular file", - path.display() - )); - } - validate_gateway_additional_ca_artifact_metadata(path, &metadata)?; - - let mut options = fs::OpenOptions::new(); - options.read(true); - #[cfg(unix)] - { - // The pre-open metadata check gives portable diagnostics, while these - // flags ensure an attacker cannot replace it with a symlink, FIFO, or - // blocking special file before the actual one-time read. - options.custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK); - } - let mut file = options - .open(path) - .map_err(|error| format!("open additional CA artifact '{}': {error}", path.display()))?; - let opened_metadata = file.metadata().map_err(|error| { - format!( - "inspect additional CA artifact '{}': {error}", - path.display() - ) - })?; - if !opened_metadata.file_type().is_file() { - return Err(format!( - "additional CA artifact '{}' is not a regular file", - path.display() - )); - } - validate_gateway_additional_ca_artifact_metadata(path, &opened_metadata)?; - - let capacity = usize::try_from(opened_metadata.len()).map_err(|_| { - format!( - "additional CA artifact '{}' exceeds the {}-byte limit", - path.display(), - MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES - ) - })?; - let mut pem = Vec::with_capacity(capacity); - Read::by_ref(&mut file) - .take((MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES + 1) as u64) - .read_to_end(&mut pem) - .map_err(|error| format!("read additional CA artifact '{}': {error}", path.display()))?; - if pem.len() > MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES { - return Err(format!( - "additional CA artifact '{}' exceeds the {}-byte limit", - path.display(), - MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES - )); - } - Ok(pem) -} - -fn validate_gateway_additional_ca_artifact_metadata( - path: &Path, - metadata: &fs::Metadata, -) -> Result<(), String> { - if metadata.len() > MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES as u64 { - return Err(format!( - "additional CA artifact '{}' exceeds the {}-byte limit", - path.display(), - MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES - )); - } - #[cfg(unix)] - if metadata.permissions().mode() & 0o7777 != 0o444 { - return Err(format!( - "additional CA artifact '{}' does not have the required read-only permissions", - path.display() - )); - } - Ok(()) -} - -/// Verify that the bytes are exactly the canonical PEM representation emitted -/// by the gateway's destination-trust normalization boundary, and return its -/// number of certificate blocks. -fn normalized_additional_ca_certificate_count(pem: &[u8]) -> Result { - let text = std::str::from_utf8(pem).map_err(|_| "bundle is not UTF-8 PEM text")?; - let mut remainder = text; - let mut normalized = Vec::with_capacity(pem.len()); - let mut certificate_count = 0_usize; - - while !remainder.is_empty() { - let Some(after_begin) = remainder.strip_prefix("-----BEGIN CERTIFICATE-----\n") else { - return Err("bundle contains material outside canonical certificate blocks"); - }; - remainder = after_begin; - let mut encoded = String::new(); - loop { - let Some(newline) = remainder.find('\n') else { - return Err("certificate block is missing its terminating newline"); - }; - let line = &remainder[..newline]; - remainder = &remainder[newline + 1..]; - if line == "-----END CERTIFICATE-----" { - break; - } - if line.is_empty() || line.len() > 64 { - return Err("certificate block has a non-canonical base64 line"); - } - encoded.push_str(line); - } - let decoded = BASE64_STANDARD - .decode(encoded.as_bytes()) - .map_err(|_| "certificate block contains invalid base64")?; - if decoded.is_empty() { - return Err("certificate block is empty"); - } - normalized.extend_from_slice(b"-----BEGIN CERTIFICATE-----\n"); - let canonical = BASE64_STANDARD.encode(decoded); - for line in canonical.as_bytes().chunks(64) { - normalized.extend_from_slice(line); - normalized.push(b'\n'); - } - normalized.extend_from_slice(b"-----END CERTIFICATE-----\n"); - certificate_count += 1; - } - - if certificate_count == 0 { - return Err("bundle contains no certificate blocks"); - } - if normalized != pem { - return Err("bundle is not canonical normalized PEM"); - } - Ok(certificate_count) -} - -/// Write or remove the host-only per-sandbox trust artifact. -/// -/// The snapshot has already authenticated the bytes against the gateway's -/// generation. Do not replace this with a source-path copy: re-opening that -/// path here would let a changed gateway artifact alter later sandbox -/// launches. The temporary file is created with restrictive permissions and -/// atomically published into the sandbox's private state directory. -fn stage_additional_ca_snapshot( - state_dir: &Path, - snapshot: Option<&VmNetworkSupervisorTrustSnapshot>, -) -> Result, String> { - let destination = state_dir.join(HOST_ADDITIONAL_CA_FILE); - let Some(snapshot) = snapshot else { - remove_additional_ca_material(state_dir, &destination)?; - return Ok(None); - }; - - let temporary = state_dir.join(format!( - "{HOST_ADDITIONAL_CA_TEMP_PREFIX}{}-{}{}", - std::process::id(), - NETWORK_TRUST_WRITE_COUNTER.fetch_add(1, Ordering::Relaxed), - HOST_ADDITIONAL_CA_TEMP_SUFFIX, - )); - let result: Result<(), String> = (|| { - let mut options = fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - options.mode(0o600); - let mut file = options - .open(&temporary) - .map_err(|error| format!("create host additional CA temporary file: {error}"))?; - file.write_all(snapshot.normalized_pem()) - .map_err(|error| format!("write host additional CA temporary file: {error}"))?; - file.sync_all() - .map_err(|error| format!("sync host additional CA temporary file: {error}"))?; - #[cfg(unix)] - fs::set_permissions(&temporary, fs::Permissions::from_mode(0o600)) - .map_err(|error| format!("restrict host additional CA temporary file: {error}"))?; - fs::rename(&temporary, &destination) - .map_err(|error| format!("publish host additional CA file: {error}"))?; - fs::File::open(state_dir) - .and_then(|directory| directory.sync_all()) - .map_err(|error| format!("sync host additional CA directory: {error}"))?; - Ok(()) - })(); - if result.is_err() { - let _ = fs::remove_file(&temporary); - } - result?; - Ok(Some(destination)) -} - -/// Remove both the published host artifact and interrupted-write remnants. -fn remove_additional_ca_material(state_dir: &Path, destination: &Path) -> Result<(), String> { - remove_additional_ca_file(destination)?; - let entries = fs::read_dir(state_dir) - .map_err(|error| format!("read sandbox state while clearing additional CA: {error}"))?; - for entry in entries { - let entry = entry.map_err(|error| { - format!("read sandbox state entry while clearing additional CA: {error}") - })?; - let name = entry.file_name(); - let name = name.to_string_lossy(); - if name.starts_with(HOST_ADDITIONAL_CA_TEMP_PREFIX) - && name.ends_with(HOST_ADDITIONAL_CA_TEMP_SUFFIX) - { - remove_additional_ca_file(&entry.path())?; - } - } - Ok(()) -} - -fn remove_additional_ca_file(path: &Path) -> Result<(), String> { - match fs::remove_file(path) { - Ok(()) => Ok(()), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(error) => Err(format!( - "remove host additional CA file '{}': {error}", - path.display() - )), - } -} - -/// Render the host-supervisor-only arguments for a staged trust snapshot. -/// -/// PEM bytes never appear in argv. The supervisor receives only the -/// restrictive host file path and gateway-authenticated generation digest. -fn additional_ca_supervisor_args( - snapshot: Option<&VmNetworkSupervisorTrustSnapshot>, - staged_path: Option<&Path>, -) -> Result, String> { - match (snapshot, staged_path) { - (None, None) => Ok(Vec::new()), - (Some(_snapshot), Some(path)) => Ok(vec![ - "--additional-ca-bundle".to_string(), - path.display().to_string(), - ]), - (Some(_), None) => Err("additional CA snapshot was not staged".to_string()), - (None, Some(_)) => Err("staged additional CA exists without a snapshot".to_string()), - } -} - -fn validate_openshell_endpoint(endpoint: &str) -> Result<(), String> { - let url = Url::parse(endpoint) - .map_err(|err| format!("invalid openshell endpoint '{endpoint}': {err}"))?; - let Some(host) = url.host() else { - return Err(format!("openshell endpoint '{endpoint}' is missing a host")); - }; - - let invalid_from_vm = match host { - Host::Domain(_) => false, - Host::Ipv4(ip) => ip.is_unspecified(), - Host::Ipv6(ip) => ip.is_unspecified(), - }; - - if invalid_from_vm { - return Err(format!( - "openshell endpoint '{endpoint}' is not reachable from sandbox VMs; use a concrete host such as 127.0.0.1, {OPENSHELL_HOST_GATEWAY_ALIAS}, or another routable address" - )); - } - - Ok(()) -} - -fn host_control_openshell_endpoint(endpoint: &str) -> Result<(String, Option), String> { - let mut url = Url::parse(endpoint) - .map_err(|err| format!("invalid openshell endpoint '{endpoint}': {err}"))?; - let Some(host) = url.host_str().map(str::to_string) else { - return Ok((endpoint.to_string(), None)); - }; - if !HOST_LOOPBACK_ALIASES.contains(&host.as_str()) { - return Ok((endpoint.to_string(), None)); - } - - // The supervisor runs on the host, so guest aliases dial loopback while - // retaining the configured hostname for TLS certificate verification. - url.set_host(Some("127.0.0.1")) - .map_err(|error| format!("failed to rewrite host endpoint '{endpoint}': {error}"))?; - Ok((url.into(), Some(host))) -} - -#[derive(Debug)] -struct VmProcess { - child: Child, - supervisor: Child, - supervisor_liveness: Option, - deleting: bool, -} - -struct SandboxRecord { - snapshot: Sandbox, - state_dir: PathBuf, - process: Option>>, - provisioning_task: Option>, - preparation: Option>>, - gpu_bdf: Option, - deleting: bool, -} - -/// Resolve a lifecycle request to a registry key. -/// -/// A non-empty `sandbox_id` is authoritative: resolution uses that id alone and -/// never falls back to the name, so a request for an already-removed sandbox -/// reports absence instead of matching a same-named sandbox in another -/// workspace. Only a caller that supplies no id resolves by name, and because -/// sandbox names are unique per workspace rather than globally, a name matching -/// more than one record is rejected instead of decided by iteration order. -fn resolve_record_id( - registry: &HashMap, - sandbox_id: &str, - sandbox_name: &str, -) -> Result, Status> { - if !sandbox_id.is_empty() { - return Ok(registry.get_key_value(sandbox_id).map(|(id, _)| id.clone())); - } - - let mut matches = registry - .iter() - .filter(|(_, record)| record.snapshot.name == sandbox_name); - let first = matches.next().map(|(id, _)| id.clone()); - if matches.next().is_some() { - return Err(Status::failed_precondition(format!( - "sandbox_name {sandbox_name} matched more than one sandbox; supply sandbox_id" - ))); - } - Ok(first) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -enum OverlayPreparation { - Fresh, - PreserveExisting, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -struct SandboxOwnerIdentity { - uid: u32, - gid: u32, -} - -impl SandboxOwnerIdentity { - fn guest_environment(self) -> [String; 2] { - [ - format!("OPENSHELL_VM_SANDBOX_UID={}", self.uid), - format!("OPENSHELL_VM_SANDBOX_GID={}", self.gid), - ] - } - - fn marker_contents(self) -> String { - format!("{SANDBOX_OWNER_STATE_V2}:{}:{}\n", self.uid, self.gid) - } -} - -fn provisioning_span( - parent: &opentelemetry::Context, - sandbox_id: &str, - image_ref: &str, -) -> tracing::Span { - let span = tracing::info_span!( - parent: None, - "vm.provision", - otel.name = "vm.provision", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - image.ref = %image_ref, - ); - let parent_span_context = parent.span().span_context().clone(); - if parent_span_context.is_valid() { - let parent = opentelemetry::Context::new().with_remote_span_context(parent_span_context); - let _ = span.set_parent(parent); - } - span -} - -#[derive(Clone)] -pub struct VmDriver { - config: VmDriverConfig, - socket_root: PathBuf, - socket_root_fd: Arc, - launcher_bin: PathBuf, - registry: Arc>>, - image_cache_lock: Arc>, - preparation_root: Option, - events: broadcast::Sender, - gpu_inventory: Option>>, - lifecycle_extensions: Arc, -} - -impl VmDriver { - pub async fn new(config: VmDriverConfig) -> Result { - Self::new_with_extensions(config, LifecycleExtensionRegistry::new()).await - } - - pub async fn new_with_extensions( - mut config: VmDriverConfig, - lifecycle_extensions: LifecycleExtensionRegistry, - ) -> Result { - config.resource_admission.validate()?; - lifecycle_extensions - .validate() - .map_err(|err| err.message().to_string())?; - config.validate_sandbox_identity()?; - config.validate_runtime_security_config()?; - config.validate_bootstrap_image_config()?; - config.validate_rootfs_tar_config()?; - if config.grpc_endpoint.trim().is_empty() { - return Err("openshell endpoint is required".to_string()); - } - validate_openshell_endpoint(&config.grpc_endpoint)?; - let _ = config.tls_paths()?; - initialize_additional_ca_snapshot(&mut config)?; - config.state_dir = absolute_state_dir(&config.state_dir)?; - - #[cfg(target_os = "linux")] - if config.gpu_enabled { - check_gpu_privileges()?; - } - - let state_root = sandboxes_root_dir(&config.state_dir); - create_private_dir_all(&state_root).await.map_err(|err| { - format!( - "failed to create state dir '{}': {err}", - state_root.display() - ) - })?; - let image_cache_root = image_cache_root_dir(&config.state_dir); - create_private_dir_all(&image_cache_root) - .await - .map_err(|err| { - format!( - "failed to create state dir '{}': {err}", - image_cache_root.display() - ) - })?; - let staging_dir = config.rootfs_tar_staging_dir(); - create_private_dir_all(&staging_dir).await.map_err(|err| { - format!( - "failed to create rootfs tar staging dir '{}': {err}", - staging_dir.display() - ) - })?; - - let launcher_bin = if let Some(path) = config.launcher_bin.clone() { - path - } else { - std::env::current_exe() - .map_err(|err| format!("failed to resolve vm driver executable: {err}"))? - }; - - let gpu_inventory = if config.gpu_enabled { - let sysfs = SysfsRoot::system(); - let inventory = GpuInventory::new(sysfs, &config.state_dir); - tracing::info!( - gpu_count = inventory.gpu_count(), - "GPU inventory initialized" - ); - Some(Arc::new(std::sync::Mutex::new(inventory))) - } else { - None - }; - - let (socket_root, socket_root_fd) = allocate_socket_root() - .map_err(|err| format!("failed to allocate socket root in /tmp: {err}"))?; - - let (events, _) = broadcast::channel(WATCH_BUFFER); - let driver = Self { - config, - socket_root, - socket_root_fd: Arc::new(socket_root_fd), - launcher_bin, - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events, - gpu_inventory, - lifecycle_extensions: Arc::new(lifecycle_extensions), - }; - preparation::reconcile(&image_cache_root_dir(&driver.config.state_dir)) - .map_err(|error| format!("reconcile image preparation staging: {error}"))?; - driver.restore_persisted_sandboxes().await; - Ok(driver) - } - - async fn validate_rootfs_tar_path(&self, raw: &Path) -> Result { - let staging_dir = self.config.rootfs_tar_staging_dir(); - let canonical_staging = tokio::fs::canonicalize(&staging_dir).await.map_err(|err| { - Status::internal(format!( - "rootfs tar staging dir not accessible at {}: {err}", - staging_dir.display() - )) - })?; - - let canonical = tokio::fs::canonicalize(raw).await.map_err(|err| { - Status::failed_precondition(format!( - "rootfs tar path not accessible at {}: {err}", - raw.display() - )) - })?; - - if !canonical.starts_with(&canonical_staging) { - return Err(Status::permission_denied(format!( - "rootfs tar path {} is outside the staging directory {}", - canonical.display(), - canonical_staging.display() - ))); - } - - let relative = canonical.strip_prefix(&canonical_staging).unwrap(); - let depth = relative.components().count(); - if depth != 2 { - return Err(Status::permission_denied(format!( - "rootfs tar path {} must be inside a request subdirectory of the staging root", - canonical.display(), - ))); - } - - let metadata = tokio::fs::symlink_metadata(&canonical) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "rootfs tar not accessible at {}: {err}", - canonical.display() - )) - })?; - if !metadata.file_type().is_file() { - return Err(Status::invalid_argument(format!( - "rootfs tar path {} is not a regular file", - canonical.display() - ))); - } - - let max_bytes = self.config.rootfs_tar_max_bytes(); - let file_size = metadata.len(); - if file_size > max_bytes { - return Err(Status::invalid_argument(format!( - "rootfs tar {} is {} bytes, exceeding the {} byte limit", - canonical.display(), - file_size, - max_bytes - ))); - } - - Ok(canonical) - } - - async fn host_supervisor_binary(&self) -> Result { - if let Some(configured) = std::env::var_os("OPENSHELL_VM_SUPERVISOR_BIN") { - let configured = PathBuf::from(configured); - if configured.is_file() { - return Ok(configured); - } - return Err(Status::failed_precondition(format!( - "configured host supervisor does not exist: {}", - configured.display() - ))); - } - - let destination = self.config.state_dir.join(HOST_SUPERVISOR_BINARY); - if validate_host_supervisor(&destination).is_ok() { - return Ok(destination); - } - let cache_guard = self.image_cache_lock.clone().lock_owned().await; - if validate_host_supervisor(&destination).is_ok() { - return Ok(destination); - } - let destination_for_extract = destination.clone(); - tokio::task::spawn_blocking(move || { - // This atomic shared-cache write does not target sandbox state. - // Retain its lock until the write finishes even if provisioning is - // cancelled, so a later caller cannot start a competing extractor. - let _cache_guard = cache_guard; - extract_host_supervisor(&destination_for_extract) - }) - .await - .map_err(|error| Status::internal(format!("host supervisor extraction panicked: {error}")))? - .map_err(Status::failed_precondition)?; - validate_host_supervisor(&destination).map_err(Status::failed_precondition)?; - Ok(destination) - } - - /// Stage the captured destination trust into this sandbox's host-only - /// state directory. This intentionally happens per launch so stopped - /// sandboxes do not carry a stale source generation into a later host - /// supervisor process. - async fn stage_additional_ca_for_sandbox( - &self, - state_dir: &Path, - ) -> Result, Status> { - let state_dir = state_dir.to_path_buf(); - let snapshot = self.config.additional_ca_snapshot.clone(); - tokio::task::spawn_blocking(move || { - stage_additional_ca_snapshot(&state_dir, snapshot.as_ref()) - }) - .await - .map_err(|error| Status::internal(format!("stage additional CA task panicked: {error}")))? - .map_err(|error| Status::internal(format!("stage host additional CA: {error}"))) - } - - async fn spawn_host_supervisor( - &self, - sandbox: &Sandbox, - state_dir: &Path, - tls_paths: Option<&VmDriverTlsPaths>, - runtime_descriptor: &SandboxRuntimeDescriptor, - auth_bundle: &openshell_core::jwt::SupervisorAuthBundle, - sandbox_owner: SandboxOwnerIdentity, - ) -> Result<(Child, Option), Status> { - // The destination CA is staged on the host before either resolving - // the supervisor binary or spawning it. It never crosses into a VM - // disk or a guest environment. - let staged_network_trust = self.stage_additional_ca_for_sandbox(state_dir).await?; - let network_trust_args = additional_ca_supervisor_args( - self.config.additional_ca_snapshot.as_ref(), - staged_network_trust.as_deref(), - ) - .map_err(Status::internal)?; - let supervisor_binary = self.host_supervisor_binary().await?; - let (openshell_endpoint, gateway_tls_server_name) = - host_control_openshell_endpoint(&self.config.grpc_endpoint) - .map_err(Status::failed_precondition)?; - let auth_bundle_path = state_dir.join(HOST_AUTH_BUNDLE_FILE); - let encoded_auth_bundle = serde_json::to_vec(auth_bundle) - .map_err(|error| Status::internal(format!("encode supervisor auth bundle: {error}")))?; - tokio::fs::write(&auth_bundle_path, encoded_auth_bundle) - .await - .map_err(|error| Status::internal(format!("write supervisor auth bundle: {error}")))?; - #[cfg(unix)] - tokio::fs::set_permissions(&auth_bundle_path, fs::Permissions::from_mode(0o600)) - .await - .map_err(|error| { - Status::internal(format!("restrict supervisor auth bundle: {error}")) - })?; - - let descriptor = runtime_descriptor - .backend_descriptor() - .map_err(|error| Status::internal(error.to_string()))?; - // The payload carries the boundary bootstrap token, so it must not - // appear in the world-readable process cmdline; deliver it through a - // driver-owned 0600 file like the gateway token. - let payload_path = state_dir.join(HOST_RUNTIME_DESCRIPTOR_FILE); - tokio::fs::write(&payload_path, &descriptor.payload) - .await - .map_err(|error| Status::internal(format!("write host runtime descriptor: {error}")))?; - #[cfg(unix)] - tokio::fs::set_permissions(&payload_path, fs::Permissions::from_mode(0o600)) - .await - .map_err(|error| { - Status::internal(format!("restrict host runtime descriptor: {error}")) - })?; - let main_process_spec = openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec( - sandbox.spec.as_ref(), - ) - .map_err(|error| Status::internal(format!("encode main process spec: {error}")))?; - let upstream_proxy_args = upstream_proxy_cli_args(&self.config) - .map_err(|error| Status::invalid_argument(format!("render upstream proxy: {error}")))?; - let mut command = Command::new(&supervisor_binary); - isolate_host_control_environment(&mut command); - command - .kill_on_drop(true) - .stdin(Stdio::null()) - .stdout(Stdio::from( - fs::File::create(state_dir.join("supervisor.log")) - .map_err(|error| Status::internal(format!("create supervisor log: {error}")))?, - )) - .stderr(Stdio::from( - fs::File::create(state_dir.join("supervisor.err.log")).map_err(|error| { - Status::internal(format!("create supervisor error log: {error}")) - })?, - )) - .arg("--backend-descriptor-file") - .arg(&payload_path) - .arg("--auth-bundle-file") - .arg(&auth_bundle_path) - .arg("--workdir") - .arg("/sandbox") - .args(upstream_proxy_args) - .args(network_trust_args) - .args(self.config.ipv6_egress.supervisor_args()) - .env( - openshell_core::sandbox_env::ADMITTED_ISOLATION_BACKEND, - DRIVER_ADMITTED_BACKEND, - ) - .env( - openshell_core::sandbox_env::MAIN_PROCESS_SPEC, - main_process_spec, - ) - .env(openshell_core::sandbox_env::ENDPOINT, openshell_endpoint) - .env(openshell_core::sandbox_env::SANDBOX_ID, &sandbox.id) - .env(openshell_core::sandbox_env::SANDBOX, &sandbox.name) - .env( - openshell_core::sandbox_env::SSH_SOCKET_PATH, - sandbox_socket_dir(&self.socket_root, &sandbox.id).join("ssh.sock"), - ) - .env( - openshell_core::sandbox_env::PROXY_TLS_DIR, - state_dir.join("proxy-tls"), - ) - .env( - openshell_core::sandbox_env::SANDBOX_UID, - sandbox_owner.uid.to_string(), - ) - .env( - openshell_core::sandbox_env::SANDBOX_GID, - sandbox_owner.gid.to_string(), - ) - .env(openshell_core::sandbox_env::OCI_IMAGE_USER, "") - .env( - openshell_core::sandbox_env::LOG_LEVEL, - openshell_core::driver_utils::sandbox_log_level(sandbox, &self.config.log_level), - ) - .env( - openshell_core::sandbox_env::TELEMETRY_ENABLED, - openshell_core::telemetry::enabled_env_value(), - ); - command.envs(supervisor_otlp_environment(&self.config)); - if let Some(server_name) = gateway_tls_server_name { - command.env( - openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME, - server_name, - ); - } - configure_main_exit_marker(&mut command, state_dir); - if let Some(tls) = tls_paths { - command.env(openshell_core::sandbox_env::TLS_CA, &tls.ca); - } - #[cfg(unix)] - let (liveness_read, liveness_write) = nix::unistd::pipe().map_err(|error| { - Status::internal(format!("create supervisor parent-liveness pipe: {error}")) - })?; - #[cfg(unix)] - for fd in [&liveness_read, &liveness_write] { - nix::fcntl::fcntl( - fd.as_raw_fd(), - nix::fcntl::FcntlArg::F_SETFD(nix::fcntl::FdFlag::FD_CLOEXEC), - ) - .map_err(|error| { - Status::internal(format!( - "protect supervisor parent-liveness descriptor: {error}" - )) - })?; - } - #[cfg(unix)] - command - .stdin(Stdio::from(liveness_read)) - .arg("--parent-liveness-stdin"); - #[cfg(unix)] - unsafe { - command.pre_exec(move || { - #[cfg(target_os = "linux")] - nix::sys::prctl::set_pdeathsig(Signal::SIGKILL).map_err(std::io::Error::other)?; - Ok(()) - }); - } - let child = command.spawn().map_err(|error| { - Status::internal(format!( - "start host supervisor '{}': {error}", - supervisor_binary.display() - )) - })?; - #[cfg(unix)] - { - Ok((child, Some(fs::File::from(liveness_write)))) - } - #[cfg(not(unix))] - Ok((child, None)) - } - - #[must_use] - pub fn capabilities(&self) -> GetCapabilitiesResponse { - let mut extension = openshell_core::extension_protocol::extension_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - "openshell/vm", - openshell_core::VERSION, - [], - ); - extension - .required_capabilities - .push(openshell_core::extension_protocol::COMPUTE_LAUNCH_AUTHENTICATION.to_string()); - GetCapabilitiesResponse { - resource_admission_policy: openshell_core::resource_admission::DriverAdmissionConfig { - allow_driver_config: self.config.allow_driver_config, - resource_admission: self.config.resource_admission.clone(), - } - .acknowledgement(), - driver_name: DRIVER_NAME.to_string(), - driver_version: openshell_core::VERSION.to_string(), - default_image: self.config.default_image.clone(), - gateway_manages_lifecycle: true, - supports_sandbox_authentication: false, - driver_reports_runtime_readiness: false, - resource_capabilities: Some(ResourceCapabilities { - cpu: Some(CpuResourceCapabilities { - limit_supported: false, - }), - memory: Some(MemoryResourceCapabilities { - limit_supported: false, - }), - gpu: Some(GpuResourceCapabilities { - default_selection_supported: self.config.gpu_enabled, - count_selection_supported: self.config.gpu_enabled, - }), - }), - rootfs_tar_staging_dir: self - .config - .rootfs_tar_staging_dir() - .to_string_lossy() - .into_owned(), - rootfs_tar_max_bytes: self.config.rootfs_tar_max_bytes(), - extension: Some(extension), - } - } - - // `tonic::Status` is large but is the standard error type across the - // gRPC API surface; boxing here would diverge from every other handler. - #[allow(clippy::result_large_err)] - pub fn validate_sandbox(&self, sandbox: &Sandbox) -> Result<(), Status> { - openshell_core::resource_admission::check_sandbox_driver_config( - self.config.allow_driver_config, - sandbox, - )?; - validate_vm_sandbox(sandbox, self.config.gpu_enabled)?; - let driver_config = - VmSandboxDriverConfig::from_sandbox(sandbox).map_err(Status::invalid_argument)?; - validate_vm_driver_mounts( - &driver_config.mounts, - &self.config, - sandbox_requests_gpu(sandbox), - )?; - let has_rootfs_tar = driver_config.rootfs_tar_path.is_some(); - if self.resolved_sandbox_image(sandbox).is_none() && !has_rootfs_tar { - return Err(Status::failed_precondition( - "vm sandboxes require template.image, rootfs_tar_path in driver_config, or a configured default sandbox image", - )); - } - Ok(()) - } - - // `tonic::Status` is large but is the standard error type across the - // gRPC API surface; boxing here would diverge from every other handler. - #[allow(clippy::result_large_err)] - pub async fn create_sandbox(&self, sandbox: &Sandbox) -> Result { - self.validate_sandbox(sandbox)?; - decode_launch_authentication( - sandbox - .spec - .as_ref() - .map_or(&[], |spec| spec.launch_authentication.as_slice()), - )?; - info!( - sandbox_id = %sandbox.id, - sandbox_name = %sandbox.name, - "vm driver: create_sandbox received" - ); - validate_vm_sandbox(sandbox, self.config.gpu_enabled)?; - - let state_dir = sandbox_state_dir(&self.config.state_dir, &sandbox.id)?; - let has_rootfs_tar = - VmSandboxDriverConfig::from_sandbox(sandbox).is_ok_and(|c| c.rootfs_tar_path.is_some()); - let image_ref = self - .resolved_sandbox_image(sandbox) - .or_else(|| { - has_rootfs_tar - .then(|| self.bootstrap_image_ref_default()) - .flatten() - }) - .ok_or_else(|| { - Status::failed_precondition( - "vm sandboxes require template.image, rootfs_tar_path in driver_config, or a configured default sandbox image", - ) - })?; - info!( - sandbox_id = %sandbox.id, - image_ref = %image_ref, - state_dir = %state_dir.display(), - "vm driver: resolved image ref, preparing disks" - ); - - let snapshot = sandbox_snapshot(sandbox, provisioning_condition(), false); - { - let mut registry = self.registry.lock().await; - if registry.contains_key(&sandbox.id) { - return Err(Status::already_exists("sandbox already exists")); - } - registry.insert( - sandbox.id.clone(), - SandboxRecord { - snapshot: snapshot.clone(), - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - } - - let tls_paths = match self.config.tls_paths() { - Ok(paths) => paths, - Err(err) => { - let mut registry = self.registry.lock().await; - registry.remove(&sandbox.id); - return Err(Status::failed_precondition(err)); - } - }; - - if let Err(err) = create_private_dir_all(&state_dir).await { - let mut registry = self.registry.lock().await; - registry.remove(&sandbox.id); - return Err(Status::internal(format!("create state dir failed: {err}"))); - } - - if let Err(err) = - create_sandbox_socket_dir(&self.socket_root_fd, &self.socket_root, &sandbox.id) - { - let mut registry = self.registry.lock().await; - registry.remove(&sandbox.id); - let _ = tokio::fs::remove_dir_all(&state_dir).await; - return Err(Status::internal(format!("create socket dir failed: {err}"))); - } - - if let Err(err) = self.ensure_extension_state_dirs(&state_dir).await { - let mut registry = self.registry.lock().await; - registry.remove(&sandbox.id); - let _ = tokio::fs::remove_dir_all(&state_dir).await; - remove_sandbox_socket_dir(&self.socket_root_fd, &sandbox.id); - return Err(err); - } - - if let Err(err) = write_sandbox_request(&state_dir, sandbox).await { - let mut registry = self.registry.lock().await; - registry.remove(&sandbox.id); - let _ = tokio::fs::remove_dir_all(&state_dir).await; - remove_sandbox_socket_dir(&self.socket_root_fd, &sandbox.id); - return Err(Status::internal(format!( - "write sandbox start metadata failed: {err}" - ))); - } - - self.publish_platform_event( - sandbox.id.clone(), - platform_event( - "vm", - "Normal", - "Scheduled", - format!("Sandbox accepted by vm driver to image \"{image_ref}\""), - ), - ); - self.publish_snapshot(snapshot); - - let driver = self.clone(); - let sandbox_for_task = sandbox.clone(); - let sandbox_id = sandbox.id.clone(); - let image_ref_for_task = image_ref.clone(); - let state_dir_for_task = state_dir.clone(); - let parent = tracing::Span::current().context(); - let provisioning_span = provisioning_span(&parent, &sandbox_id, &image_ref); - let task = tokio::spawn( - async move { - Box::pin(driver.provision_sandbox( - sandbox_for_task, - image_ref_for_task, - state_dir_for_task, - tls_paths, - OverlayPreparation::Fresh, - )) - .await; - } - .instrument(provisioning_span), - ); - - let mut registry = self.registry.lock().await; - if let Some(record) = registry.get_mut(&sandbox_id) { - if record.deleting { - task.abort(); - } else { - record.provisioning_task = Some(task); - } - } else { - task.abort(); - } - - Ok(CreateSandboxResponse::default()) - } - - async fn provision_sandbox( - &self, - sandbox: Sandbox, - image_ref: String, - state_dir: PathBuf, - tls_paths: Option, - overlay_preparation: OverlayPreparation, - ) { - let sandbox_id = sandbox.id.clone(); - if let Err(err) = self - .provision_sandbox_inner( - sandbox, - image_ref, - state_dir.clone(), - tls_paths, - overlay_preparation, - ) - .await - { - tracing::Span::current().record("otel.status_code", "ERROR"); - if err.code() == tonic::Code::Cancelled { - if overlay_preparation == OverlayPreparation::Fresh { - let _ = tokio::fs::remove_dir_all(&state_dir).await; - } - remove_sandbox_socket_dir(&self.socket_root_fd, &sandbox_id); - return; - } - - warn!( - sandbox_id = %sandbox_id, - error = %err.message(), - "vm driver: sandbox provisioning failed" - ); - self.fail_provisioning( - &sandbox_id, - &state_dir, - "ProvisioningFailed", - err.message(), - overlay_preparation == OverlayPreparation::Fresh, - ) - .await; - } - } - - #[allow(clippy::result_large_err)] - async fn provision_sandbox_inner( - &self, - sandbox: Sandbox, - image_ref: String, - state_dir: PathBuf, - tls_paths: Option, - overlay_preparation: OverlayPreparation, - ) -> Result<(), Status> { - self.ensure_provisioning_active(&sandbox.id).await?; - // Launch credentials are independent of the image. Validate them before - // resolving registry references, preparing disks, or publishing progress. - let launch_authentication = decode_launch_authentication( - sandbox - .spec - .as_ref() - .map_or(&[], |spec| spec.launch_authentication.as_slice()), - )?; - let is_gpu = sandbox_requests_gpu(&sandbox); - let driver_config = - VmSandboxDriverConfig::from_sandbox(&sandbox).map_err(Status::invalid_argument)?; - // Check host sources before the costly image and overlay preparation. - validate_vm_mount_sources(&driver_config.mounts).await?; - let driver_config_had_rootfs_tar = driver_config.rootfs_tar_path.is_some(); - let rootfs_tar_path = match driver_config.rootfs_tar_path { - Some(raw) if overlay_preparation == OverlayPreparation::Fresh => { - Some(self.validate_rootfs_tar_path(Path::new(&raw)).await?) - } - Some(_) | None => None, - }; - - self.publish_platform_event( - sandbox.id.clone(), - platform_event( - "vm", - "Normal", - "ResolvingImage", - format!("Resolving VM sandbox image \"{image_ref}\""), - ), - ); - - let image_plan = if overlay_preparation == OverlayPreparation::PreserveExisting - && driver_config_had_rootfs_tar - { - let persisted_identity = - read_persisted_image_identity(&state_dir).await.map_err(|err| { - Status::internal(format!( - "cannot restore rootfs-tar sandbox: persisted image identity not found: {err}" - )) - })?; - let bootstrap_image_ref = self.bootstrap_image_ref()?; - let bootstrap_image_identity = self - .prepare_images_in_worker(&sandbox.id, &bootstrap_image_ref, None, true) - .await? - .bootstrap_image_identity; - let root_disk = - image_cache_rootfs_image(&self.config.state_dir, &bootstrap_image_identity); - let image_disk = image_cache_rootfs_image(&self.config.state_dir, &persisted_identity); - RuntimeImagePlan { - root_disk, - image_disk: Some(image_disk), - image_identity: persisted_identity, - bootstrap_image_identity, - } - } else { - self.prepare_images_in_worker( - &sandbox.id, - &image_ref, - rootfs_tar_path.as_deref(), - false, - ) - .await? - }; - let image_identity = image_plan.image_identity.clone(); - self.ensure_provisioning_active(&sandbox.id).await?; - info!( - sandbox_id = %sandbox.id, - image_identity = %image_identity, - bootstrap_image_identity = %image_plan.bootstrap_image_identity, - image_disk = image_plan.image_disk.as_ref().map(|path| path.display().to_string()).unwrap_or_default(), - "vm driver: sandbox root disk plan resolved" - ); - let disk_paths = sandbox_runtime_disk_paths(&state_dir); - let root_disk = image_plan.root_disk; - let image_disk = image_plan.image_disk; - let owner_source_disk = image_disk.as_ref().unwrap_or(&root_disk).clone(); - let overlay_disk = disk_paths.overlay_disk; - let boundary_generation = - match tokio::fs::read_to_string(state_dir.join(HOST_BOUNDARY_GENERATION_FILE)).await { - Ok(generation) if !generation.trim().is_empty() => generation.trim().to_string(), - Ok(_) => random_boundary_token()?, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - random_boundary_token()? - } - Err(error) => { - return Err(Status::internal(format!( - "read VM boundary generation: {error}" - ))); - } - }; - self.publish_platform_event( - sandbox.id.clone(), - platform_event( - "vm", - "Normal", - "PreparingOverlay", - "Preparing writable VM overlay disk".to_string(), - ), - ); - let sandbox_owner_state = self - .prepare_overlay_in_worker( - &sandbox.id, - &owner_source_disk, - overlay_preparation, - sandbox - .spec - .as_ref() - .and_then(|spec| spec.workload_identity.as_ref()), - ) - .await - .map_err(|err| Status::internal(format!("prepare guest overlay disk failed: {err}")))?; - self.ensure_provisioning_active(&sandbox.id).await?; - - if let Err(err) = - write_sandbox_image_metadata(&state_dir, &image_ref, &image_identity).await - { - return Err(Status::internal(format!( - "write sandbox image metadata failed: {err}" - ))); - } - - let gpu_device_id = vm_gpu_device_id(&sandbox)?; - let gpu_bdf = if let Some(gpu_device_id) = gpu_device_id.as_deref() { - Some( - self.assign_gpu_to_record(&sandbox.id, gpu_device_id) - .await?, - ) - } else { - None - }; - - let needs_qemu = is_gpu; - - let mut plan = - match self.build_vm_launch_plan(&sandbox.id, needs_qemu, is_gpu, gpu_bdf.clone()) { - Ok(plan) => plan, - Err(err) => { - self.release_gpu(&sandbox.id); - return Err(err); - } - }; - - if let Err(err) = self - .lifecycle_extensions - .configure_launch(&sandbox, &state_dir, &mut plan) - .await - { - self.lifecycle_extensions - .after_launch_failed( - &sandbox, - &state_dir, - LaunchAbortReason::BeforeLaunchHookFailed, - ) - .await; - self.release_gpu(&sandbox.id); - let message = format!( - "vm lifecycle extension rejected sandbox launch plan: {}", - err.message() - ); - return Err(if err.is_resource_exhausted() { - Status::resource_exhausted(message) - } else { - Status::failed_precondition(message) - }); - } - - // Resolve and validate the backend from the requirements that - // `configure_launch` extensions contributed. After this point the - // plan's backend, sizing, and host allocations are final; the - // `before_launch` hook below may still mutate - // `plan.env` and `plan.guest_init_dropins` and may abort the launch, - // but it MUST NOT change `plan.backend`, `plan.required_backends`, - // or `plan.required_backend_features` -- those are enforced as a - // documented trait contract, not a runtime check. - if let Err(err) = - self.resolve_launch_plan_backend(&sandbox.id, is_gpu, gpu_bdf.clone(), &mut plan) - { - self.lifecycle_extensions - .after_launch_failed( - &sandbox, - &state_dir, - LaunchAbortReason::BeforeLaunchHookFailed, - ) - .await; - self.release_gpu(&sandbox.id); - return Err(err); - } - - if let Err(err) = Self::validate_launch_plan_backend(is_gpu, &plan).and_then(|()| { - // Cannot fail today: `validate_sandbox` already ran and non-GPU - // QEMU is blocked above. Keeps virtiofs mounts off QEMU once that - // guard is lifted. - validate_vm_driver_mounts( - &driver_config.mounts, - &self.config, - plan.backend == VmBackend::Qemu, - ) - }) { - self.lifecycle_extensions - .after_launch_failed( - &sandbox, - &state_dir, - LaunchAbortReason::BeforeLaunchHookFailed, - ) - .await; - self.release_gpu(&sandbox.id); - return Err(err); - } - - if let Err(err) = self - .lifecycle_extensions - .before_launch(&sandbox, &state_dir, &mut plan) - .await - { - self.lifecycle_extensions - .after_launch_failed( - &sandbox, - &state_dir, - LaunchAbortReason::BeforeLaunchHookFailed, - ) - .await; - self.release_gpu(&sandbox.id); - let message = format!( - "vm lifecycle extension rejected sandbox launch: {}", - err.message() - ); - return Err(if err.is_resource_exhausted() { - Status::resource_exhausted(message) - } else { - Status::failed_precondition(message) - }); - } - - // The mount manifest is always written, even when empty, so an - // image-supplied manifest in the lowerdir can never drive guest mounts. - if let Err(err) = inject_guest_init_dropins(&overlay_disk, &plan.guest_init_dropins) - .and_then(|()| { - inject_guest_mount_manifest(&overlay_disk, &driver_config.mounts) - .map_err(|error| Status::internal(format!("inject VM mount manifest: {error}"))) - }) - { - self.lifecycle_extensions - .after_launch_failed(&sandbox, &state_dir, LaunchAbortReason::GuestPrepareFailed) - .await; - self.release_gpu(&sandbox.id); - return Err(err); - } - - let console_output = state_dir.join("rootfs-console.log"); - create_sandbox_socket_dir(&self.socket_root_fd, &self.socket_root, &sandbox.id) - .map_err(|err| Status::internal(format!("create socket dir failed: {err}")))?; - let control_socket = - sandbox_socket_dir(&self.socket_root, &sandbox.id).join(VM_CONTROL_SOCKET); - let session_id = launch_authentication.supervisor.session_id; - let channel_tls = generate_sandbox_tls_material(session_id) - .map_err(|error| Status::internal(error.to_string()))?; - let supervisor_tls = SandboxTlsClientConfig { - server_name: channel_tls.server_name.clone(), - trust_anchor_pem: channel_tls.trust_anchor_pem.clone(), - }; - let transport = if plan.backend == VmBackend::Qemu { - let guest_cid = plan - .vsock_cid - .ok_or_else(|| Status::internal("QEMU launch plan is missing a guest vsock CID"))?; - SandboxTransport::RuntimeInitiatedVsock { - guest_cid, - // Each QEMU guest connects to a distinct host port. The CID - // allocator already guarantees uniqueness among live guests. - port: VM_CONTROL_PORT - .checked_add(guest_cid) - .filter(|port| *port != u32::MAX) - .ok_or_else(|| Status::resource_exhausted("VM control port space exhausted"))?, - } - } else { - SandboxTransport::RuntimeInitiatedUnix { - socket_path: control_socket.clone(), - } - }; - let verification_keys = launch_authentication - .verification_keys - .iter() - .map(|key| { - String::from_utf8(key.public_key_pem.clone()) - .map(|public_key_pem| GatewayVerificationKey { - key_id: key.key_id.clone(), - public_key_pem, - }) - .map_err(|error| { - Status::failed_precondition(format!( - "VM sandbox verification key is not UTF-8 PEM: {error}" - )) - }) - }) - .collect::, _>>()?; - let provisioning = VmBoundarySpec { - boundary_id: sandbox.id.clone(), - generation: launch_authentication - .supervisor - .runtime_generation - .to_string(), - session_id, - session_rotation: launch_authentication.supervisor.session_rotation, - auth_epoch: launch_authentication.supervisor.auth_epoch, - gateway_id: launch_authentication.gateway_id.clone(), - verification_keys, - image_identity, - transport, - supervisor_tls, - sandbox_tls: guest_boundary_tls_paths(&boundary_generation), - control_port: VM_CONTROL_PORT, - agent_uid: sandbox_owner_state.uid, - agent_gid: sandbox_owner_state.gid, - child_env: merged_environment(&sandbox), - gpu_requested: is_gpu, - } - .provision() - .map_err(|error| Status::failed_precondition(error.to_string()))?; - let guest_boundary_config_path = - guest_boundary_config_path(&provisioning.boundary_config.generation); - inject_guest_boundary_bundle( - &overlay_disk, - &guest_boundary_config_path, - &provisioning.boundary_config, - &channel_tls, - ) - .map_err(|error| Status::internal(format!("inject VM boundary configuration: {error}")))?; - write_private_file( - &state_dir.join(HOST_BOUNDARY_GENERATION_FILE), - boundary_generation.as_bytes().to_vec(), - ) - .await - .map_err(|error| Status::internal(format!("persist VM boundary generation: {error}")))?; - let runtime_descriptor = provisioning.runtime_descriptor; - let mut command = Command::new(&self.launcher_bin); - command.kill_on_drop(true); - command.stdin(Stdio::null()); - command.stdout(Stdio::inherit()); - command.stderr(Stdio::inherit()); - command.arg("--internal-run-vm"); - command.arg("--vm-root-disk").arg(&root_disk); - command.arg("--vm-overlay-disk").arg(&overlay_disk); - if let Some(image_disk) = &image_disk { - command.arg("--vm-image-disk").arg(image_disk); - } - command.arg("--vm-exec").arg(sandbox_guest_init_path()); - command.arg("--vm-workdir").arg("/"); - command.arg("--vm-console-output").arg(&console_output); - command.arg("--vm-vcpus").arg(plan.vcpus.to_string()); - command.arg("--vm-mem-mib").arg(plan.mem_mib.to_string()); - if let Some(kernel_image) = &plan.kernel_image { - command.arg("--vm-kernel-image").arg(kernel_image); - } - - if plan.backend == VmBackend::Qemu { - command.arg("--vm-backend").arg("qemu"); - if let Some(bdf) = plan.gpu_bdf.as_deref() { - command.arg("--vm-gpu-bdf").arg(bdf); - } - if let Some(vsock_cid) = plan.vsock_cid { - command.arg("--vm-vsock-cid").arg(vsock_cid.to_string()); - } - } else { - let _ = tokio::fs::remove_file(&control_socket).await; - command - .arg("--vm-vsock-runtime-initiated") - .arg("--vm-vsock-control-port") - .arg(VM_CONTROL_PORT.to_string()) - .arg("--vm-vsock-control-socket") - .arg(&control_socket); - } - - self.ensure_provisioning_active(&sandbox.id).await?; - - command - .arg("--vm-krun-log-level") - .arg(self.config.krun_log_level.to_string()); - - for env in build_guest_environment(&sandbox, &self.config) { - command.arg("--vm-env").arg(env); - } - command.arg("--vm-env").arg(format!( - "{GUEST_BOUNDARY_CONFIG_ENV}={guest_boundary_config_path}" - )); - for env in &plan.env { - command.arg("--vm-env").arg(env); - } - for env in sandbox_owner_state.guest_environment() { - command.arg("--vm-env").arg(env); - } - for (i, mount) in driver_config.mounts.iter().enumerate() { - command.arg("--vm-mount").arg(format!( - "{}\t{}\t{}", - mount.host_source(), - virtiofs_tag(i), - vm_mount_mode(mount.read_only) - )); - info!( - sandbox_id = %sandbox.id, - source = %mount.host_source(), - target = %mount.target, - mode = vm_mount_mode(mount.read_only), - "vm driver: sharing host directory with sandbox" - ); - } - - info!( - sandbox_id = %sandbox.id, - launcher = %self.launcher_bin.display(), - console_output = %console_output.display(), - "vm driver: spawning VM launcher" - ); - let mut child = match command.spawn() { - Ok(child) => child, - Err(err) => { - warn!( - sandbox_id = %sandbox.id, - error = %err, - "vm driver: launcher spawn failed" - ); - self.lifecycle_extensions - .after_launch_failed( - &sandbox, - &state_dir, - LaunchAbortReason::LauncherSpawnFailed, - ) - .await; - self.release_gpu(&sandbox.id); - return Err(Status::internal(format!( - "failed to launch vm helper '{}': {err}", - self.launcher_bin.display() - ))); - } - }; - info!( - sandbox_id = %sandbox.id, - launcher_pid = child.id().unwrap_or(0), - "vm driver: launcher spawned" - ); - let (supervisor, supervisor_liveness) = match self - .spawn_host_supervisor( - &sandbox, - &state_dir, - tls_paths.as_ref(), - &runtime_descriptor, - &launch_authentication.supervisor, - sandbox_owner_state, - ) - .await - { - Ok(supervisor) => supervisor, - Err(error) => { - let _ = terminate_vm_process(&mut child).await; - self.lifecycle_extensions - .after_launch_failed( - &sandbox, - &state_dir, - LaunchAbortReason::LauncherSpawnFailed, - ) - .await; - self.release_gpu(&sandbox.id); - return Err(error); - } - }; - let process = Arc::new(Mutex::new(VmProcess { - child, - supervisor, - supervisor_liveness, - deleting: false, - })); - - let mut process_to_stop = None; - let mut snapshot_to_publish = None; - { - let mut registry = self.registry.lock().await; - match registry.get_mut(&sandbox.id) { - Some(record) if !record.deleting => { - record.process = Some(process.clone()); - record.gpu_bdf.clone_from(&gpu_bdf); - let identity = &runtime_descriptor.workload_identity; - record - .snapshot - .status - .get_or_insert_with(SandboxStatus::default) - .resolved_identity = Some(ResolvedWorkloadIdentity { - uid: identity.uid, - gid: identity.gid, - supplementary_gids: identity.supplementary_gids.clone(), - source: identity.source.clone(), - resource_digest: identity.resource_digest.clone(), - }); - snapshot_to_publish = Some(record.snapshot.clone()); - } - _ => { - process_to_stop = Some(process.clone()); - } - } - } - - if let Some(process) = process_to_stop { - { - let mut process = process.lock().await; - process.deleting = true; - terminate_sandbox_processes(&mut process) - .await - .map_err(|err| Status::internal(format!("failed to stop sandbox: {err}")))?; - } - self.release_gpu(&sandbox.id); - return Err(Status::cancelled("sandbox provisioning cancelled")); - } - - self.publish_platform_event( - sandbox.id.clone(), - platform_event("vm", "Normal", "Started", "Started VM launcher".to_string()), - ); - if let Some(snapshot) = snapshot_to_publish { - self.publish_snapshot(snapshot); - } - if overlay_preparation == OverlayPreparation::PreserveExisting { - let persisted = RestoreContext { - sandbox: sandbox.clone(), - state_dir: state_dir.clone(), - }; - self.lifecycle_extensions.after_restore(&persisted).await; - } - tokio::spawn({ - let driver = self.clone(); - let sandbox_id = sandbox.id.clone(); - async move { - driver.monitor_sandbox(sandbox_id).await; - } - }); - - Ok(()) - } - - pub async fn stop_sandbox(&self, sandbox_id: &str, sandbox_name: &str) -> Result<(), Status> { - if !sandbox_id.is_empty() { - validate_sandbox_id(sandbox_id)?; - } - let record_id = { - let registry = self.registry.lock().await; - resolve_record_id(®istry, sandbox_id, sandbox_name)? - } - .ok_or_else(|| Status::not_found("sandbox not found"))?; - - let state_dir = { - let registry = self.registry.lock().await; - registry - .get(&record_id) - .ok_or_else(|| Status::not_found("sandbox not found"))? - .state_dir - .clone() - }; - - // Persist intent before detaching process handles or releasing host - // allocations. If this write fails, the live record remains intact. - tokio::fs::write(state_dir.join(SANDBOX_STOPPED_FILE), b"stopped\n") - .await - .map_err(|err| Status::internal(format!("persist stop marker failed: {err}")))?; - - let (process, provisioning_task, has_gpu, snapshot) = { - let mut registry = self.registry.lock().await; - let record = registry - .get_mut(&record_id) - .ok_or_else(|| Status::not_found("sandbox not found"))?; - ( - record.process.take(), - record.provisioning_task.take(), - record.gpu_bdf.take().is_some(), - record.snapshot.clone(), - ) - }; - - if let Some(task) = provisioning_task { - task.abort(); - // Wait for the future to drop its worker I/O before taking the - // registered attempt. Aborting alone does not stop its subprocess. - let _ = task.await; - } - self.cleanup_image_preparation(&record_id).await?; - if let Some(process) = process { - let mut process = process.lock().await; - process.deleting = true; - terminate_sandbox_processes(&mut process) - .await - .map_err(|err| Status::internal(format!("failed to stop sandbox: {err}")))?; - } - remove_runtime_generation_material(&state_dir) - .await - .map_err(|error| { - Status::internal(format!( - "remove stopped VM authentication material: {error}" - )) - })?; - self.lifecycle_extensions - .after_launch_failed(&snapshot, &state_dir, LaunchAbortReason::Stopped) - .await; - if has_gpu { - self.release_gpu(&record_id); - } - - if let Some(snapshot) = self - .set_snapshot_condition(&record_id, stopped_condition(), false) - .await - { - self.publish_snapshot(snapshot); - } - self.publish_platform_event( - record_id, - platform_event("vm", "Normal", "Stopped", "VM sandbox stopped".to_string()), - ); - Ok(()) - } - - pub async fn start_sandbox( - &self, - sandbox_id: &str, - sandbox_name: &str, - generation_id: &str, - launch_authentication: Vec, - ) -> Result<(), Status> { - if !sandbox_id.is_empty() { - validate_sandbox_id(sandbox_id)?; - } - let generation = openshell_core::sandbox_generation::SandboxGenerationId::parse( - generation_id.to_string(), - ) - .map_err(|error| Status::invalid_argument(error.to_string()))?; - let (record_id, state_dir, already_running) = { - let registry = self.registry.lock().await; - let id = resolve_record_id(®istry, sandbox_id, sandbox_name)? - .ok_or_else(|| Status::not_found("sandbox not found"))?; - let record = registry - .get(&id) - .ok_or_else(|| Status::not_found("sandbox not found"))?; - if record.preparation.is_some() && record.provisioning_task.is_none() { - return Err(Status::failed_precondition( - "image preparation cleanup is still in progress", - )); - } - ( - id, - record.state_dir.clone(), - record.process.is_some() || record.provisioning_task.is_some(), - ) - }; - if already_running { - let active_generation = - tokio::fs::read_to_string(state_dir.join(HOST_BOUNDARY_GENERATION_FILE)) - .await - .map_err(|error| { - Status::failed_precondition(format!( - "read active VM sandbox generation: {error}" - )) - })?; - if active_generation.trim() != generation.as_str() { - return Err(Status::failed_precondition(format!( - "VM sandbox is already running generation {}", - active_generation.trim() - ))); - } - if launch_authentication.is_empty() { - return Ok(()); - } - } - // An invalid replacement must not stop the active VM or remove the - // previous generation's credentials. Preserve the empty idempotent - // replay above, which does not request a new launch. - decode_launch_authentication(&launch_authentication)?; - let mut sandbox = read_sandbox_request(&state_dir.join(SANDBOX_REQUEST_FILE)) - .await - .map_err(|error| { - Status::failed_precondition(format!("read VM admission provenance: {error}")) - })?; - self.validate_sandbox(&sandbox)?; - if already_running { - // The gateway keeps launch sessions in memory. A non-empty bundle - // during startup recovery represents a new gateway session, so - // restart the VM before installing it rather than leaving the old - // supervisor connected with invalid credentials. - self.stop_sandbox(&record_id, sandbox_name).await?; - } - - remove_runtime_generation_material(&state_dir) - .await - .map_err(|error| { - Status::internal(format!( - "remove previous VM authentication material: {error}" - )) - })?; - write_private_file( - &state_dir.join(HOST_BOUNDARY_GENERATION_FILE), - generation.as_str().as_bytes().to_vec(), - ) - .await - .map_err(|error| Status::internal(format!("persist VM start generation: {error}")))?; - let spec = sandbox - .spec - .as_mut() - .ok_or_else(|| Status::failed_precondition("persisted VM sandbox spec is missing"))?; - spec.launch_authentication = launch_authentication; - write_sandbox_request(&state_dir, &sandbox) - .await - .map_err(|error| { - Status::internal(format!( - "persist refreshed VM launch authentication: {error}" - )) - })?; - let stopped_record = self - .registry - .lock() - .await - .remove(&record_id) - .ok_or_else(|| Status::not_found("sandbox not found"))?; - let restored = self - .restore_persisted_sandbox(sandbox, state_dir, true, &tracing::Span::current()) - .await; - if !restored { - self.registry - .lock() - .await - .entry(record_id) - .or_insert(stopped_record); - return Err(Status::internal("failed to start persisted VM sandbox")); - } - Ok(()) - } - - #[tracing::instrument( - name = "vm.teardown", - skip(self), - fields( - otel.name = "vm.teardown", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - sandbox.name = %sandbox_name, - ) - )] - pub async fn delete_sandbox( - &self, - sandbox_id: &str, - sandbox_name: &str, - ) -> Result { - let span_status = openshell_otel::ErrorStatusGuard::current(); - if !sandbox_id.is_empty() { - validate_sandbox_id(sandbox_id)?; - } - - let record_id = { - let registry = self.registry.lock().await; - resolve_record_id(®istry, sandbox_id, sandbox_name)? - }; - - let Some(record_id) = record_id else { - return span_status.finish(Ok(DeleteSandboxResponse { deleted: false })); - }; - - let (state_dir, process, gpu_bdf, provisioning_task, sandbox_snapshot) = { - let mut registry = self.registry.lock().await; - let Some(record) = registry.get_mut(&record_id) else { - return span_status.finish(Ok(DeleteSandboxResponse { deleted: false })); - }; - record.deleting = true; - ( - record.state_dir.clone(), - record.process.clone(), - record.gpu_bdf.clone(), - record.provisioning_task.take(), - record.snapshot.clone(), - ) - }; - - if let Some(snapshot) = self - .set_snapshot_condition(&record_id, deleting_condition(), true) - .await - { - self.publish_snapshot(snapshot); - } - - if let Some(task) = provisioning_task { - task.abort(); - // Wait for the future to drop its worker I/O before taking the - // registered attempt. Aborting alone does not stop its subprocess. - let _ = task.await; - } - self.cleanup_image_preparation(&record_id).await?; - - if let Some(process) = process { - let mut process = process.lock().await; - process.deleting = true; - terminate_sandbox_processes(&mut process) - .await - .map_err(|err| Status::internal(format!("failed to stop sandbox: {err}")))?; - } - - self.lifecycle_extensions - .after_delete(&sandbox_snapshot, &state_dir) - .await; - - if gpu_bdf.is_some() { - self.release_gpu(&record_id); - } - - remove_sandbox_state_dir(&self.config.state_dir, &state_dir).await?; - remove_sandbox_socket_dir(&self.socket_root_fd, &record_id); - - { - let mut registry = self.registry.lock().await; - registry.remove(&record_id); - } - - self.publish_deleted(record_id); - span_status.finish(Ok(DeleteSandboxResponse { deleted: true })) - } - - pub async fn get_sandbox( - &self, - sandbox_id: &str, - sandbox_name: &str, - ) -> Result, Status> { - if !sandbox_id.is_empty() { - validate_sandbox_id(sandbox_id)?; - } - - let registry = self.registry.lock().await; - let sandbox = if sandbox_id.is_empty() { - registry - .values() - .find(|record| record.snapshot.name == sandbox_name) - .map(|record| record.snapshot.clone()) - } else { - registry - .get(sandbox_id) - .map(|record| record.snapshot.clone()) - }; - Ok(sandbox) - } - - pub async fn current_snapshots(&self) -> Vec { - let registry = self.registry.lock().await; - let mut snapshots = registry - .values() - .map(|record| record.snapshot.clone()) - .collect::>(); - snapshots.sort_by(|left, right| left.name.cmp(&right.name)); - snapshots - } - - #[tracing::instrument( - name = "reconcile", - skip_all, - fields( - otel.name = "reconcile.sandboxes", - driver.name = "vm", - ) - )] - async fn restore_persisted_sandboxes(&self) { - let state_root = sandboxes_root_dir(&self.config.state_dir); - let mut entries = match tokio::fs::read_dir(&state_root).await { - Ok(entries) => entries, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return, - Err(err) => { - warn!( - state_root = %state_root.display(), - error = %err, - "vm driver: failed to scan persisted sandboxes" - ); - return; - } - }; - - loop { - let entry = match entries.next_entry().await { - Ok(Some(entry)) => entry, - Ok(None) => break, - Err(err) => { - warn!( - state_root = %state_root.display(), - error = %err, - "vm driver: failed to continue scanning persisted sandboxes" - ); - break; - } - }; - let state_dir = entry.path(); - let is_dir = match entry.file_type().await { - Ok(file_type) => file_type.is_dir(), - Err(err) => { - warn!( - state_dir = %state_dir.display(), - error = %err, - "vm driver: failed to inspect persisted sandbox state dir" - ); - continue; - } - }; - if !is_dir { - continue; - } - - let request_path = state_dir.join(SANDBOX_REQUEST_FILE); - let sandbox = match read_sandbox_request(&request_path).await { - Ok(sandbox) => sandbox, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, - Err(err) => { - warn!( - state_dir = %state_dir.display(), - error = %err, - "vm driver: failed to read persisted sandbox request" - ); - continue; - } - }; - - if let Err(status) = - validate_restored_sandbox_state(&self.config.state_dir, &state_dir, &sandbox) - { - warn!( - sandbox_id = %sandbox.id, - state_dir = %state_dir.display(), - error = %status.message(), - "vm driver: ignoring invalid persisted sandbox state" - ); - continue; - } - - let inactive_condition = if tokio::fs::metadata(state_dir.join(SANDBOX_STOPPED_FILE)) - .await - .is_ok() - { - Some(stopped_condition()) - } else if tokio::fs::try_exists(state_dir.join(MAIN_PROCESS_EXITED_FILE)) - .await - .unwrap_or(false) - { - Some(error_condition( - "ProcessExited", - "Canonical main process exited before VM driver restart", - )) - } else { - None - }; - if let Some(condition) = inactive_condition { - // These sandboxes do not run the launch path that publishes - // identity. Recover it from the same validated owner marker - // before either GetSandbox or WatchSandboxes can observe them. - let identity = match read_persisted_workload_identity(&state_dir).await { - Ok(identity) => identity, - Err(error) => { - warn!(sandbox_id = %sandbox.id, %error, "vm driver: ignoring invalid persisted workload identity"); - // Keep inactive resources manageable even when their - // identity cannot be trusted. Explicit deletion still - // needs this registry entry to remove persisted state. - None - } - }; - let mut snapshot = sandbox_snapshot(&sandbox, condition, false); - snapshot - .status - .get_or_insert_with(SandboxStatus::default) - .resolved_identity = identity; - let mut registry = self.registry.lock().await; - registry.entry(sandbox.id.clone()).or_insert(SandboxRecord { - snapshot: snapshot.clone(), - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }); - drop(registry); - self.publish_snapshot(snapshot); - info!( - sandbox_id = %sandbox.id, - "vm driver: restored inactive sandbox without launching compute" - ); - continue; - } - - self.restore_persisted_sandbox(sandbox, state_dir, false, &tracing::Span::current()) - .await; - } - } - - /// Restore a persisted sandbox and report whether the driver accepted it. - /// For explicit start, the stop marker is cleared only after all - /// restore preflight checks pass and the replacement registry record is - /// installed. A failed restore therefore remains durably stopped. - async fn restore_persisted_sandbox( - &self, - sandbox: Sandbox, - state_dir: PathBuf, - clear_stop_marker: bool, - reconciliation_span: &tracing::Span, - ) -> bool { - // Startup recovery bypasses create/start admission. Validate saved - // credentials before host preparation, extension hooks, or state changes. - if let Err(error) = decode_launch_authentication( - sandbox - .spec - .as_ref() - .map_or(&[], |spec| spec.launch_authentication.as_slice()), - ) { - warn!(sandbox_id = %sandbox.id, reason = %error.message(), "VM recovery denied by launch authentication"); - return false; - } - if let Err(error) = self.validate_sandbox(&sandbox) { - warn!(sandbox_id = %sandbox.id, reason = %error.message(), "VM recovery denied by admission"); - return false; - } - let has_rootfs_tar = VmSandboxDriverConfig::from_sandbox(&sandbox) - .is_ok_and(|c| c.rootfs_tar_path.is_some()); - - let Some(image_ref) = self.resolved_sandbox_image(&sandbox).or_else(|| { - has_rootfs_tar - .then(|| self.bootstrap_image_ref_default()) - .flatten() - }) else { - warn!( - sandbox_id = %sandbox.id, - sandbox_name = %sandbox.name, - "vm driver: cannot restore persisted sandbox without image" - ); - return false; - }; - let tls_paths = match self.config.tls_paths() { - Ok(paths) => paths, - Err(err) => { - warn!( - sandbox_id = %sandbox.id, - sandbox_name = %sandbox.name, - error = %err, - "vm driver: cannot restore persisted sandbox TLS configuration" - ); - return false; - } - }; - - if let Err(err) = self.ensure_extension_state_dirs(&state_dir).await { - warn!( - sandbox_id = %sandbox.id, - sandbox_name = %sandbox.name, - state_dir = %state_dir.display(), - error = %err.message(), - "vm driver: cannot restore persisted sandbox extension state" - ); - return false; - } - - let persisted = RestoreContext { - sandbox: sandbox.clone(), - state_dir: state_dir.clone(), - }; - if let Err(err) = self.lifecycle_extensions.before_restore(&persisted).await { - warn!( - sandbox_id = %sandbox.id, - sandbox_name = %sandbox.name, - state_dir = %state_dir.display(), - error = %err, - "vm driver: lifecycle extension rejected persisted sandbox restore" - ); - return false; - } - - let snapshot = sandbox_snapshot(&sandbox, provisioning_condition(), false); - { - let mut registry = self.registry.lock().await; - if registry.contains_key(&sandbox.id) { - return false; - } - registry.insert( - sandbox.id.clone(), - SandboxRecord { - snapshot: snapshot.clone(), - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - } - - if clear_stop_marker && let Err(err) = clear_explicit_start_markers(&state_dir).await { - self.registry.lock().await.remove(&sandbox.id); - warn!( - sandbox_id = %sandbox.id, - state_dir = %state_dir.display(), - error = %err, - "vm driver: cannot clear lifecycle markers for persisted sandbox restore" - ); - return false; - } - - self.publish_platform_event( - sandbox.id.clone(), - platform_event( - "vm", - "Normal", - "Restoring", - "Restoring persisted VM sandbox after driver restart".to_string(), - ), - ); - self.publish_snapshot(snapshot); - - let driver = self.clone(); - let sandbox_id = sandbox.id.clone(); - let restoration_span = tracing::info_span!( - parent: reconciliation_span, - "vm.restore", - otel.name = "vm.restore", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - ); - let reconciliation_span = reconciliation_span.clone(); - let provisioning_span = - provisioning_span(&restoration_span.context(), &sandbox_id, &image_ref); - let task = tokio::spawn( - async move { - Box::pin(driver.provision_sandbox( - sandbox, - image_ref, - state_dir, - tls_paths, - OverlayPreparation::PreserveExisting, - )) - .await; - drop(reconciliation_span); - } - .instrument(provisioning_span) - .instrument(restoration_span), - ); - - let mut registry = self.registry.lock().await; - if let Some(record) = registry.get_mut(&sandbox_id) { - if record.deleting { - task.abort(); - } else { - record.provisioning_task = Some(task); - } - } else { - task.abort(); - } - true - } - - /// Best-effort removal of the per-driver socket root. VM children are - /// `kill_on_drop`, so no socket is live once the server has stopped. - pub fn remove_socket_root(&self) { - let _ = fs::remove_dir_all(&self.socket_root); - } - - fn release_gpu(&self, sandbox_id: &str) { - if let Some(inventory) = self.gpu_inventory.as_ref() - && let Ok(mut inv) = inventory.lock() - { - inv.release(sandbox_id); - } - } - - async fn ensure_extension_state_dirs(&self, state_dir: &Path) -> Result<(), Status> { - for extension_name in self.lifecycle_extensions.names() { - let extension_dir = extension_state_dir(state_dir, &extension_name).map_err(|err| { - Status::failed_precondition(format!( - "invalid VM lifecycle extension '{}': {}", - extension_name, - err.message() - )) - })?; - create_private_dir_all(&extension_dir) - .await - .map_err(|err| { - Status::internal(format!( - "create VM lifecycle extension state dir '{}' failed: {err}", - extension_dir.display() - )) - })?; - } - Ok(()) - } - - #[allow(clippy::result_large_err)] - fn resolve_launch_plan_backend( - &self, - sandbox_id: &str, - is_gpu: bool, - gpu_bdf: Option, - plan: &mut LaunchPlan, - ) -> Result<(), Status> { - if plan.kernel_image.is_some() { - plan.require_backend_feature(BackendFeature::ExternalKernelImage); - } - if !plan.guest_init_dropins.is_empty() { - plan.require_backend_feature(BackendFeature::GuestInitDropins); - } - - if plan.required_backends.contains(&VmBackend::Qemu) - || plan.backend == VmBackend::Qemu - || plan - .required_backend_features - .iter() - .any(|feature| feature.requires_qemu()) - { - self.configure_qemu_launch_plan(sandbox_id, is_gpu, gpu_bdf, plan)?; - } - - Ok(()) - } - - // Keep the fallible shape used by launch-plan resolution: driver-local - // backends may add allocation failures here without changing callers. - #[allow(clippy::result_large_err, clippy::unnecessary_wraps)] - fn configure_qemu_launch_plan( - &self, - _sandbox_id: &str, - is_gpu: bool, - gpu_bdf: Option, - plan: &mut LaunchPlan, - ) -> Result<(), Status> { - plan.backend = VmBackend::Qemu; - if is_gpu { - plan.vcpus = self.config.gpu_vcpus; - plan.mem_mib = self.config.gpu_mem_mib; - } - if plan.gpu_bdf.is_none() { - plan.gpu_bdf = gpu_bdf; - } - if plan.vsock_cid.is_some() { - return Ok(()); - } - plan.vsock_cid = Some(allocate_vsock_cid()); - Ok(()) - } - - #[allow(clippy::result_large_err)] - fn validate_launch_plan_backend(is_gpu: bool, plan: &LaunchPlan) -> Result<(), Status> { - // NOTE: this guard exists because the non-GPU QEMU launch path - // (PCI device transport, VFIO root port wiring) has not landed - // yet. Until then, even though the resolver will happily promote - // a plan to QEMU when an extension requires `PciPassthrough` or - // `ExternalKernelImage`, the launch itself is blocked here so we - // don't spawn a QEMU instance with no concrete device backing. - // Remove this guard once the non-GPU QEMU launch path supports - // emitting `pcie-root-port` + `vfio-pci` for arbitrary device - // descriptors. - if plan.backend == VmBackend::Qemu && !is_gpu { - let offending_feature = plan - .required_backend_features - .iter() - .find(|feature| feature.requires_qemu()) - .map_or("(explicit QEMU backend requirement)", |feature| { - feature.as_str() - }); - return Err(Status::failed_precondition(format!( - "vm lifecycle extension required '{offending_feature}', which resolves to the QEMU backend, \ - but non-GPU QEMU launch is not yet supported (pending PCI device transport)" - ))); - } - if plan.backend != VmBackend::Qemu && is_gpu { - return Err(Status::failed_precondition( - "GPU sandbox launch requires the QEMU backend", - )); - } - if plan.required_backends.contains(&VmBackend::Libkrun) - && plan.required_backends.contains(&VmBackend::Qemu) - { - return Err(Status::failed_precondition( - "VM lifecycle extensions requested conflicting VM backends", - )); - } - if plan.required_backends.contains(&VmBackend::Libkrun) - && plan.backend != VmBackend::Libkrun - { - return Err(Status::failed_precondition( - "VM lifecycle extension requires the libkrun backend", - )); - } - if plan.required_backends.contains(&VmBackend::Qemu) && plan.backend != VmBackend::Qemu { - return Err(Status::failed_precondition( - "VM lifecycle extension requires the QEMU backend", - )); - } - if plan.backend != VmBackend::Qemu - && let Some(feature) = plan - .required_backend_features - .iter() - .find(|feature| feature.requires_qemu()) - { - return Err(Status::failed_precondition(format!( - "VM backend feature '{}' requires a VM backend with PCI-style launch support", - feature.as_str() - ))); - } - if plan.kernel_image.is_some() && plan.backend != VmBackend::Qemu { - return Err(Status::failed_precondition( - "selected kernel image requires a VM backend that supports external kernel images", - )); - } - if let Some(kernel_image) = &plan.kernel_image - && !kernel_image.is_file() - { - return Err(Status::failed_precondition(format!( - "selected kernel image does not exist: {}", - kernel_image.display() - ))); - } - Ok(()) - } - - // Keep the fallible shape used by provisioning and lifecycle tests even - // though NIC/subnet allocation no longer introduces a failure today. - #[allow(clippy::result_large_err, clippy::unnecessary_wraps)] - fn build_vm_launch_plan( - &self, - _sandbox_id: &str, - needs_qemu: bool, - is_gpu: bool, - gpu_bdf: Option, - ) -> Result { - if !needs_qemu { - return Ok(LaunchPlan { - backend: VmBackend::Libkrun, - vcpus: self.config.vcpus, - mem_mib: self.config.mem_mib, - required_backends: Vec::new(), - required_backend_features: Vec::new(), - kernel_profile: None, - kernel_image: None, - gpu_bdf: None, - vsock_cid: None, - guest_init_dropins: Vec::new(), - env: Vec::new(), - }); - } - - let vsock_cid = allocate_vsock_cid(); - let (vcpus, mem_mib) = if is_gpu { - (self.config.gpu_vcpus, self.config.gpu_mem_mib) - } else { - (self.config.vcpus, self.config.mem_mib) - }; - - Ok(LaunchPlan { - backend: VmBackend::Qemu, - vcpus, - mem_mib, - required_backends: Vec::new(), - required_backend_features: Vec::new(), - kernel_profile: None, - kernel_image: None, - gpu_bdf, - vsock_cid: Some(vsock_cid), - guest_init_dropins: Vec::new(), - env: Vec::new(), - }) - } - - async fn ensure_provisioning_active(&self, sandbox_id: &str) -> Result<(), Status> { - let registry = self.registry.lock().await; - match registry.get(sandbox_id) { - Some(record) if !record.deleting => Ok(()), - _ => Err(Status::cancelled("sandbox provisioning cancelled")), - } - } - - #[cfg(test)] - async fn wait_for_provisioning_for_test(&self, sandbox_id: &str) { - let task = self - .registry - .lock() - .await - .get_mut(sandbox_id) - .and_then(|record| record.provisioning_task.take()) - .unwrap_or_else(|| panic!("provisioning task for {sandbox_id}")); - tokio::time::timeout(Duration::from_secs(5), task) - .await - .unwrap_or_else(|_| panic!("provisioning task for {sandbox_id} timed out")) - .unwrap_or_else(|err| panic!("provisioning task for {sandbox_id} failed: {err}")); - } - - async fn assign_gpu_to_record( - &self, - sandbox_id: &str, - gpu_device: &str, - ) -> Result { - let mut registry = self.registry.lock().await; - match registry.get_mut(sandbox_id) { - Some(record) if !record.deleting => {} - _ => return Err(Status::cancelled("sandbox provisioning cancelled")), - } - - let inventory = self - .gpu_inventory - .as_ref() - .ok_or_else(|| Status::internal("GPU inventory not initialized"))?; - let assignment = inventory - .lock() - .map_err(|e| Status::internal(format!("GPU inventory lock poisoned: {e}")))? - .assign(sandbox_id, gpu_device) - .map_err(Status::failed_precondition)?; - - let record = registry - .get_mut(sandbox_id) - .expect("sandbox record exists while registry lock is held"); - record.gpu_bdf = Some(assignment.bdf.clone()); - tracing::info!( - sandbox_id = %sandbox_id, - bdf = %assignment.bdf, - gpu_name = %assignment.name, - iommu_group = assignment.iommu_group, - "assigned GPU to sandbox" - ); - Ok(assignment.bdf) - } - - async fn fail_provisioning( - &self, - sandbox_id: &str, - state_dir: &Path, - reason: &str, - message: &str, - remove_state: bool, - ) { - self.release_gpu(sandbox_id); - let (snapshot, may_remove_state) = { - let mut registry = self.registry.lock().await; - let Some(record) = registry.get_mut(sandbox_id) else { - return; - }; - if record.deleting { - return; - } - record.process = None; - record.gpu_bdf = None; - record.snapshot.status = Some(status_with_condition( - &record.snapshot, - error_condition(reason, message), - false, - )); - // A failed cleanup leaves the attempt registered. Preserve all - // sandbox state until its worker and descendants are confirmed - // stopped, even when provisioning itself has already failed. - ( - Some(record.snapshot.clone()), - remove_state && record.preparation.is_none(), - ) - }; - - if may_remove_state { - let _ = tokio::fs::remove_dir_all(state_dir).await; - remove_sandbox_socket_dir(&self.socket_root_fd, sandbox_id); - } - self.publish_platform_event( - sandbox_id.to_string(), - platform_event( - "vm", - "Warning", - reason, - format!("VM provisioning failed: {message}"), - ), - ); - if let Some(snapshot) = snapshot { - self.publish_snapshot(snapshot); - } - } - - /// Keep every image write in a process owned by the sandbox record. The - /// registry retains the attempt when this future is cancelled so lifecycle - /// cleanup can kill and reap it before removing any staging or state. - #[tracing::instrument( - name = "vm.prepare_images", - skip(self), - fields(otel.name = "vm.prepare_images", otel.status_code = tracing::field::Empty, sandbox.id = %sandbox_id, image.ref = %image_ref) - )] - async fn prepare_images_in_worker( - &self, - sandbox_id: &str, - image_ref: &str, - rootfs_tar: Option<&Path>, - bootstrap_only: bool, - ) -> Result { - match self - .run_preparation_in_worker(sandbox_id, image_ref, rootfs_tar, bootstrap_only, None) - .await? - { - preparation::Output::Images(plan) => Ok(plan), - preparation::Output::Overlay(_) => { - Err(Status::internal("image worker returned an overlay result")) - } - } - } - - #[tracing::instrument( - name = "vm.prepare_overlay", - skip(self), - fields(otel.name = "vm.prepare_overlay", otel.status_code = tracing::field::Empty, sandbox.id = %sandbox_id) - )] - async fn prepare_overlay_in_worker( - &self, - sandbox_id: &str, - owner_source_disk: &Path, - preparation: OverlayPreparation, - requested_identity: Option<&WorkloadIdentityRequest>, - ) -> Result { - let overlay = preparation::OverlayRequest { - source_disk: owner_source_disk.to_path_buf(), - preparation, - requested_identity: requested_identity - .map(preparation::WorkloadIdentitySelectors::from), - }; - match self - .run_preparation_in_worker(sandbox_id, "", None, false, Some(overlay)) - .await? - { - preparation::Output::Overlay(owner) => Ok(owner), - preparation::Output::Images(_) => { - Err(Status::internal("overlay worker returned an image result")) - } - } - } - - /// The worker resolves the owner from the same state directory it will - /// modify, then rejects selectors that conflict with that owner before - /// preparing or repairing the writable disk. - async fn prepare_requested_overlay( - &self, - sandbox_id: &str, - overlay: preparation::OverlayRequest, - ) -> Result { - if !overlay - .source_disk - .starts_with(image_cache_root_dir(&self.config.state_dir)) - { - return Err(Status::invalid_argument( - "overlay source must be a cached image", - )); - } - let state_dir = sandbox_state_dir(&self.config.state_dir, sandbox_id)?; - let overlay_disk = sandbox_runtime_disk_paths(&state_dir).overlay_disk; - let requested_identity = overlay - .requested_identity - .map(WorkloadIdentityRequest::from); - self.prepare_runtime_overlay( - &state_dir, - &overlay_disk, - &overlay.source_disk, - overlay.preparation, - requested_identity.as_ref(), - ) - .await - .map_err(Status::internal) - } - - async fn run_preparation_in_worker( - &self, - sandbox_id: &str, - image_ref: &str, - rootfs_tar: Option<&Path>, - bootstrap_only: bool, - overlay: Option, - ) -> Result { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let bootstrap_image_ref = self.bootstrap_image_ref()?; - // Keep the driver trace continuous across the worker boundary. The - // first Pulled event completes bootstrap resolution; later events - // belong to the requested workload image. - let mut bootstrap_span = overlay.is_none().then(|| { - tracing::info_span!( - "vm.resolve_bootstrap_image", - otel.name = "vm.resolve_bootstrap_image", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - image.ref = %bootstrap_image_ref, - ) - }); - // Independent attempts can prepare images and private overlays at the - // same time. Workers serialize only shared cache publication. - let (attempt, stdout) = { - let mut registry = self.registry.lock().await; - let record = registry - .get_mut(sandbox_id) - .filter(|record| !record.deleting) - .ok_or_else(|| Status::cancelled("sandbox provisioning cancelled"))?; - if record.preparation.is_some() { - return Err(Status::failed_precondition( - "sandbox image preparation is already active", - )); - } - let mut attempt = - preparation::Attempt::create(&image_cache_root_dir(&self.config.state_dir)) - .map_err(|error| { - Status::internal(format!("create image preparation attempt: {error}")) - })?; - let stdout = attempt.spawn( - &self.launcher_bin, - preparation::Request { - config: self.config.clone(), - sandbox_id: sandbox_id.to_string(), - image_ref: image_ref.to_string(), - rootfs_tar: rootfs_tar.map(Path::to_path_buf), - bootstrap_only, - overlay, - lease_fd: -1, - parent_pid: 0, - }, - ); - let attempt = Arc::new(Mutex::new(attempt)); - record.preparation = Some(attempt.clone()); - (attempt, stdout) - }; - let _cleanup = preparation::CleanupOnDrop(attempt.clone()); - let outcome = async { - let stdout = stdout.map_err(|error| { - Status::internal(format!("start image preparation worker: {error}")) - })?; - let mut lines = tokio::io::BufReader::new(stdout).lines(); - let mut result = None; - while let Some(line) = lines.next_line().await.map_err(|error| { - Status::internal(format!("read image preparation progress: {error}")) - })? { - match serde_json::from_str::(&line).map_err(|error| { - Status::internal(format!("decode image preparation progress: {error}")) - })? { - preparation::Message::Event(bytes) => { - let event = - WatchSandboxesEvent::decode(bytes.as_slice()).map_err(|error| { - Status::internal(format!("decode image preparation event: {error}")) - })?; - if matches!(event.payload.as_ref(), Some(watch_sandboxes_event::Payload::PlatformEvent(value)) - if value.event.as_ref().is_some_and(|event| event.reason == "Pulled")) { - bootstrap_span.take(); - } - let _ = self.events.send(event); - } - preparation::Message::Complete(value) => result = Some(value), - } - } - let status = attempt.lock().await.wait().await.map_err(|error| { - Status::internal(format!("wait for image preparation: {error}")) - })?; - if !status.success() { - return Err(Status::failed_precondition(format!( - "image preparation worker exited with {status}" - ))); - } - result - .ok_or_else(|| { - Status::internal("image preparation worker exited without a result") - })? - .map_err(Status::failed_precondition) - } - .await; - if outcome.is_err() - && let Some(span) = bootstrap_span.as_ref() - { - span.record("otel.status_code", "ERROR"); - } - self.cleanup_image_preparation(sandbox_id).await?; - span_status.finish(outcome) - } - - async fn cleanup_image_preparation(&self, sandbox_id: &str) -> Result<(), Status> { - let attempt = self - .registry - .lock() - .await - .get(sandbox_id) - .and_then(|record| record.preparation.clone()); - if let Some(attempt) = attempt { - attempt.lock().await.cleanup().await?; - if let Some(record) = self.registry.lock().await.get_mut(sandbox_id) - && record - .preparation - .as_ref() - .is_some_and(|current| Arc::ptr_eq(current, &attempt)) - { - record.preparation = None; - } - } - Ok(()) - } - - fn image_staging_dir(&self, image_identity: &str) -> PathBuf { - self.preparation_root.as_ref().map_or_else( - || image_cache_staging_dir(&self.config.state_dir, image_identity), - |root| { - root.join(format!( - "{}.staging-{}", - sanitize_image_identity(image_identity), - unique_image_cache_suffix() - )) - }, - ) - } - - #[tracing::instrument( - name = "vm.prepare_images", - skip(self), - fields( - otel.name = "vm.prepare_images", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - image.ref = %image_ref, - ) - )] - async fn prepare_runtime_images( - &self, - sandbox_id: &str, - image_ref: &str, - rootfs_tar_path: Option<&Path>, - ) -> Result { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let bootstrap_image_ref = self.bootstrap_image_ref()?; - let bootstrap_image_identity = self - .ensure_cached_bootstrap_rootfs_image(sandbox_id, &bootstrap_image_ref) - .await?; - let root_disk = image_cache_rootfs_image(&self.config.state_dir, &bootstrap_image_identity); - - if let Some(tar_path) = rootfs_tar_path { - let prepared = self - .ensure_prepared_rootfs_tar_disk(sandbox_id, tar_path, &root_disk) - .await?; - return Ok(RuntimeImagePlan { - root_disk, - image_disk: Some(prepared.disk_path), - image_identity: prepared.image_identity, - bootstrap_image_identity, - }); - } - - if image_ref.trim() == bootstrap_image_ref.trim() { - return span_status.finish(Ok(RuntimeImagePlan { - root_disk, - image_disk: None, - image_identity: bootstrap_image_identity.clone(), - bootstrap_image_identity, - })); - } - - let prepared = self - .ensure_prepared_image_disk(sandbox_id, image_ref, &root_disk) - .await?; - span_status.finish(Ok(RuntimeImagePlan { - root_disk, - image_disk: Some(prepared.disk_path), - image_identity: prepared.image_identity, - bootstrap_image_identity, - })) - } - - fn bootstrap_image_ref(&self) -> Result { - self.bootstrap_image_ref_default() - .ok_or_else(|| { - Status::failed_precondition( - "vm driver requires bootstrap_image or default_image; the sandbox image cannot be used as the VM bootstrap image", - ) - }) - } - - fn bootstrap_image_ref_default(&self) -> Option { - let configured = self.config.bootstrap_image.trim(); - if !configured.is_empty() { - return Some(configured.to_string()); - } - let default = self.config.default_image.trim(); - if !default.is_empty() { - return Some(default.to_string()); - } - None - } - - #[tracing::instrument( - name = "vm.prepare_overlay", - skip_all, - fields( - otel.name = "vm.prepare_overlay", - otel.status_code = tracing::field::Empty, - overlay.path = %overlay_disk.display(), - preparation = ?preparation, - ) - )] - async fn prepare_runtime_overlay( - &self, - state_dir: &Path, - overlay_disk: &Path, - owner_source_disk: &Path, - preparation: OverlayPreparation, - requested_identity: Option<&WorkloadIdentityRequest>, - ) -> Result { - let span_status = openshell_otel::ErrorStatusGuard::current(); - let overlay_disk = overlay_disk.to_path_buf(); - let overlay_size_bytes = self - .config - .overlay_disk_mib - .checked_mul(1024 * 1024) - .ok_or_else(|| { - format!( - "overlay disk size {} MiB is too large", - self.config.overlay_disk_mib - ) - })?; - let (owner_state, write_owner_state) = sandbox_owner_state_for_launch( - state_dir, - &overlay_disk, - owner_source_disk, - &self.config, - preparation, - ) - .await?; - // Validate before creating or recovering an overlay. A conflicting - // request must never change the persisted owner or its files. - validate_vm_workload_identity(requested_identity, owner_state)?; - let owner_state_written_before_prepare = - write_owner_state && preparation == OverlayPreparation::Fresh; - if owner_state_written_before_prepare { - // Persist the selected identity before creating the overlay. A - // crash during preparation can then retry without misclassifying - // the partial overlay as legacy state. - write_sandbox_owner_state(state_dir, owner_state).await?; - } - - let template_path = overlay_template_image(&self.config.state_dir, overlay_size_bytes); - let overlay_metadata = tokio::fs::metadata(&overlay_disk).await; - let recover_preserved_overlay = preparation == OverlayPreparation::PreserveExisting - && overlay_metadata.as_ref().is_ok_and(fs::Metadata::is_file); - let publish_new_overlay = preparation == OverlayPreparation::Fresh - || matches!(overlay_metadata, Err(error) if error.kind() == std::io::ErrorKind::NotFound); - if !overlay_template_image_ready(&template_path, overlay_size_bytes).await? { - let _cache_guard = self.image_cache_lock.lock().await; - let template_path = template_path.clone(); - let staging_dir = self.image_staging_dir("overlay-template"); - let cache_root = image_cache_root_dir(&self.config.state_dir); - tokio::task::spawn_blocking(move || { - ensure_sandbox_overlay_template_image( - &cache_root, - &template_path, - overlay_size_bytes, - &staging_dir, - ) - }) - .await - .map_err(|err| format!("overlay template preparation panicked: {err}"))??; - } - - let overlay_to_recover = overlay_disk.clone(); - let staging_dir = self.image_staging_dir("writable-overlay"); - let result = tokio::task::spawn_blocking(move || { - if publish_new_overlay { - // An interrupted first start can leave no persisted overlay. - // Stage that retry just like a fresh copy, so cancellation - // cannot publish a partial disk as existing VM state. Other - // metadata errors still go through the preservation checks. - fs::create_dir_all(&staging_dir).map_err(|error| error.to_string())?; - let staging_overlay = staging_dir.join(SANDBOX_OVERLAY_IMAGE); - prepare_sandbox_overlay_image( - &template_path, - &staging_overlay, - preparation, - overlay_size_bytes, - )?; - fs::rename(&staging_overlay, &overlay_disk).map_err(|error| error.to_string()) - } else { - prepare_sandbox_overlay_image( - &template_path, - &overlay_disk, - preparation, - overlay_size_bytes, - ) - } - }) - .await - .map_err(|err| format!("overlay image preparation panicked: {err}"))?; - result?; - if recover_preserved_overlay { - tokio::task::spawn_blocking(move || recover_rootfs_image(&overlay_to_recover)) - .await - .map_err(|error| format!("overlay recovery panicked: {error}"))??; - } - if write_owner_state && !owner_state_written_before_prepare { - write_sandbox_owner_state(state_dir, owner_state).await?; - } - span_status.finish(Ok(owner_state)) - } - - fn resolved_sandbox_image(&self, sandbox: &Sandbox) -> Option { - requested_sandbox_image(sandbox) - .map(ToOwned::to_owned) - .or_else(|| { - let image = self.config.default_image.trim(); - (!image.is_empty()).then(|| image.to_string()) - }) - } - - #[tracing::instrument( - name = "vm.resolve_bootstrap_image", - skip(self), - fields( - otel.name = "vm.resolve_bootstrap_image", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - image.ref = %image_ref, - ) - )] - async fn ensure_cached_bootstrap_rootfs_image( - &self, - sandbox_id: &str, - image_ref: &str, - ) -> Result { - let span_status = openshell_otel::ErrorStatusGuard::current(); - if let Some((engine, image_identity)) = - self.resolve_local_container_image(image_ref).await? - { - let result = self - .ensure_cached_local_image_rootfs_image( - sandbox_id, - image_ref, - &engine, - &image_identity, - ) - .await; - return span_status.finish(result); - } - - span_status.finish( - self.ensure_cached_registry_rootfs_image( - sandbox_id, - image_ref, - ®istry_client(), - ®istry_auth(image_ref)?, - ) - .await, - ) - } - - fn publish_pulling_event(&self, sandbox_id: &str, image_ref: &str) { - self.publish_platform_event( - sandbox_id.to_string(), - platform_event( - "vm", - "Normal", - "Pulling", - format!("Pulling image \"{image_ref}\""), - ), - ); - } - - /// A registry-sourced root disk found in the cache: `Pulling`, the - /// `CacheHit` progress and `Pulled`, so the image step still advances. - async fn publish_registry_cache_hit( - &self, - sandbox_id: &str, - image_ref: &str, - image_identity: &str, - image_path: &Path, - ) { - self.publish_pulling_event(sandbox_id, image_ref); - self.publish_vm_progress( - sandbox_id, - "CacheHit", - format!("Using cached VM root disk for image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ("cache_hit".to_string(), "true".to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ]), - ); - self.publish_pulled_event(sandbox_id, image_ref, image_path) - .await; - } - - async fn ensure_cached_registry_rootfs_image( - &self, - sandbox_id: &str, - image_ref: &str, - client: &OciClient, - auth: &RegistryAuth, - ) -> Result { - let span_status = openshell_otel::ErrorStatusGuard::current(); - info!(image_ref = %image_ref, "vm driver: ensuring cached root disk image (registry)"); - let reference = parse_registry_reference(image_ref)?; - // A digest pin already names the image's content, and a cached root - // disk is only published after its manifest was verified against - // that digest. On a hit the registry cannot add anything, so neither - // authenticate nor resolve: the sandbox boots from the cache without a - // network round trip, and keeps booting while the registry is down. - // Tags still resolve through the registry below. - if let Some(digest) = reference.digest() { - let image_identity = bootstrap_image_cache_identity(digest); - let image_path = image_cache_rootfs_image(&self.config.state_dir, &image_identity); - if tokio::fs::metadata(&image_path).await.is_ok() { - info!( - image_identity = %image_identity, - image_path = %image_path.display(), - "vm driver: root disk image cache hit (digest-pinned, no registry call)" - ); - self.publish_registry_cache_hit( - sandbox_id, - image_ref, - &image_identity, - &image_path, - ) - .await; - return span_status.finish(Ok(image_identity)); - } - } - info!(image_ref = %image_ref, "vm driver: authenticating with registry"); - self.publish_vm_progress( - sandbox_id, - "AuthenticatingRegistry", - format!("Authenticating registry access for image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ]), - ); - retry_registry_request("authenticate with registry", || { - client.auth(&reference, auth, RegistryOperation::Pull) - }) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "failed to authenticate registry access for vm sandbox image '{image_ref}': {err}" - )) - })?; - info!(image_ref = %image_ref, "vm driver: fetching manifest digest"); - self.publish_vm_progress( - sandbox_id, - "FetchingManifest", - format!("Fetching manifest for image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ]), - ); - let (reference, source_image_identity) = pin_registry_reference(client, &reference, auth) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "failed to resolve vm sandbox image '{image_ref}': {err}" - )) - })?; - info!( - image_ref = %image_ref, - image_identity = %source_image_identity, - "vm driver: manifest digest resolved" - ); - let image_identity = bootstrap_image_cache_identity(&source_image_identity); - let image_path = image_cache_rootfs_image(&self.config.state_dir, &image_identity); - - if tokio::fs::metadata(&image_path).await.is_ok() { - info!( - image_identity = %image_identity, - image_path = %image_path.display(), - "vm driver: root disk image cache hit (no build needed)" - ); - self.publish_registry_cache_hit(sandbox_id, image_ref, &image_identity, &image_path) - .await; - return span_status.finish(Ok(image_identity)); - } - - // A driver progress hint before the build, so the image step advances. - self.publish_pulling_event(sandbox_id, image_ref); - - info!( - image_identity = %image_identity, - "vm driver: root disk image cache miss, acquiring build lock" - ); - self.publish_vm_progress( - sandbox_id, - "CacheMiss", - format!("Preparing VM root disk cache for image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ("cache_hit".to_string(), "false".to_string()), - ("image_identity".to_string(), image_identity.clone()), - ]), - ); - self.publish_vm_progress( - sandbox_id, - "WaitingForImageCacheLock", - "Waiting for VM image cache build lock".to_string(), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_identity".to_string(), image_identity.clone()), - ]), - ); - let _cache_guard = self.image_cache_lock.lock().await; - info!( - image_identity = %image_identity, - "vm driver: build lock acquired" - ); - if tokio::fs::metadata(&image_path).await.is_ok() { - info!( - image_identity = %image_identity, - "vm driver: root disk image cache hit after lock (built by another task)" - ); - self.publish_vm_progress( - sandbox_id, - "CacheHit", - format!("Using cached VM root disk for image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ("cache_hit".to_string(), "true".to_string()), - ("image_identity".to_string(), image_identity.clone()), - ]), - ); - self.publish_pulled_event(sandbox_id, image_ref, &image_path) - .await; - return span_status.finish(Ok(image_identity)); - } - - self.build_cached_registry_image_rootfs_image( - sandbox_id, - client, - &reference, - auth, - image_ref, - &image_identity, - ) - .await?; - self.publish_pulled_event(sandbox_id, image_ref, &image_path) - .await; - span_status.finish(Ok(image_identity)) - } - - async fn resolve_local_container_image( - &self, - image_ref: &str, - ) -> Result, Status> { - let required_local_image = is_openshell_local_build_image_ref(image_ref); - let engine = match connect_local_container_engine().await { - Some(engine) => engine, - None if required_local_image => { - return Err(Status::failed_precondition(format!( - "no container engine (Docker/Podman) available for locally built sandbox image '{image_ref}'" - ))); - } - None => { - warn!( - image_ref = %image_ref, - "vm driver: no local container engine available, falling back to registry" - ); - return Ok(None); - } - }; - - match engine.inspect_image(image_ref).await { - Ok(inspect) => { - if let Some(message) = local_image_platform_mismatch( - image_ref, - inspect.os.as_deref(), - inspect.architecture.as_deref(), - ) { - if required_local_image { - return Err(Status::failed_precondition(message)); - } - warn!( - image_ref = %image_ref, - %message, - "vm driver: local container image platform mismatch, falling back to registry" - ); - return Ok(None); - } - - let image_identity = inspect.id.filter(|id| !id.trim().is_empty()).ok_or_else( - || { - Status::failed_precondition(format!( - "local container image '{image_ref}' inspect response has no image ID" - )) - }, - )?; - info!( - image_ref = %image_ref, - image_identity = %image_identity, - "vm driver: resolved image from local container engine" - ); - Ok(Some((engine, image_identity))) - } - Err(err) if is_docker_not_found_error(&err) && required_local_image => { - Err(Status::failed_precondition(format!( - "locally built sandbox image '{image_ref}' is not present in the local container engine" - ))) - } - Err(err) if is_docker_not_found_error(&err) => Ok(None), - Err(err) if required_local_image => Err(Status::failed_precondition(format!( - "failed to inspect locally built sandbox image '{image_ref}': {err}" - ))), - Err(err) => { - warn!( - image_ref = %image_ref, - error = %err, - "vm driver: local container image inspection failed, falling back to registry" - ); - Ok(None) - } - } - } - - async fn ensure_cached_local_image_rootfs_image( - &self, - sandbox_id: &str, - image_ref: &str, - docker: &Docker, - image_identity: &str, - ) -> Result { - let cache_identity = bootstrap_image_cache_identity(image_identity); - let image_path = image_cache_rootfs_image(&self.config.state_dir, &cache_identity); - - self.publish_platform_event( - sandbox_id.to_string(), - platform_event( - "vm", - "Normal", - "Pulling", - format!("Pulling image \"{image_ref}\""), - ), - ); - - if tokio::fs::metadata(&image_path).await.is_ok() { - self.publish_vm_progress( - sandbox_id, - "CacheHit", - format!("Using cached VM root disk for local image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "local_docker".to_string()), - ("cache_hit".to_string(), "true".to_string()), - ("image_identity".to_string(), cache_identity.clone()), - ]), - ); - self.publish_pulled_event(sandbox_id, image_ref, &image_path) - .await; - return Ok(cache_identity); - } - - self.publish_vm_progress( - sandbox_id, - "CacheMiss", - format!("Preparing VM root disk cache for local image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "local_docker".to_string()), - ("cache_hit".to_string(), "false".to_string()), - ("image_identity".to_string(), cache_identity.clone()), - ]), - ); - self.publish_vm_progress( - sandbox_id, - "WaitingForImageCacheLock", - "Waiting for VM image cache build lock".to_string(), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_identity".to_string(), cache_identity.clone()), - ]), - ); - let _cache_guard = self.image_cache_lock.lock().await; - if tokio::fs::metadata(&image_path).await.is_ok() { - self.publish_vm_progress( - sandbox_id, - "CacheHit", - format!("Using cached VM root disk for local image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "local_docker".to_string()), - ("cache_hit".to_string(), "true".to_string()), - ("image_identity".to_string(), cache_identity.clone()), - ]), - ); - self.publish_pulled_event(sandbox_id, image_ref, &image_path) - .await; - return Ok(cache_identity); - } - - self.build_cached_local_image_rootfs_image(sandbox_id, docker, image_ref, &cache_identity) - .await?; - self.publish_pulled_event(sandbox_id, image_ref, &image_path) - .await; - Ok(cache_identity) - } - - async fn ensure_prepared_image_disk( - &self, - sandbox_id: &str, - image_ref: &str, - bootstrap_root_disk: &Path, - ) -> Result { - if let Some((docker, image_identity)) = - self.resolve_local_container_image(image_ref).await? - { - return self - .ensure_prepared_local_image_disk( - sandbox_id, - image_ref, - &docker, - &image_identity, - bootstrap_root_disk, - ) - .await; - } - - self.ensure_prepared_registry_image_disk( - sandbox_id, - image_ref, - bootstrap_root_disk, - ®istry_client(), - ®istry_auth(image_ref)?, - ) - .await - } - - async fn ensure_prepared_local_image_disk( - &self, - sandbox_id: &str, - image_ref: &str, - docker: &Docker, - image_identity: &str, - bootstrap_root_disk: &Path, - ) -> Result { - let cache_identity = prepared_image_cache_identity(image_identity, &self.config); - let image_path = image_cache_rootfs_image(&self.config.state_dir, &cache_identity); - - if tokio::fs::metadata(&image_path).await.is_ok() { - self.publish_prepared_cache_hit(sandbox_id, image_ref, "local_docker", &cache_identity); - return Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }); - } - - self.publish_prepared_cache_miss(sandbox_id, image_ref, "local_docker", &cache_identity); - let _cache_guard = self.image_cache_lock.lock().await; - if tokio::fs::metadata(&image_path).await.is_ok() { - self.publish_prepared_cache_hit(sandbox_id, image_ref, "local_docker", &cache_identity); - return Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }); - } - - let staging_dir = self.image_staging_dir(&cache_identity); - let rootfs_archive = staging_dir.join(IMAGE_EXPORT_ROOTFS_ARCHIVE); - self.reset_image_staging_dir(&staging_dir).await?; - - self.publish_vm_progress( - sandbox_id, - "ExportingRootfs", - format!("Exporting rootfs from local image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "local_docker".to_string()), - ("image_identity".to_string(), cache_identity.clone()), - ]), - ); - if let Err(err) = - export_local_image_rootfs_to_path(docker, image_ref, &rootfs_archive).await - { - let _ = tokio::fs::remove_dir_all(&staging_dir).await; - return Err(err); - } - - let payload = GuestImagePayload { - image_ref: image_ref.to_string(), - image_identity: cache_identity.clone(), - source: GuestImagePayloadSource::LocalDocker { rootfs_archive }, - }; - self.build_prepared_image_disk( - sandbox_id, - image_ref, - "local_docker", - &cache_identity, - bootstrap_root_disk, - &staging_dir, - &payload, - ) - .await?; - - Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }) - } - - async fn ensure_prepared_rootfs_tar_disk( - &self, - sandbox_id: &str, - tar_path: &Path, - bootstrap_root_disk: &Path, - ) -> Result { - let request_staging_dir = tar_path.parent().map(Path::to_path_buf); - let cleanup_request_staging = || async { - if let Some(d) = &request_staging_dir { - let _ = tokio::fs::remove_dir_all(d).await; - } - }; - - // Identity comes from the archive contents. See `rootfs_tar_cache_identity`. - let hash_source = tar_path.to_path_buf(); - let source_digest = match tokio::task::spawn_blocking(move || { - compute_file_sha256_hex(&hash_source) - }) - .await - { - Ok(Ok(digest)) => digest, - Ok(Err(err)) => { - cleanup_request_staging().await; - return Err(Status::failed_precondition(format!( - "rootfs tar not readable at {}: {err}", - tar_path.display() - ))); - } - Err(err) => { - cleanup_request_staging().await; - return Err(Status::internal(format!( - "failed to hash rootfs tar at {}: {err}", - tar_path.display() - ))); - } - }; - let cache_identity = rootfs_tar_cache_identity(&source_digest, &self.config); - let image_path = image_cache_rootfs_image(&self.config.state_dir, &cache_identity); - let tar_display = tar_path.display().to_string(); - - if tokio::fs::metadata(&image_path).await.is_ok() { - self.publish_prepared_cache_hit( - sandbox_id, - &tar_display, - "rootfs_tar", - &cache_identity, - ); - cleanup_request_staging().await; - return Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }); - } - - self.publish_prepared_cache_miss(sandbox_id, &tar_display, "rootfs_tar", &cache_identity); - let _cache_guard = self.image_cache_lock.lock().await; - if tokio::fs::metadata(&image_path).await.is_ok() { - self.publish_prepared_cache_hit( - sandbox_id, - &tar_display, - "rootfs_tar", - &cache_identity, - ); - cleanup_request_staging().await; - return Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }); - } - - let staging_dir = self.image_staging_dir(&cache_identity); - let rootfs_archive = staging_dir.join(IMAGE_EXPORT_ROOTFS_ARCHIVE); - self.reset_image_staging_dir(&staging_dir).await?; - - self.publish_vm_progress( - sandbox_id, - "CopyingRootfsTar", - format!("Copying rootfs tar \"{tar_display}\""), - HashMap::from([ - ("rootfs_tar_path".to_string(), tar_display.clone()), - ("image_source".to_string(), "rootfs_tar".to_string()), - ("image_identity".to_string(), cache_identity.clone()), - ]), - ); - let copy_src = tar_path.to_path_buf(); - let copy_dst = rootfs_archive.clone(); - let max_bytes = self.config.rootfs_tar_max_bytes(); - let copied_digest = match tokio::task::spawn_blocking(move || { - stage_rootfs_tar_archive(©_src, ©_dst, max_bytes) - }) - .await - { - Ok(Ok(digest)) => digest, - Ok(Err(err)) => { - let _ = tokio::fs::remove_dir_all(&staging_dir).await; - cleanup_request_staging().await; - return Err(Status::internal(format!( - "failed to copy rootfs tar to staging: {err}" - ))); - } - Err(err) => { - let _ = tokio::fs::remove_dir_all(&staging_dir).await; - cleanup_request_staging().await; - return Err(Status::internal(format!( - "failed to copy rootfs tar to staging: {err}" - ))); - } - }; - - // The archive changed between the hash pass and the copy: the prepared - // disk we are about to build would not match the identity it is cached - // under. Reject rather than poison the cache. - if copied_digest != source_digest { - let _ = tokio::fs::remove_dir_all(&staging_dir).await; - cleanup_request_staging().await; - return Err(Status::aborted(format!( - "rootfs tar {tar_display} changed while it was being staged; retry the request" - ))); - } - cleanup_request_staging().await; - - let payload = GuestImagePayload { - image_ref: tar_display.clone(), - image_identity: cache_identity.clone(), - source: GuestImagePayloadSource::LocalDocker { rootfs_archive }, - }; - self.build_prepared_image_disk( - sandbox_id, - &tar_display, - "rootfs_tar", - &cache_identity, - bootstrap_root_disk, - &staging_dir, - &payload, - ) - .await?; - - Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }) - } - - async fn ensure_prepared_registry_image_disk( - &self, - sandbox_id: &str, - image_ref: &str, - bootstrap_root_disk: &Path, - client: &OciClient, - auth: &RegistryAuth, - ) -> Result { - let reference = parse_registry_reference(image_ref)?; - - self.publish_vm_progress( - sandbox_id, - "AuthenticatingRegistry", - format!("Authenticating registry access for image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ]), - ); - retry_registry_request("authenticate with registry", || { - client.auth(&reference, auth, RegistryOperation::Pull) - }) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "failed to authenticate registry access for vm sandbox image '{image_ref}': {err}" - )) - })?; - - self.publish_vm_progress( - sandbox_id, - "FetchingManifest", - format!("Fetching manifest for image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ]), - ); - let (reference, source_image_identity) = pin_registry_reference(client, &reference, auth) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "failed to resolve vm sandbox image '{image_ref}': {err}" - )) - })?; - let cache_identity = prepared_image_cache_identity(&source_image_identity, &self.config); - let image_path = image_cache_rootfs_image(&self.config.state_dir, &cache_identity); - - if tokio::fs::metadata(&image_path).await.is_ok() { - self.publish_prepared_cache_hit(sandbox_id, image_ref, "registry", &cache_identity); - return Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }); - } - - self.publish_prepared_cache_miss(sandbox_id, image_ref, "registry", &cache_identity); - let _cache_guard = self.image_cache_lock.lock().await; - if tokio::fs::metadata(&image_path).await.is_ok() { - self.publish_prepared_cache_hit(sandbox_id, image_ref, "registry", &cache_identity); - return Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }); - } - - let staging_dir = self.image_staging_dir(&cache_identity); - self.reset_image_staging_dir(&staging_dir).await?; - let layout_dir = staging_dir.join(GUEST_IMAGE_OCI_LAYOUT_DIR); - - let (manifest, _) = retry_registry_request("pull image manifest", || { - client.pull_image_manifest(&reference, auth) - }) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "failed to pull vm sandbox image manifest '{image_ref}': {err}" - )) - })?; - tokio::fs::create_dir_all(oci_layout_blobs_dir(&layout_dir)) - .await - .map_err(|err| Status::internal(format!("create guest OCI layout failed: {err}")))?; - - download_registry_descriptor_blob_file( - client, - &reference, - image_ref, - &layout_dir, - &manifest.config, - "config", - ) - .await?; - - let total_layers = manifest.layers.len(); - let total_bytes: i64 = manifest.layers.iter().map(|layer| layer.size.max(0)).sum(); - futures::stream::iter(manifest.layers.iter().cloned().enumerate()) - .map(|(index, layer)| { - let client = client.clone(); - let reference = reference.clone(); - let layout_dir = layout_dir.clone(); - async move { - self.publish_registry_layer_progress( - sandbox_id, - image_ref, - &layer, - index, - total_layers, - total_bytes, - ); - download_registry_descriptor_blob_file( - &client, - &reference, - image_ref, - &layout_dir, - &layer, - &format!("layer {}", index + 1), - ) - .await - } - }) - .buffer_unordered(registry_layer_download_concurrency()) - .try_collect::>() - .await?; - - write_oci_layout_for_manifest(&layout_dir, GUEST_IMAGE_OCI_REF, &manifest) - .map_err(|err| Status::internal(format!("write OCI layout failed: {err}")))?; - - let payload = GuestImagePayload { - image_ref: image_ref.to_string(), - image_identity: cache_identity.clone(), - source: GuestImagePayloadSource::RegistryOciLayout { layout_dir }, - }; - self.build_prepared_image_disk( - sandbox_id, - image_ref, - "registry", - &cache_identity, - bootstrap_root_disk, - &staging_dir, - &payload, - ) - .await?; - - Ok(PreparedImageDisk { - image_identity: cache_identity, - disk_path: image_path, - }) - } - - async fn reset_image_staging_dir(&self, staging_dir: &Path) -> Result<(), Status> { - tokio::fs::create_dir_all(image_cache_root_dir(&self.config.state_dir)) - .await - .map_err(|err| Status::internal(format!("create image cache dir failed: {err}")))?; - if tokio::fs::metadata(staging_dir).await.is_ok() { - tokio::fs::remove_dir_all(staging_dir) - .await - .map_err(|err| { - Status::internal(format!( - "remove stale image cache staging dir failed: {err}" - )) - })?; - } - tokio::fs::create_dir_all(staging_dir).await.map_err(|err| { - Status::internal(format!("create image cache staging dir failed: {err}")) - }) - } - - #[allow(clippy::too_many_arguments)] - async fn build_prepared_image_disk( - &self, - sandbox_id: &str, - image_ref: &str, - image_source: &str, - image_identity: &str, - bootstrap_root_disk: &Path, - staging_dir: &Path, - payload: &GuestImagePayload, - ) -> Result<(), Status> { - let cache_dir = image_cache_dir(&self.config.state_dir, image_identity); - let image_path = image_cache_rootfs_image(&self.config.state_dir, image_identity); - let prepared_image = staging_dir.join(IMAGE_CACHE_ROOTFS_IMAGE); - tokio::fs::create_dir_all(&cache_dir).await.map_err(|err| { - Status::internal(format!("create prepared image cache dir failed: {err}")) - })?; - - let payload_for_size = payload.clone(); - let min_size = self - .config - .overlay_disk_mib - .checked_mul(1024 * 1024) - .ok_or_else(|| Status::internal("prepared image disk size overflow"))?; - let image_size = tokio::task::spawn_blocking(move || { - prepared_image_disk_size_bytes(&payload_for_size, min_size) - }) - .await - .map_err(|err| { - Status::internal(format!("prepared image size calculation panicked: {err}")) - })? - .map_err(Status::internal)?; - - let payload_for_disk = payload.clone(); - let prepared_image_for_disk = prepared_image.clone(); - self.publish_vm_progress( - sandbox_id, - "CreatingRootDisk", - "Formatting prepared VM image disk".to_string(), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), image_source.to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ]), - ); - tokio::task::spawn_blocking(move || { - create_image_prep_disk(&prepared_image_for_disk, image_size, &payload_for_disk) - }) - .await - .map_err(|err| Status::internal(format!("prepared image disk build panicked: {err}")))? - .map_err(Status::failed_precondition)?; - - self.publish_vm_progress( - sandbox_id, - "PreparingRootfs", - format!("Preparing VM image rootfs for \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), image_source.to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ]), - ); - if let Err(err) = self - .run_image_prep_vm(bootstrap_root_disk, &prepared_image, staging_dir) - .await - { - let _ = tokio::fs::remove_dir_all(staging_dir).await; - return Err(err); - } - - // The prep VM exits successfully even when guest init fails, so check - // the disk itself. Caching a disk without the rootfs would break every - // later sandbox that uses this image. - let prepared_image_for_check = prepared_image.clone(); - let has_rootfs = tokio::task::spawn_blocking(move || { - ext4_image_has_directory(&prepared_image_for_check, PREPARED_IMAGE_ROOTFS_DIR) - }) - .await - .map_err(|err| Status::internal(format!("prepared image validation panicked: {err}")))?; - if !matches!(has_rootfs, Ok(true)) { - let mut message = format!( - "image-prep for \"{image_ref}\" did not produce {PREPARED_IMAGE_ROOTFS_DIR}" - ); - if let Err(err) = &has_rootfs { - write!(message, ": {err}").expect("writing to String cannot fail"); - } - if let Some(console) = read_vm_console_tail( - &staging_dir.join(IMAGE_PREP_CONSOLE_LOG), - VM_CONSOLE_DIAGNOSTIC_BYTES, - ) { - write!(message, "; guest console tail:\n{console}") - .expect("writing to String cannot fail"); - } - let _ = tokio::fs::remove_dir_all(staging_dir).await; - return Err(Status::failed_precondition(message)); - } - - self.publish_prepared_image(&prepared_image, &image_path) - .await?; - let _ = tokio::fs::remove_dir_all(staging_dir).await; - Ok(()) - } - - async fn publish_prepared_image( - &self, - staged: &Path, - destination: &Path, - ) -> Result<(), Status> { - let cache_root = image_cache_root_dir(&self.config.state_dir); - let staged = staged.to_path_buf(); - let destination = destination.to_path_buf(); - tokio::task::spawn_blocking(move || { - preparation::publish_cache_file(&cache_root, &staged, &destination, None) - }) - .await - .map_err(|error| Status::internal(format!("cache publication panicked: {error}")))? - .map_err(|error| Status::internal(format!("store cached rootfs image failed: {error}"))) - } - - #[allow(clippy::similar_names)] - async fn run_image_prep_vm( - &self, - bootstrap_root_disk: &Path, - prep_disk: &Path, - run_dir: &Path, - ) -> Result<(), Status> { - let console_output = run_dir.join(IMAGE_PREP_CONSOLE_LOG); - let mut command = Command::new(&self.launcher_bin); - command.kill_on_drop(true); - command.stdin(Stdio::null()); - // Worker stdout carries framed progress and completion messages. - command.stdout(Stdio::from(std::io::stderr())); - command.stderr(Stdio::inherit()); - command.arg("--internal-run-vm"); - command.arg("--vm-root-disk").arg(bootstrap_root_disk); - command.arg("--vm-overlay-disk").arg(prep_disk); - command.arg("--vm-exec").arg(sandbox_guest_init_path()); - command.arg("--vm-workdir").arg("/"); - command.arg("--vm-console-output").arg(&console_output); - command.arg("--vm-vcpus").arg(self.config.vcpus.to_string()); - command - .arg("--vm-mem-mib") - .arg(self.config.mem_mib.to_string()); - command - .arg("--vm-krun-log-level") - .arg(self.config.krun_log_level.to_string()); - command - .arg("--vm-env") - .arg(format!("OPENSHELL_VM_INIT_MODE={IMAGE_PREP_INIT_MODE}")); - if let Some((uid, gid)) = configured_sandbox_identity(&self.config) { - command - .arg("--vm-env") - .arg(format!("OPENSHELL_VM_SANDBOX_UID={uid}")); - command - .arg("--vm-env") - .arg(format!("OPENSHELL_VM_SANDBOX_GID={gid}")); - } - - let mut child = command - .spawn() - .map_err(|err| Status::internal(format!("failed to run image-prep vm: {err}")))?; - let status = child - .wait() - .await - .map_err(|err| Status::internal(format!("failed to wait for image-prep vm: {err}")))?; - if status.success() { - return Ok(()); - } - let console = tokio::fs::read_to_string(&console_output) - .await - .unwrap_or_default(); - Err(Status::failed_precondition(format!( - "image-prep vm exited with status {status}: {console}" - ))) - } - - fn publish_prepared_cache_hit( - &self, - sandbox_id: &str, - image_ref: &str, - image_source: &str, - image_identity: &str, - ) { - self.publish_vm_progress( - sandbox_id, - "CacheHit", - format!("Using cached prepared VM image disk for \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), image_source.to_string()), - ("cache_hit".to_string(), "true".to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ]), - ); - } - - fn publish_prepared_cache_miss( - &self, - sandbox_id: &str, - image_ref: &str, - image_source: &str, - image_identity: &str, - ) { - self.publish_vm_progress( - sandbox_id, - "CacheMiss", - format!("Preparing VM image disk cache for \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), image_source.to_string()), - ("cache_hit".to_string(), "false".to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ]), - ); - } - - #[allow(clippy::similar_names)] - async fn build_cached_local_image_rootfs_image( - &self, - sandbox_id: &str, - docker: &Docker, - image_ref: &str, - image_identity: &str, - ) -> Result<(), Status> { - let cache_dir = image_cache_dir(&self.config.state_dir, image_identity); - let image_path = image_cache_rootfs_image(&self.config.state_dir, image_identity); - let staging_dir = self.image_staging_dir(image_identity); - let exported_rootfs = staging_dir.join(IMAGE_EXPORT_ROOTFS_ARCHIVE); - let prepared_rootfs = staging_dir.join("rootfs"); - let prepared_image = staging_dir.join(IMAGE_CACHE_ROOTFS_IMAGE); - - tokio::fs::create_dir_all(image_cache_root_dir(&self.config.state_dir)) - .await - .map_err(|err| Status::internal(format!("create image cache dir failed: {err}")))?; - tokio::fs::create_dir_all(&cache_dir) - .await - .map_err(|err| Status::internal(format!("create image cache dir failed: {err}")))?; - - if tokio::fs::metadata(&staging_dir).await.is_ok() { - tokio::fs::remove_dir_all(&staging_dir) - .await - .map_err(|err| { - Status::internal(format!( - "remove stale image cache staging dir failed: {err}" - )) - })?; - } - tokio::fs::create_dir_all(&staging_dir) - .await - .map_err(|err| { - Status::internal(format!("create image cache staging dir failed: {err}")) - })?; - - self.publish_vm_progress( - sandbox_id, - "ExportingRootfs", - format!("Exporting rootfs from local image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "local_docker".to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ]), - ); - if let Err(err) = - export_local_image_rootfs_to_path(docker, image_ref, &exported_rootfs).await - { - let _ = tokio::fs::remove_dir_all(&staging_dir).await; - return Err(err); - } - - let image_ref_owned = image_ref.to_string(); - let image_identity_owned = image_identity.to_string(); - let exported_rootfs_for_build = exported_rootfs.clone(); - let prepared_rootfs_for_build = prepared_rootfs.clone(); - let (sandbox_uid, sandbox_gid) = configured_sandbox_identity(&self.config) - .map_or((None, None), |(uid, gid)| (Some(uid), Some(gid))); - self.publish_vm_progress( - sandbox_id, - "PreparingRootfs", - format!("Preparing VM rootfs for local image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "local_docker".to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ( - "sandbox_uid".to_string(), - sandbox_uid.map_or_else(|| "image".to_string(), |uid| uid.to_string()), - ), - ]), - ); - let prepare_result = tokio::task::spawn_blocking(move || { - extract_rootfs_archive_to(&exported_rootfs_for_build, &prepared_rootfs_for_build)?; - prepare_sandbox_rootfs_from_image_root( - &prepared_rootfs_for_build, - &image_identity_owned, - sandbox_uid, - sandbox_gid, - ) - .map_err(|err| { - format!("vm sandbox image '{image_ref_owned}' is not base-compatible: {err}") - }) - }) - .await - .map_err(|err| Status::internal(format!("local image preparation panicked: {err}")))?; - - if let Err(err) = prepare_result { - let _ = tokio::fs::remove_dir_all(&staging_dir).await; - return Err(Status::failed_precondition(err)); - } - - self.publish_vm_progress( - sandbox_id, - "CreatingRootDisk", - "Formatting VM root disk image".to_string(), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "local_docker".to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ]), - ); - let prepared_rootfs_for_build = prepared_rootfs.clone(); - let prepared_image_for_build = prepared_image.clone(); - let build_result = tokio::task::spawn_blocking(move || { - create_rootfs_image_from_dir(&prepared_rootfs_for_build, &prepared_image_for_build) - }) - .await - .map_err(|err| Status::internal(format!("rootfs image build panicked: {err}")))?; - - if let Err(err) = build_result { - let _ = tokio::fs::remove_dir_all(&staging_dir).await; - return Err(Status::failed_precondition(err)); - } - - self.publish_prepared_image(&prepared_image, &image_path) - .await?; - let _ = tokio::fs::remove_dir_all(&staging_dir).await; - Ok(()) - } - - #[allow(clippy::similar_names)] - async fn build_cached_registry_image_rootfs_image( - &self, - sandbox_id: &str, - client: &OciClient, - reference: &Reference, - auth: &RegistryAuth, - image_ref: &str, - image_identity: &str, - ) -> Result<(), Status> { - let cache_dir = image_cache_dir(&self.config.state_dir, image_identity); - let image_path = image_cache_rootfs_image(&self.config.state_dir, image_identity); - let staging_dir = self.image_staging_dir(image_identity); - let prepared_rootfs = staging_dir.join("rootfs"); - let prepared_image = staging_dir.join(IMAGE_CACHE_ROOTFS_IMAGE); - - tokio::fs::create_dir_all(image_cache_root_dir(&self.config.state_dir)) - .await - .map_err(|err| Status::internal(format!("create image cache dir failed: {err}")))?; - - if tokio::fs::metadata(&staging_dir).await.is_ok() { - remove_bootstrap_staging(&staging_dir) - .await - .map_err(|err| { - Status::internal(format!( - "remove stale image cache staging dir failed: {err}" - )) - })?; - } - tokio::fs::create_dir_all(&staging_dir) - .await - .map_err(|err| { - Status::internal(format!("create image cache staging dir failed: {err}")) - })?; - - info!( - image_ref = %image_ref, - staging_dir = %staging_dir.display(), - "vm driver: pulling registry image layers" - ); - if let Err(err) = self - .pull_registry_image_rootfs( - sandbox_id, - client, - reference, - auth, - image_ref, - &staging_dir, - &prepared_rootfs, - ) - .await - { - warn!( - image_ref = %image_ref, - error = %err.message(), - "vm driver: pull_registry_image_rootfs failed" - ); - let _ = remove_bootstrap_staging(&staging_dir).await; - return Err(err); - } - info!( - image_ref = %image_ref, - "vm driver: image layers pulled, preparing rootfs image" - ); - - let image_ref_owned = image_ref.to_string(); - let image_identity_owned = image_identity.to_string(); - let prepared_rootfs_for_build = prepared_rootfs.clone(); - let (sandbox_uid, sandbox_gid) = configured_sandbox_identity(&self.config) - .map_or((None, None), |(uid, gid)| (Some(uid), Some(gid))); - self.publish_vm_progress( - sandbox_id, - "PreparingRootfs", - format!("Preparing VM rootfs for image \"{image_ref}\""), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ( - "sandbox_uid".to_string(), - sandbox_uid.map_or_else(|| "image".to_string(), |uid| uid.to_string()), - ), - ]), - ); - let prepare_result = tokio::task::spawn_blocking(move || { - prepare_sandbox_rootfs_from_image_root( - &prepared_rootfs_for_build, - &image_identity_owned, - sandbox_uid, - sandbox_gid, - ) - .map_err(|err| { - format!("vm sandbox image '{image_ref_owned}' is not base-compatible: {err}") - }) - }) - .await - .map_err(|err| Status::internal(format!("image rootfs preparation panicked: {err}")))?; - - if let Err(err) = prepare_result { - warn!( - image_ref = %image_ref, - error = %err, - "vm driver: rootfs preparation failed" - ); - let _ = remove_bootstrap_staging(&staging_dir).await; - return Err(Status::failed_precondition(err)); - } - - self.publish_vm_progress( - sandbox_id, - "CreatingRootDisk", - "Formatting VM root disk image".to_string(), - HashMap::from([ - ("image_ref".to_string(), image_ref.to_string()), - ("image_source".to_string(), "registry".to_string()), - ("image_identity".to_string(), image_identity.to_string()), - ]), - ); - let prepared_rootfs_for_build = prepared_rootfs.clone(); - let prepared_image_for_build = prepared_image.clone(); - let build_result = tokio::task::spawn_blocking(move || { - create_rootfs_image_from_dir(&prepared_rootfs_for_build, &prepared_image_for_build) - }) - .await - .map_err(|err| Status::internal(format!("image rootfs build panicked: {err}")))?; - - if let Err(err) = build_result { - warn!( - image_ref = %image_ref, - error = %err, - "vm driver: rootfs image build failed" - ); - let _ = remove_bootstrap_staging(&staging_dir).await; - return Err(Status::failed_precondition(err)); - } - - let published = async { - tokio::fs::create_dir_all(&cache_dir) - .await - .map_err(|err| Status::internal(format!("create image cache dir failed: {err}")))?; - self.publish_prepared_image(&prepared_image, &image_path) - .await - } - .await; - let _ = remove_bootstrap_staging(&staging_dir).await; - published - } - - /// Watch the launcher child process and surface errors as driver - /// conditions. - /// - /// The driver no longer owns the `Ready` transition — the gateway - /// promotes a sandbox to `Ready` the moment its supervisor session - /// lands (see `openshell-server/src/compute/mod.rs`). This loop only - /// handles the sad paths: the child process failing to start, exiting - /// abnormally, or becoming unpollable. Those still surface as driver - /// `Error` conditions so the gateway can reason about a dead VM. - async fn monitor_sandbox(&self, sandbox_id: String) { - loop { - let process = { - let registry = self.registry.lock().await; - let Some(record) = registry.get(&sandbox_id) else { - return; - }; - let Some(process) = record.process.as_ref() else { - return; - }; - process.clone() - }; - - let poll_result = { - let mut process = process.lock().await; - if process.deleting { - return; - } - match process.child.try_wait() { - Ok(Some(status)) => Ok(Some(("VM", status))), - Ok(None) => process - .supervisor - .try_wait() - .map(|status| status.map(|status| ("host supervisor", status))), - Err(error) => Err(error), - } - }; - - let exit_status = match poll_result { - Ok(status) => status, - Err(err) => { - if let Some(snapshot) = self - .set_snapshot_condition( - &sandbox_id, - error_condition("ProcessPollFailed", &err.to_string()), - false, - ) - .await - { - self.publish_snapshot(snapshot); - } - self.publish_platform_event( - sandbox_id.clone(), - platform_event( - "vm", - "Warning", - "ProcessPollFailed", - format!("Failed to poll VM sandbox process: {err}"), - ), - ); - return; - } - }; - - if let Some((component, status)) = exit_status { - let state_dir = { - let registry = self.registry.lock().await; - registry - .get(&sandbox_id) - .map(|record| record.state_dir.clone()) - }; - if let Some(ref state_dir) = state_dir { - let marker = state_dir.join(MAIN_PROCESS_EXITED_FILE); - if !tokio::fs::try_exists(&marker).await.unwrap_or(false) - && let Err(error) = - write_private_file(&marker, b"terminal\n".to_vec()).await - { - warn!( - sandbox_id = %sandbox_id, - %error, - "vm driver: failed to persist canonical-process exit tombstone" - ); - } - } - { - let mut process = process.lock().await; - if component == "VM" { - let _ = terminate_vm_process(&mut process.supervisor).await; - } else { - let _ = terminate_vm_process(&mut process.child).await; - } - } - let mut message = status.code().map_or_else( - || format!("{component} process exited"), - |code| format!("{component} process exited with status {code}"), - ); - if component == "host supervisor" - && let Some(state_dir) = state_dir.as_deref() - && let Some(stderr) = read_vm_console_tail( - &state_dir.join("supervisor.err.log"), - VM_CONSOLE_DIAGNOSTIC_BYTES, - ) - { - write!(message, "; supervisor stderr tail:\n{stderr}") - .expect("writing to String cannot fail"); - } - if let Some(snapshot) = self - .set_snapshot_condition( - &sandbox_id, - error_condition("ProcessExited", &message), - false, - ) - .await - { - self.publish_snapshot(snapshot); - } - self.publish_platform_event( - sandbox_id.clone(), - platform_event("vm", "Warning", "ProcessExited", message), - ); - let (has_gpu, cleanup_ctx) = { - let registry = self.registry.lock().await; - registry.get(&sandbox_id).map_or((false, None), |record| { - ( - record.gpu_bdf.is_some(), - Some((record.snapshot.clone(), record.state_dir.clone())), - ) - }) - }; - // Give lifecycle extensions a chance to release host - // resources they allocated in `before_launch` (e.g. device - // bindings, OVS flows). The driver releases its own - // allocations just below; without this, extension-owned - // resources would leak whenever a VM helper exits without an - // explicit delete. Cleanup is best-effort and idempotent, so - // a later delete that also fires `after_delete` is safe. - if let Some((sandbox, state_dir)) = cleanup_ctx { - self.lifecycle_extensions - .after_launch_failed(&sandbox, &state_dir, LaunchAbortReason::ProcessExited) - .await; - } - if has_gpu { - self.release_gpu(&sandbox_id); - } - return; - } - - tokio::time::sleep(Duration::from_millis(250)).await; - } - } - - async fn set_snapshot_condition( - &self, - sandbox_id: &str, - condition: SandboxCondition, - deleting: bool, - ) -> Option { - let mut registry = self.registry.lock().await; - let record = registry.get_mut(sandbox_id)?; - record.snapshot.status = Some(status_with_condition(&record.snapshot, condition, deleting)); - Some(record.snapshot.clone()) - } - - fn publish_snapshot(&self, sandbox: Sandbox) { - let _ = self.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Sandbox( - WatchSandboxesSandboxEvent { - sandbox: Some(sandbox), - }, - )), - }); - } - - fn publish_deleted(&self, sandbox_id: String) { - let _ = self.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Deleted( - WatchSandboxesDeletedEvent { sandbox_id }, - )), - }); - } - - fn publish_platform_event(&self, sandbox_id: String, event: PlatformEvent) { - let _ = self.events.send(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::PlatformEvent( - WatchSandboxesPlatformEvent { - sandbox_id, - event: Some(event), - }, - )), - }); - } - - fn publish_vm_progress( - &self, - sandbox_id: &str, - reason: &str, - message: String, - metadata: HashMap, - ) { - let mut event = platform_event("vm", "Normal", reason, message); - event.metadata = metadata; - attach_vm_progress_metadata(&mut event); - self.publish_platform_event(sandbox_id.to_string(), event); - } -} - -/// Execute an internal image preparation request in its own process group. -/// The driver supplies a private request file and an inherited staging lease; -/// this entry point never restores sandboxes or launches a gateway listener. -#[doc(hidden)] -pub async fn run_image_preparation_worker(request_path: &Path) -> Result<(), String> { - let (request, directory) = preparation::read_request(request_path)?; - validate_sandbox_id(&request.sandbox_id).map_err(|error| error.message().to_string())?; - preparation::watch_parent(request.parent_pid)?; - tracing_subscriber::fmt() - .with_writer(std::io::stderr) - .with_ansi(openshell_core::color::stderr_ansi()) - .with_env_filter(request.config.log_level.clone()) - .try_init() - .map_err(|error| format!("initialize image preparation logging: {error}"))?; - let (events, mut receiver) = broadcast::channel(WATCH_BUFFER); - let socket_root_fd = fs::File::open(&directory) - .map_err(|error| error.to_string())? - .into(); - let launcher_bin = request - .config - .launcher_bin - .clone() - .map_or_else(std::env::current_exe, Ok) - .map_err(|error| error.to_string())?; - let driver = VmDriver { - config: request.config, - socket_root: directory.clone(), - socket_root_fd: Arc::new(socket_root_fd), - launcher_bin, - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: Some(directory), - events, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - let prepare = async { - if let Some(overlay) = request.overlay { - driver - .prepare_requested_overlay(&request.sandbox_id, overlay) - .await - .map(preparation::Output::Overlay) - } else if request.bootstrap_only { - let identity = driver - .ensure_cached_bootstrap_rootfs_image(&request.sandbox_id, &request.image_ref) - .await?; - Ok(preparation::Output::Images(RuntimeImagePlan { - root_disk: image_cache_rootfs_image(&driver.config.state_dir, &identity), - image_disk: None, - image_identity: identity.clone(), - bootstrap_image_identity: identity, - })) - } else { - driver - .prepare_runtime_images( - &request.sandbox_id, - &request.image_ref, - request.rootfs_tar.as_deref(), - ) - .await - .map(preparation::Output::Images) - } - }; - tokio::pin!(prepare); - let result = loop { - tokio::select! { - result = &mut prepare => break result, - event = receiver.recv() => { - if let Ok(event) = event { - preparation::send(&preparation::Message::Event(event.encode_to_vec())).map_err(|error| error.to_string())?; - } - } - } - }; - while let Ok(event) = receiver.try_recv() { - preparation::send(&preparation::Message::Event(event.encode_to_vec())) - .map_err(|error| error.to_string())?; - } - preparation::send(&preparation::Message::Complete( - result.map_err(|error| error.message().to_string()), - )) - .map_err(|error| error.to_string()) -} - -fn read_vm_console_tail(path: &Path, limit: u64) -> Option { - if limit == 0 { - return None; - } - let mut file = fs::File::open(path).ok()?; - let length = file.metadata().ok()?.len(); - file.seek(SeekFrom::Start(length.saturating_sub(limit))) - .ok()?; - let mut bytes = Vec::with_capacity(usize::try_from(length.min(limit)).ok()?); - file.read_to_end(&mut bytes).ok()?; - let text = String::from_utf8_lossy(&bytes); - let text = text.trim_matches(['\0', '\n', '\r']); - (!text.is_empty()).then(|| text.to_string()) -} - -fn configure_main_exit_marker(command: &mut Command, state_dir: &Path) { - command - .arg("--main-exit-marker") - .arg(state_dir.join(MAIN_PROCESS_EXITED_FILE)); -} - -#[tonic::async_trait] -impl openshell_core::compute::ComputeDriver for VmDriver {} - -#[tonic::async_trait] -impl ComputeDriver for VmDriver { - async fn authenticate_sandbox( - &self, - _request: Request, - ) -> Result, Status> - { - Err(Status::unimplemented( - "VM driver does not authenticate sandbox credentials", - )) - } - - async fn get_capabilities( - &self, - request: Request, - ) -> Result, Status> { - let capabilities = self.capabilities(); - openshell_core::extension_protocol::validate_gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - DRIVER_NAME, - capabilities.extension.as_ref(), - request.into_inner().gateway, - ) - .map_err(|error| Status::failed_precondition(error.to_string()))?; - Ok(Response::new(capabilities)) - } - - async fn validate_sandbox_create( - &self, - request: Request, - ) -> Result, Status> { - let sandbox = request - .into_inner() - .sandbox - .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; - self.validate_sandbox(&sandbox)?; - Ok(Response::new(ValidateSandboxCreateResponse {})) - } - - async fn create_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let sandbox = request - .into_inner() - .sandbox - .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; - let response = self.create_sandbox(&sandbox).await?; - Ok(Response::new(response)) - } - - async fn get_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let request = request.into_inner(); - if request.sandbox_id.is_empty() && request.name.is_empty() { - return Err(Status::invalid_argument( - "sandbox_id or sandbox_name is required", - )); - } - - let sandbox = self - .get_sandbox(&request.sandbox_id, &request.name) - .await? - .ok_or_else(|| Status::not_found("sandbox not found"))?; - - if !request.sandbox_id.is_empty() && request.sandbox_id != sandbox.id { - return Err(Status::failed_precondition( - "sandbox_id did not match the fetched sandbox", - )); - } - - Ok(Response::new(GetSandboxResponse { - sandbox: Some(sandbox), - })) - } - - async fn list_sandboxes( - &self, - _request: Request, - ) -> Result, Status> { - Ok(Response::new(ListSandboxesResponse { - sandboxes: self.current_snapshots().await, - })) - } - - async fn suspend_sandbox( - &self, - _request: Request, - ) -> Result, Status> { - Err(Status::unimplemented( - "the VM compute driver does not support sandbox suspend", - )) - } - - async fn stop_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let request = request.into_inner(); - self.stop_sandbox(&request.sandbox_id, &request.name) - .await?; - Ok(Response::new(StopSandboxResponse {})) - } - - async fn start_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let request = request.into_inner(); - self.start_sandbox( - &request.sandbox_id, - &request.name, - &request.generation_id, - request.launch_authentication, - ) - .await?; - Ok(Response::new(StartSandboxResponse::default())) - } - - async fn delete_sandbox( - &self, - request: Request, - ) -> Result, Status> { - let request = request.into_inner(); - let response = self - .delete_sandbox(&request.sandbox_id, &request.name) - .await?; - Ok(Response::new(response)) - } - - type WatchSandboxesStream = - Pin> + Send + 'static>>; - - async fn watch_sandboxes( - &self, - _request: Request, - ) -> Result, Status> { - let initial = self.current_snapshots().await; - let mut rx = self.events.subscribe(); - let (tx, out_rx) = mpsc::channel(WATCH_BUFFER); - tokio::spawn(async move { - let mut sent = HashSet::new(); - for sandbox in initial { - sent.insert(sandbox.id.clone()); - if tx - .send(Ok(WatchSandboxesEvent { - payload: Some(watch_sandboxes_event::Payload::Sandbox( - WatchSandboxesSandboxEvent { - sandbox: Some(sandbox), - }, - )), - })) - .await - .is_err() - { - return; - } - } - - loop { - let event = tokio::select! { - () = tx.closed() => return, - event = rx.recv() => event, - }; - match event { - Ok(event) => { - if let Some(watch_sandboxes_event::Payload::Sandbox(sandbox_event)) = - &event.payload - && let Some(sandbox) = &sandbox_event.sandbox - && !sent.insert(sandbox.id.clone()) - { - // duplicate snapshots are still forwarded - } - if tx.send(Ok(event)).await.is_err() { - return; - } - } - Err(broadcast::error::RecvError::Lagged(_)) => {} - Err(broadcast::error::RecvError::Closed) => return, - } - } - }); - - let stream: Self::WatchSandboxesStream = Box::pin(ReceiverStream::new(out_rx)); - Ok(Response::new(stream)) - } - - async fn ensure_workspace( - &self, - _request: Request, - ) -> Result, Status> { - Ok(Response::new(EnsureWorkspaceResponse {})) - } - - async fn delete_workspace( - &self, - _request: Request, - ) -> Result, Status> { - Ok(Response::new(DeleteWorkspaceResponse {})) - } -} - -#[cfg(target_os = "linux")] -fn check_gpu_privileges() -> Result<(), String> { - if !rustix::process::geteuid().is_root() { - return Err( - "GPU support requires root privileges for VFIO bind/unbind. \ - Run with sudo or grant the host device-management capabilities required by VFIO." - .to_string(), - ); - } - Ok(()) -} - -// `tonic::Status` is ~176 bytes; it's the standard error type across the -// gRPC API surface, so boxing here would diverge from every other handler. -#[allow(clippy::result_large_err)] -fn decode_launch_authentication( - encoded: &[u8], -) -> Result { - if encoded.is_empty() { - return Err(Status::failed_precondition( - "VM sandbox launch authentication is required; configure the gateway's \ - [openshell.gateway.gateway_jwt] signing bundle. Listener TLS is separate", - )); - } - // Serde errors may quote an unexpected field or value from the secret - // bundle. Return fixed diagnostics rather than forwarding those details. - let authentication = - serde_json::from_slice::(encoded) - .map_err(|_| { - Status::failed_precondition("VM sandbox launch authentication is malformed") - })?; - authentication.validate().map_err(|_| { - Status::failed_precondition("VM sandbox launch authentication has invalid fields") - })?; - Ok(authentication) -} - -#[allow(clippy::result_large_err)] -fn validate_vm_sandbox(sandbox: &Sandbox, gpu_enabled: bool) -> Result<(), Status> { - validate_sandbox_id(&sandbox.id)?; - - let spec = sandbox - .spec - .as_ref() - .ok_or_else(|| Status::invalid_argument("sandbox spec is required"))?; - - if let Some(template) = spec.template.as_ref() { - validate_vm_sandbox_template(template)?; - } - validate_gpu_request(sandbox, gpu_enabled)?; - - Ok(()) -} - -#[allow(clippy::result_large_err)] -fn validate_vm_sandbox_template(template: &SandboxTemplate) -> Result<(), Status> { - if !template.agent_socket_path.is_empty() { - return Err(Status::failed_precondition( - "vm sandboxes do not support template.agent_socket_path", - )); - } - if template.platform_config.is_some() { - return Err(Status::failed_precondition( - "vm sandboxes do not support template.platform_config", - )); - } - Ok(()) -} - -/// Each share is one virtio device and libkrun has a fixed number of interrupt -/// lines; a share beyond them breaks VM start. The VM's own devices take up -/// to 8 (balloon, rng, console, root filesystem, three disks, vsock), plus an -/// RTC on `aarch64`. `x86_64` has 11 lines. `aarch64` has 128 on HVF but only -/// 64 usable on KVM (the vGIC is created with 96 SPIs and libkrun allocates -/// from GSI 32), so 32 leaves headroom on both. -const VM_MAX_BIND_MOUNTS: usize = if cfg!(target_arch = "aarch64") { 32 } else { 3 }; - -const VM_RESERVED_GUEST_PATHS: &[&str] = &[ - "/.openshell", - "/.openshell-bootstrap", - "/overlay", - "/lower", - "/newroot", - "/image-cache", - "/srv", - "/proc", - "/sys", - "/dev", - "/tmp", -]; - -const VIRTIOFS_TAG_PREFIX: &str = "osfs"; - -fn virtiofs_tag(index: usize) -> String { - format!("{VIRTIOFS_TAG_PREFIX}{index}") -} - -fn vm_mount_mode(read_only: bool) -> &'static str { - if read_only { "ro" } else { "rw" } -} - -/// Guest manifest consumed by `mount_virtiofs_shares`: `tag\ttarget\tmode`. -fn render_mount_manifest(mounts: &[VmMountConfig]) -> String { - let mut manifest = String::new(); - for (i, mount) in mounts.iter().enumerate() { - writeln!( - manifest, - "{}\t{}\t{}", - virtiofs_tag(i), - driver_mounts::normalize_mount_target(&mount.target), - vm_mount_mode(mount.read_only) - ) - .expect("write to String cannot fail"); - } - manifest -} - -fn sandbox_requests_gpu(sandbox: &Sandbox) -> bool { - sandbox - .spec - .as_ref() - .and_then(|spec| spec.resource_requirements.as_ref()) - .and_then(|requirements| driver_gpu_requirements(Some(requirements))) - .is_some() -} - -fn validate_no_control_chars(value: &str, field: &str) -> Result<(), String> { - if value.chars().any(char::is_control) { - return Err(format!("{field} must not contain control characters")); - } - Ok(()) -} - -#[allow(clippy::result_large_err)] -fn validate_vm_driver_mounts( - mounts: &[VmMountConfig], - config: &VmDriverConfig, - is_qemu: bool, -) -> Result<(), Status> { - if mounts.is_empty() { - return Ok(()); - } - if is_qemu { - return Err(Status::failed_precondition( - "vm bind mounts require the libkrun backend; GPU sandboxes and other QEMU launches cannot use them", - )); - } - if !config.enable_bind_mounts { - return Err(Status::failed_precondition( - "vm bind mounts require enable_bind_mounts = true in the VM driver configuration", - )); - } - config - .resource_admission - .reject_unlabelable("host bind mount")?; - if mounts.len() > VM_MAX_BIND_MOUNTS { - return Err(Status::invalid_argument(format!( - "vm sandboxes support at most {VM_MAX_BIND_MOUNTS} bind mounts, got {}", - mounts.len() - ))); - } - let mut targets: Vec = Vec::with_capacity(mounts.len()); - for mount in mounts { - driver_mounts::validate_absolute_mount_source(&mount.source, "vm mount source") - .map_err(Status::invalid_argument)?; - validate_no_control_chars(&mount.source, "vm mount source") - .map_err(Status::invalid_argument)?; - driver_mounts::validate_container_mount_target(&mount.target) - .map_err(Status::invalid_argument)?; - let normalized = driver_mounts::normalize_mount_target(&mount.target); - driver_mounts::validate_workspace_mount_target( - &normalized, - driver_mounts::DEFAULT_WORKSPACE_ROOT, - ) - .map_err(Status::invalid_argument)?; - for reserved in VM_RESERVED_GUEST_PATHS { - if driver_mounts::paths_overlap(Path::new(&normalized), Path::new(reserved)) { - return Err(Status::invalid_argument(format!( - "vm mount target '{}' conflicts with VM-internal path '{reserved}'", - mount.target - ))); - } - } - // Nested shares would make guest init create directories inside an - // already-mounted host share, so targets must be disjoint. - if let Some(existing) = targets.iter().find(|existing| { - driver_mounts::paths_overlap(Path::new(&normalized), Path::new(existing)) - }) { - return Err(Status::invalid_argument(if *existing == normalized { - format!("duplicate vm driver_config mount target '{normalized}'") - } else { - format!("vm mount target '{normalized}' overlaps mount target '{existing}'") - })); - } - targets.push(normalized); - } - Ok(()) -} - -/// Host filesystem checks, run at provisioning rather than in -/// `validate_sandbox` so a briefly missing source (for example an NFS share -/// not yet mounted after a reboot) fails provisioning visibly instead of -/// denying recovery of a persisted sandbox. -#[allow(clippy::result_large_err)] -async fn validate_vm_mount_sources(mounts: &[VmMountConfig]) -> Result<(), Status> { - for mount in mounts { - // libkrun opens the share root without following a final symlink. - let metadata = match tokio::fs::symlink_metadata(mount.host_source()).await { - Ok(metadata) => metadata, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - return Err(Status::failed_precondition(format!( - "vm mount source path does not exist: {}", - mount.source - ))); - } - Err(err) => { - return Err(Status::failed_precondition(format!( - "cannot access vm mount source {}: {err}", - mount.source - ))); - } - }; - if metadata.file_type().is_symlink() { - return Err(Status::invalid_argument(format!( - "vm mount source must be a real directory, not a symbolic link: {}", - mount.source - ))); - } - if !metadata.is_dir() { - return Err(Status::invalid_argument(format!( - "vm mount source must be a directory, not a file: {}", - mount.source - ))); - } - // On macOS libkrun opens the share root during guest boot and panics - // if it cannot, so an unreadable source must fail here instead. - if let Err(err) = tokio::fs::read_dir(mount.host_source()).await { - return Err(Status::failed_precondition(format!( - "cannot access vm mount source {}: {err}", - mount.source - ))); - } - } - Ok(()) -} - -#[allow(clippy::result_large_err)] -fn validate_gpu_request(sandbox: &Sandbox, gpu_enabled: bool) -> Result<(), Status> { - let spec = sandbox - .spec - .as_ref() - .ok_or_else(|| Status::invalid_argument("sandbox spec is required"))?; - - let gpu_requirements = driver_gpu_requirements(spec.resource_requirements.as_ref()); - let gpu_count = - effective_driver_gpu_count(gpu_requirements).map_err(Status::invalid_argument)?; - - if gpu_requirements.is_some() && !gpu_enabled { - return Err(Status::failed_precondition( - "GPU support is not enabled on this driver; start with --gpu", - )); - } - - let _ = vm_gpu_device_id(sandbox)?; - - if gpu_count.is_some_and(|count| count > 1) { - return Err(Status::invalid_argument( - "VM GPU sandboxes support only one GPU", - )); - } - - Ok(()) -} - -#[allow(clippy::result_large_err)] -fn vm_gpu_device_id(sandbox: &Sandbox) -> Result, Status> { - let Some(spec) = sandbox.spec.as_ref() else { - return Ok(None); - }; - let gpu_device_ids = VmSandboxDriverConfig::from_sandbox(sandbox) - .map_err(Status::invalid_argument)? - .gpu_device_ids - .unwrap_or_default(); - let gpu_requirements = driver_gpu_requirements(spec.resource_requirements.as_ref()); - validate_specific_gpu_device_request( - gpu_requirements, - &gpu_device_ids, - "driver_config.gpu_device_ids", - ) - .map_err(Status::invalid_argument)?; - if gpu_device_ids.len() > 1 { - return Err(Status::invalid_argument( - "vm driver currently supports at most one gpu_device_ids entry", - )); - } - - Ok(gpu_requirements - .is_some() - .then(|| gpu_device_ids.into_iter().next().unwrap_or_default())) -} - -#[allow(clippy::result_large_err)] -fn validate_sandbox_id(sandbox_id: &str) -> Result<(), Status> { - if sandbox_id.is_empty() { - return Err(Status::invalid_argument("sandbox id is required")); - } - if sandbox_id.len() > 128 { - return Err(Status::invalid_argument( - "sandbox id exceeds maximum length (128 bytes)", - )); - } - if matches!(sandbox_id, "." | "..") { - return Err(Status::invalid_argument( - "sandbox id must match [A-Za-z0-9._-]{1,128}", - )); - } - if !sandbox_id - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) - { - return Err(Status::invalid_argument( - "sandbox id must match [A-Za-z0-9._-]{1,128}", - )); - } - Ok(()) -} - -#[allow(clippy::result_large_err)] -fn parse_registry_reference(image_ref: &str) -> Result { - Reference::try_from(image_ref).map_err(|err| { - Status::failed_precondition(format!( - "invalid vm sandbox image reference '{image_ref}': {err}" - )) - }) -} - -/// Try to connect to a local container engine (Docker or Podman). -/// -/// Tries Docker first (`connect_with_local_defaults`, which respects -/// `DOCKER_HOST`). If Docker is unavailable, falls back to the Podman -/// socket, which exposes a Docker-compatible API. -async fn connect_local_container_engine() -> Option { - if let Ok(docker) = Docker::connect_with_local_defaults() - && docker.ping().await.is_ok() - { - return Some(docker); - } - - let podman_socket = detect_podman_socket()?; - if let Ok(docker) = - Docker::connect_with_unix(podman_socket.to_str()?, 120, bollard::API_DEFAULT_VERSION) - && docker.ping().await.is_ok() - { - info!( - socket = %podman_socket.display(), - "vm driver: connected to Podman (Docker-compatible API)" - ); - return Some(docker); - } - - None -} - -fn detect_podman_socket() -> Option { - openshell_container_runtime::podman_socket::detect_socket() -} - -fn is_openshell_local_build_image_ref(image_ref: &str) -> bool { - image_ref.starts_with("openshell/sandbox-from:") -} - -fn local_image_platform_mismatch( - image_ref: &str, - actual_os: Option<&str>, - actual_arch: Option<&str>, -) -> Option { - let actual_os = actual_os.unwrap_or("unknown"); - let actual_arch = actual_arch.unwrap_or("unknown"); - let expected_os = "linux"; - let expected_arch = linux_oci_arch(); - - (actual_os != expected_os || actual_arch != expected_arch).then(|| { - format!( - "local Docker image '{image_ref}' is {actual_os}/{actual_arch}, but VM sandboxes require {expected_os}/{expected_arch}" - ) - }) -} - -fn is_docker_not_found_error(err: &BollardError) -> bool { - matches!( - err, - BollardError::DockerResponseServerError { - status_code: 404, - .. - } - ) -} - -async fn export_local_image_rootfs_to_path( - docker: &Docker, - image_ref: &str, - tar_path: &Path, -) -> Result<(), Status> { - let container_name = format!( - "openshell-vm-rootfs-export-{}", - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_nanos() - ); - let create_options = CreateContainerOptionsBuilder::default() - .name(container_name.as_str()) - .build(); - let container = docker - .create_container( - Some(create_options), - ContainerCreateBody { - image: Some(image_ref.to_string()), - ..Default::default() - }, - ) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "failed to create temporary export container for local Docker image '{image_ref}': {err}" - )) - })?; - let container_id = container.id; - - let export_result = async { - if let Some(parent) = tar_path.parent() { - tokio::fs::create_dir_all(parent).await.map_err(|err| { - Status::internal(format!( - "create export dir {} failed: {err}", - parent.display() - )) - })?; - } - let mut file = tokio::fs::File::create(tar_path).await.map_err(|err| { - Status::internal(format!("create {} failed: {err}", tar_path.display())) - })?; - let mut stream = docker.export_container(&container_id); - while let Some(chunk) = stream.next().await { - let chunk = chunk.map_err(|err| { - Status::failed_precondition(format!( - "failed to export local Docker image '{image_ref}': {err}" - )) - })?; - file.write_all(&chunk).await.map_err(|err| { - Status::internal(format!("write {} failed: {err}", tar_path.display())) - })?; - } - file.flush() - .await - .map_err(|err| Status::internal(format!("flush {} failed: {err}", tar_path.display()))) - } - .await; - - let cleanup_result = docker - .remove_container( - &container_id, - Some(RemoveContainerOptionsBuilder::default().force(true).build()), - ) - .await; - - match (export_result, cleanup_result) { - (Ok(()), Ok(())) => Ok(()), - (Err(err), _) => Err(err), - (Ok(()), Err(err)) => Err(Status::internal(format!( - "failed to remove temporary export container for local Docker image '{image_ref}': {err}" - ))), - } -} - -fn registry_client() -> OciClient { - OciClient::new(ClientConfig { - platform_resolver: Some(Box::new(linux_platform_resolver)), - ..Default::default() - }) -} - -async fn pin_registry_reference( - client: &OciClient, - reference: &Reference, - auth: &RegistryAuth, -) -> Result<(Reference, String), OciDistributionError> { - // Preserve caller pins, including their digest algorithm. A HEAD response - // is only a resolution hint for tags, never proof of the image's contents. - let digest = match reference.digest() { - Some(digest) => digest.to_string(), - None => { - retry_registry_request("fetch manifest digest", || { - client.fetch_manifest_digest(reference, auth) - }) - .await? - } - }; - // oci-client verifies GET bytes against this pin. For an index it verifies - // the index first, then the selected platform manifest against its entry. - // All retries must use this same reference before publishing to the cache. - Ok((reference.clone_with_digest(digest.clone()), digest)) -} - -async fn retry_registry_request( - operation: &str, - request: F, -) -> Result -where - F: FnMut() -> Fut, - Fut: Future>, -{ - retry_registry_request_with_delay(operation, REGISTRY_RETRY_INITIAL_DELAY, request).await -} - -async fn retry_registry_request_with_delay( - operation: &str, - initial_delay: Duration, - mut request: F, -) -> Result -where - F: FnMut() -> Fut, - Fut: Future>, -{ - let mut delay = initial_delay; - for attempt in 1..=REGISTRY_REQUEST_MAX_ATTEMPTS { - match request().await { - Ok(value) => return Ok(value), - Err(err) - if attempt < REGISTRY_REQUEST_MAX_ATTEMPTS && registry_error_is_retryable(&err) => - { - warn!( - operation, - attempt, - max_attempts = REGISTRY_REQUEST_MAX_ATTEMPTS, - retry_delay_ms = delay.as_millis(), - error = %err, - "vm driver: transient registry request failed; retrying" - ); - tokio::time::sleep(delay).await; - delay = delay.saturating_mul(2).min(REGISTRY_RETRY_MAX_DELAY); - } - Err(err) => return Err(err), - } - } - - unreachable!("registry request retry loop always returns") -} - -fn registry_error_is_retryable(err: &OciDistributionError) -> bool { - match err { - OciDistributionError::AuthenticationFailure(message) => { - registry_message_is_retryable(message) - } - OciDistributionError::RegistryError { envelope, .. } => { - envelope.errors.iter().any(|error| { - error.code == OciErrorCode::Toomanyrequests - || registry_message_is_retryable(&error.message) - }) - } - OciDistributionError::RequestError(err) => { - err.is_connect() - || err.is_timeout() - || err - .status() - .is_some_and(|status| matches!(status.as_u16(), 408 | 425 | 429 | 500..=599)) - } - OciDistributionError::ServerError { code, message, .. } => { - matches!(code, 408 | 425 | 429 | 500..=599) || registry_message_is_retryable(message) - } - OciDistributionError::IoError(err) => matches!( - err.kind(), - std::io::ErrorKind::Interrupted - | std::io::ErrorKind::TimedOut - | std::io::ErrorKind::ConnectionAborted - | std::io::ErrorKind::ConnectionReset - | std::io::ErrorKind::ConnectionRefused - | std::io::ErrorKind::BrokenPipe - | std::io::ErrorKind::UnexpectedEof - | std::io::ErrorKind::WouldBlock - ), - _ => false, - } -} - -fn registry_message_is_retryable(message: &str) -> bool { - let message = message.to_ascii_lowercase(); - message.contains("retry-after") - || message.contains("too many requests") - || message.contains("rate limit") -} - -enum RegistryBlobPullError { - CreateFile(std::io::Error), - Registry(OciDistributionError), -} - -async fn pull_registry_blob_file( - operation: &str, - client: &OciClient, - reference: &Reference, - descriptor: &OciDescriptor, - blob_path: &Path, -) -> Result { - let mut delay = REGISTRY_RETRY_INITIAL_DELAY; - for attempt in 1..=REGISTRY_REQUEST_MAX_ATTEMPTS { - let mut file = tokio::fs::File::create(blob_path) - .await - .map_err(RegistryBlobPullError::CreateFile)?; - match client.pull_blob(reference, descriptor, &mut file).await { - Ok(()) => return Ok(file), - Err(err) - if attempt < REGISTRY_REQUEST_MAX_ATTEMPTS && registry_error_is_retryable(&err) => - { - warn!( - operation, - attempt, - max_attempts = REGISTRY_REQUEST_MAX_ATTEMPTS, - retry_delay_ms = delay.as_millis(), - error = %err, - "vm driver: transient registry request failed; retrying" - ); - tokio::time::sleep(delay).await; - delay = delay.saturating_mul(2).min(REGISTRY_RETRY_MAX_DELAY); - } - Err(err) => return Err(RegistryBlobPullError::Registry(err)), - } - } - - unreachable!("registry blob retry loop always returns") -} - -fn linux_platform_resolver(manifests: &[ImageIndexEntry]) -> Option { - let expected_arch = linux_oci_arch(); - manifests - .iter() - .find_map(|entry| { - let platform = entry.platform.as_ref()?; - (platform.os.to_string() == "linux" - && platform.architecture.to_string() == expected_arch) - .then(|| entry.digest.clone()) - }) - .or_else(|| { - manifests.iter().find_map(|entry| { - let platform = entry.platform.as_ref()?; - (platform.os.to_string() == "linux").then(|| entry.digest.clone()) - }) - }) -} - -fn linux_oci_arch() -> &'static str { - match std::env::consts::ARCH { - "x86_64" => "amd64", - "aarch64" => "arm64", - "arm" => "arm", - other => other, - } -} - -#[allow(clippy::result_large_err)] -fn registry_auth(image_ref: &str) -> Result { - let username = env_non_empty("OPENSHELL_REGISTRY_USERNAME"); - let token = env_non_empty("OPENSHELL_REGISTRY_TOKEN"); - - match token { - Some(token) => { - let username = match username { - Some(username) => username, - None if image_reference_registry_host(image_ref) - .eq_ignore_ascii_case("ghcr.io") => - { - "__token__".to_string() - } - None => { - return Err(Status::failed_precondition( - "OPENSHELL_REGISTRY_USERNAME is required when OPENSHELL_REGISTRY_TOKEN is set for non-GHCR registries", - )); - } - }; - Ok(RegistryAuth::Basic(username, token)) - } - None => Ok(RegistryAuth::Anonymous), - } -} - -fn env_non_empty(key: &str) -> Option { - std::env::var(key) - .ok() - .filter(|value| !value.trim().is_empty()) -} - -fn image_reference_registry_host(image_ref: &str) -> &str { - let mut parts = image_ref.splitn(2, '/'); - let first = parts.next().unwrap_or(image_ref); - let has_path = parts.next().is_some(); - if has_path - && (first.contains('.') || first.contains(':') || first.eq_ignore_ascii_case("localhost")) - { - first - } else { - "docker.io" - } -} - -impl VmDriver { - #[allow(clippy::too_many_arguments)] - async fn pull_registry_image_rootfs( - &self, - sandbox_id: &str, - client: &OciClient, - reference: &Reference, - auth: &RegistryAuth, - image_ref: &str, - staging_dir: &Path, - rootfs: &Path, - ) -> Result<(), Status> { - retry_registry_request("authenticate with registry", || { - client.auth(reference, auth, RegistryOperation::Pull) - }) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "failed to authenticate registry access for vm sandbox image '{image_ref}': {err}" - )) - })?; - let (manifest, _) = retry_registry_request("pull image manifest", || { - client.pull_image_manifest(reference, auth) - }) - .await - .map_err(|err| { - Status::failed_precondition(format!( - "failed to pull vm sandbox image manifest '{image_ref}': {err}" - )) - })?; - - tokio::fs::create_dir_all(rootfs) - .await - .map_err(|err| Status::internal(format!("create rootfs dir failed: {err}")))?; - tokio::fs::create_dir_all(staging_dir.join("layers")) - .await - .map_err(|err| Status::internal(format!("create layer staging dir failed: {err}")))?; - - let total_layers = manifest.layers.len(); - let total_bytes = manifest - .layers - .iter() - .map(|layer| layer.size.max(0)) - .fold(0, i64::saturating_add); - let mut layers = futures::stream::iter(manifest.layers.into_iter().enumerate()) - .map(|(index, layer)| async move { - self.publish_registry_layer_progress( - sandbox_id, - image_ref, - &layer, - index, - total_layers, - total_bytes, - ); - download_registry_layer_blob( - client, - reference, - image_ref, - staging_dir, - layer, - index, - ) - .await - }) - .buffer_unordered(registry_layer_download_concurrency()) - .try_collect::>() - .await?; - layers.sort_by_key(|layer| layer.index); - - // The blobs are verified. One writer owns the budget and each staged - // tree stays immutable while its files are copied into the rootfs. - let limit = self.config.bootstrap_extraction_max_bytes.map_or( - DEFAULT_BOOTSTRAP_EXTRACTION_MAX_BYTES, - std::num::NonZeroU64::get, - ); - let layer_root = staging_dir.join("layers/root"); - let rootfs = rootfs.to_owned(); - tokio::task::spawn_blocking(move || { - let mut budget = BootstrapExtractionBudget::new(limit); - for layer in layers { - extract_layer_blob_to_dir( - &layer.blob_path, - &layer.media_type, - &layer_root, - &mut budget, - ) - .and_then(|()| budget.apply_layer(&layer_root, &rootfs)) - .map_err(|err| format!("layer '{}': {err}", layer.digest))?; - } - Ok::<(), String>(()) - }) - .await - .map_err(|err| Status::internal(format!("bootstrap layer extraction panicked: {err}")))? - .map_err(|err| { - Status::failed_precondition(format!( - "failed to extract vm bootstrap image '{image_ref}': {err}" - )) - })?; - - remove_registry_layer_staging(staging_dir).await?; - - Ok(()) - } - - fn publish_registry_layer_progress( - &self, - sandbox_id: &str, - image_ref: &str, - layer: &OciDescriptor, - index: usize, - total_layers: usize, - total_bytes: i64, - ) { - let mut metadata = HashMap::new(); - metadata.insert("layer_index".to_string(), (index + 1).to_string()); - metadata.insert("layer_total".to_string(), total_layers.to_string()); - metadata.insert("layer_digest".to_string(), layer.digest.clone()); - metadata.insert("layer_size_bytes".to_string(), layer.size.to_string()); - metadata.insert("image_ref".to_string(), image_ref.to_string()); - if total_bytes > 0 { - metadata.insert("image_size_bytes".to_string(), total_bytes.to_string()); - } - let mut event = platform_event( - "vm", - "Normal", - "PullingLayer", - format!( - "Pulling layer {}/{} ({} bytes) for image \"{image_ref}\"", - index + 1, - total_layers, - layer.size - ), - ); - event.metadata = metadata; - attach_vm_progress_metadata(&mut event); - self.publish_platform_event(sandbox_id.to_string(), event); - } - - /// Emit a `Pulled` platform event with progress metadata for the CLI. - async fn publish_pulled_event(&self, sandbox_id: &str, image_ref: &str, image_path: &Path) { - let mut metadata = HashMap::from([("image_ref".to_string(), image_ref.to_string())]); - let size_suffix = tokio::fs::metadata(image_path).await.map_or_else( - |_| String::new(), - |meta| { - metadata.insert("image_size_bytes".to_string(), meta.len().to_string()); - format!(" Image size: {} bytes.", meta.len()) - }, - ); - self.publish_vm_progress( - sandbox_id, - "Pulled", - format!("Successfully pulled image \"{image_ref}\".{size_suffix}"), - metadata, - ); - } -} - -struct DownloadedRegistryLayer { - index: usize, - digest: String, - blob_path: PathBuf, - media_type: String, -} - -async fn download_registry_layer_blob( - client: &OciClient, - reference: &Reference, - image_ref: &str, - staging_dir: &Path, - layer: OciDescriptor, - index: usize, -) -> Result { - let digest_component = sanitize_image_identity(&layer.digest); - let blob_path = staging_dir - .join("layers") - .join(format!("{index:02}-{digest_component}.blob")); - - let mut file = pull_registry_blob_file( - "download image layer", - client, - reference, - &layer, - &blob_path, - ) - .await - .map_err(|err| match err { - RegistryBlobPullError::CreateFile(err) => { - Status::internal(format!("create layer blob failed: {err}")) - } - RegistryBlobPullError::Registry(err) => Status::failed_precondition(format!( - "failed to download layer '{}' for vm sandbox image '{image_ref}': {err}", - layer.digest - )), - })?; - file.flush() - .await - .map_err(|err| Status::internal(format!("flush layer blob failed: {err}")))?; - - let blob_path_for_digest = blob_path.clone(); - let expected_digest = layer.digest.clone(); - tokio::task::spawn_blocking(move || { - verify_descriptor_digest(&blob_path_for_digest, &expected_digest) - }) - .await - .map_err(|err| Status::internal(format!("layer digest verification panicked: {err}")))? - .map_err(|err| { - Status::failed_precondition(format!( - "vm sandbox image layer verification failed for '{}': {err}", - layer.digest - )) - })?; - - Ok(DownloadedRegistryLayer { - index, - digest: layer.digest, - blob_path, - media_type: layer.media_type, - }) -} - -async fn remove_registry_layer_staging(staging_dir: &Path) -> Result<(), Status> { - let layers_dir = staging_dir.join("layers"); - remove_bootstrap_staging(&layers_dir).await.map_err(|err| { - Status::internal(format!( - "remove registry layer staging dir '{}' failed: {err}", - layers_dir.display() - )) - }) -} - -async fn remove_bootstrap_staging(dir: &Path) -> std::io::Result<()> { - let dir = dir.to_owned(); - tokio::task::spawn_blocking(move || preparation::remove_staging_tree(&dir)).await? -} - -async fn download_registry_descriptor_blob_file( - client: &OciClient, - reference: &Reference, - image_ref: &str, - layout_dir: &Path, - descriptor: &OciDescriptor, - kind: &str, -) -> Result<(), Status> { - let blob_path = oci_layout_blob_path(layout_dir, &descriptor.digest) - .map_err(|err| Status::failed_precondition(format!("invalid {kind} digest: {err}")))?; - if let Some(parent) = blob_path.parent() { - tokio::fs::create_dir_all(parent) - .await - .map_err(|err| Status::internal(format!("create OCI blob dir failed: {err}")))?; - } - - let mut file = pull_registry_blob_file( - "download image blob", - client, - reference, - descriptor, - &blob_path, - ) - .await - .map_err(|err| match err { - RegistryBlobPullError::CreateFile(err) => { - Status::internal(format!("create OCI {kind} blob failed: {err}")) - } - RegistryBlobPullError::Registry(err) => Status::failed_precondition(format!( - "failed to download {kind} '{}' for vm sandbox image '{image_ref}': {err}", - descriptor.digest - )), - })?; - file.flush() - .await - .map_err(|err| Status::internal(format!("flush OCI {kind} blob failed: {err}")))?; - - let blob_path_for_digest = blob_path.clone(); - let expected_digest = descriptor.digest.clone(); - tokio::task::spawn_blocking(move || { - verify_descriptor_digest(&blob_path_for_digest, &expected_digest) - }) - .await - .map_err(|err| Status::internal(format!("OCI {kind} digest verification panicked: {err}")))? - .map_err(|err| { - Status::failed_precondition(format!( - "vm sandbox image {kind} verification failed for '{}': {err}", - descriptor.digest - )) - }) -} - -fn verify_descriptor_digest(path: &Path, expected_digest: &str) -> Result<(), String> { - let expected = expected_digest - .strip_prefix("sha256:") - .ok_or_else(|| format!("unsupported layer digest '{expected_digest}'"))?; - let actual = compute_file_sha256_hex(path)?; - if actual == expected { - Ok(()) - } else { - Err(format!( - "digest mismatch for {}: expected sha256:{expected}, got sha256:{actual}", - path.display() - )) - } -} - -fn compute_file_sha256_hex(path: &Path) -> Result { - let mut file = fs::File::open(path).map_err(|err| format!("open {}: {err}", path.display()))?; - let mut hasher = Sha256::new(); - let mut buffer = vec![0_u8; 64 * 1024].into_boxed_slice(); - loop { - let read = file - .read(&mut buffer) - .map_err(|err| format!("read {}: {err}", path.display()))?; - if read == 0 { - break; - } - hasher.update(&buffer[..read]); - } - Ok(format!("{:x}", hasher.finalize())) -} - -fn compute_bytes_sha256_hex(bytes: &[u8]) -> String { - let mut hasher = Sha256::new(); - hasher.update(bytes); - format!("{:x}", hasher.finalize()) -} - -/// Stage the caller-supplied rootfs archive at `src` into the image cache at -/// `dst`, and return the SHA-256 of the source bytes that were read. -/// -/// The staged file is always an uncompressed tar. `--from` accepts `.tar.gz` -/// and `.tgz`, but the guest image-prep VM extracts the staged file with a -/// plain `tar -xpf`, and the prepared disk is sized from that file's length, -/// so leaving gzip bytes on disk would both depend on the guest tar -/// auto-detecting compression and size the disk from the compressed length. -/// Compression is detected from the magic bytes: the driver only ever sees a -/// gateway-issued staging path, never the caller's file name. -/// -/// Expansion is bounded by `max_bytes` — the same limit the driver applies to -/// the archive it accepts — so a compression bomb cannot fill the host disk. -/// -/// The digest covers the source bytes rather than the bytes written, which is -/// what lets the caller detect an archive that changed underneath it during -/// staging: it stays comparable with the pre-copy hash pass whether or not the -/// source was compressed. -fn stage_rootfs_tar_archive(src: &Path, dst: &Path, max_bytes: u64) -> Result { - let file = fs::File::open(src).map_err(|err| format!("open {}: {err}", src.display()))?; - let mut reader = BufReader::new(file); - let compressed = reader - .fill_buf() - .map_err(|err| format!("read {}: {err}", src.display()))? - .starts_with(&crate::rootfs::GZIP_MAGIC); - - let mut source = HashingReader::new(reader); - if compressed { - write_stream_to_file(MultiGzDecoder::new(&mut source), dst, max_bytes)?; - } else { - write_stream_to_file(&mut source, dst, max_bytes)?; - } - - // A decoder stops at the end of the compressed stream, so drain whatever - // it left behind: the digest has to describe the whole source file for the - // caller's change-detection comparison to mean anything. - std::io::copy(&mut source, &mut std::io::sink()) - .map_err(|err| format!("read {}: {err}", src.display()))?; - Ok(source.finish()) -} - -/// Reader adapter that digests every byte it yields. -struct HashingReader { - inner: R, - hasher: Sha256, -} - -impl HashingReader { - fn new(inner: R) -> Self { - Self { - inner, - hasher: Sha256::new(), - } - } - - fn finish(self) -> String { - format!("{:x}", self.hasher.finalize()) - } -} - -impl Read for HashingReader { - fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - let read = self.inner.read(buf)?; - self.hasher.update(&buf[..read]); - Ok(read) - } -} - -fn write_stream_to_file(mut reader: impl Read, dst: &Path, max_bytes: u64) -> Result<(), String> { - let mut writer = BufWriter::new( - fs::File::create(dst).map_err(|err| format!("create {}: {err}", dst.display()))?, - ); - let mut buffer = vec![0_u8; 64 * 1024].into_boxed_slice(); - let mut written = 0_u64; - loop { - let read = reader - .read(&mut buffer) - .map_err(|err| format!("read rootfs tar: {err}"))?; - if read == 0 { - break; - } - written = written.saturating_add(u64::try_from(read).unwrap_or(u64::MAX)); - if written > max_bytes { - return Err(format!( - "rootfs tar expands to more than the {max_bytes} byte limit" - )); - } - writer - .write_all(&buffer[..read]) - .map_err(|err| format!("write {}: {err}", dst.display()))?; - } - writer - .flush() - .map_err(|err| format!("flush {}: {err}", dst.display())) -} - -/// Cache identity for a rootfs tar archive, derived from its contents. -/// -/// Deliberately not path- or mtime-derived: staging directories are unique per -/// request, so a path-based key would never hit the cache, and a -/// seconds-truncated mtime cannot distinguish two writes within the same -/// second. A fixed-length digest also keeps the cache directory name inside -/// filesystem component limits regardless of how long the source path was. -fn rootfs_tar_cache_identity(digest: &str, config: &VmDriverConfig) -> String { - prepared_image_cache_identity(&format!("rootfs-tar:sha256:{digest}"), config) -} - -fn extract_layer_blob_to_dir( - blob_path: &Path, - media_type: &str, - dest: &Path, - budget: &mut BootstrapExtractionBudget, -) -> Result<(), String> { - if dest.exists() { - preparation::remove_staging_tree(dest) - .map_err(|err| format!("remove {}: {err}", dest.display()))?; - } - let file = - fs::File::open(blob_path).map_err(|err| format!("open {}: {err}", blob_path.display()))?; - match layer_compression_from_media_type(media_type)? { - LayerCompression::None => budget.unpack_tar(file, dest), - LayerCompression::Gzip => budget.unpack_tar(MultiGzDecoder::new(file), dest), - LayerCompression::Zstd => { - let decoder = zstd::stream::read::Decoder::new(file) - .map_err(|err| format!("decompress {}: {err}", blob_path.display()))?; - budget.unpack_tar(decoder, dest) - } - } - .map_err(|err| format!("extract layer into {}: {err}", dest.display())) -} - -// `media_type` is an OCI media type string (e.g. `application/vnd.oci.image.layer.v1.tar+gzip`), -// not a filesystem path, so case-sensitive comparison is correct. -#[allow(clippy::case_sensitive_file_extension_comparisons)] -fn layer_compression_from_media_type(media_type: &str) -> Result { - if media_type.is_empty() { - return Err("layer media type is missing".to_string()); - } - if media_type.ends_with("+zstd") { - return Ok(LayerCompression::Zstd); - } - if media_type.ends_with("+gzip") || media_type.ends_with(".gzip") { - return Ok(LayerCompression::Gzip); - } - if media_type.ends_with(".tar") - || media_type.ends_with("tar") - || media_type == "application/vnd.oci.image.layer.v1.tar" - || media_type == "application/vnd.oci.image.layer.nondistributable.v1.tar" - { - return Ok(LayerCompression::None); - } - Err(format!("unsupported layer media type '{media_type}'")) -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum LayerCompression { - None, - Gzip, - Zstd, -} - -fn requested_sandbox_image(sandbox: &Sandbox) -> Option<&str> { - sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - .map(|template| template.image.trim()) - .filter(|image| !image.is_empty()) -} - -fn merged_environment(sandbox: &Sandbox) -> HashMap { - let mut environment = sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - .map_or_else(HashMap::new, |template| template.environment.clone()); - if let Some(spec) = sandbox.spec.as_ref() { - environment.extend(spec.environment.clone()); - } - environment -} - -fn random_boundary_token() -> Result { - let mut token = String::with_capacity(64); - for byte in openshell_crypto::random_bytes::<32>() - .map_err(|error| Status::internal(error.to_string()))? - { - write!(&mut token, "{byte:02x}").expect("writing to String cannot fail"); - } - Ok(token) -} - -fn build_guest_environment(sandbox: &Sandbox, config: &VmDriverConfig) -> Vec { - // The guest receives only driver-owned boot metadata. Gateway credentials, - // TLS material, and logical-supervisor configuration remain on the host; - // workload environment is carried in the authenticated BoundaryConfig. - let mut environment: HashMap = HashMap::new(); - environment.insert("HOME".to_string(), "/root".to_string()); - environment.insert( - "PATH".to_string(), - "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".to_string(), - ); - environment.insert("TERM".to_string(), "xterm".to_string()); - environment.insert( - openshell_core::sandbox_env::SANDBOX_ID.to_string(), - sandbox.id.clone(), - ); - environment.insert( - openshell_core::sandbox_env::SANDBOX.to_string(), - sandbox.name.clone(), - ); - environment.insert( - openshell_core::sandbox_env::LOG_LEVEL.to_string(), - openshell_core::driver_utils::sandbox_log_level(sandbox, &config.log_level), - ); - environment.insert( - openshell_core::sandbox_env::TELEMETRY_ENABLED.to_string(), - openshell_core::telemetry::enabled_env_value().to_string(), - ); - let mut pairs = environment.into_iter().collect::>(); - pairs.sort_by(|left, right| left.0.cmp(&right.0)); - pairs - .into_iter() - .map(|(key, value)| format!("{key}={value}")) - .collect() -} - -fn sandboxes_root_dir(root: &Path) -> PathBuf { - root.join("sandboxes") -} - -async fn create_private_dir_all(path: &Path) -> Result<(), std::io::Error> { - tokio::fs::create_dir_all(path).await?; - restrict_owner_only_dir(path).await -} - -#[cfg(unix)] -async fn restrict_owner_only_dir(path: &Path) -> Result<(), std::io::Error> { - tokio::fs::set_permissions(path, fs::Permissions::from_mode(0o700)).await -} - -#[cfg(not(unix))] -async fn restrict_owner_only_dir(_path: &Path) -> Result<(), std::io::Error> { - Ok(()) -} - -const SOCKET_ROOT_ALLOC_RETRIES: usize = 16; -/// macOS `sun_path` is 104 bytes including the NUL terminator. -const MAX_SUN_PATH_LEN: usize = 103; - -fn sandbox_socket_dir(socket_root: &Path, sandbox_id: &str) -> PathBuf { - socket_root.join(sandbox_id) -} - -fn allocate_socket_root() -> Result<(PathBuf, OwnedFd), std::io::Error> { - let uid = rustix::process::geteuid().as_raw(); - allocate_socket_root_with(Path::new("/tmp"), || { - let random = u128::from_ne_bytes( - openshell_crypto::random_bytes::<16>().map_err(std::io::Error::other)?, - ); - Ok(format!("os-{uid}-{random:032x}")) - }) -} - -fn allocate_socket_root_with( - base: &Path, - mut gen_name: impl FnMut() -> Result, -) -> Result<(PathBuf, OwnedFd), std::io::Error> { - for _ in 0..SOCKET_ROOT_ALLOC_RETRIES { - let root = base.join(gen_name()?); - match rustix::fs::mkdir(&root, rustix::fs::Mode::from_raw_mode(0o700)) { - Ok(()) => { - let fd = rustix::fs::open( - &root, - rustix::fs::OFlags::RDONLY - | rustix::fs::OFlags::DIRECTORY - | rustix::fs::OFlags::NOFOLLOW, - rustix::fs::Mode::empty(), - ) - .map_err(std::io::Error::from)?; - return Ok((root, fd)); - } - Err(rustix::io::Errno::EXIST) => {} - Err(e) => return Err(e.into()), - } - } - Err(std::io::Error::new( - std::io::ErrorKind::AlreadyExists, - format!( - "failed to allocate socket root under {} after {SOCKET_ROOT_ALLOC_RETRIES} attempts", - base.display() - ), - )) -} - -fn create_sandbox_socket_dir( - root_fd: &OwnedFd, - socket_root: &Path, - sandbox_id: &str, -) -> Result { - let longest = socket_root.join(sandbox_id).join(VM_CONTROL_SOCKET); - if longest.as_os_str().len() > MAX_SUN_PATH_LEN { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!( - "socket path {} exceeds sun_path limit ({MAX_SUN_PATH_LEN} bytes)", - longest.display() - ), - )); - } - match rustix::fs::mkdirat(root_fd, sandbox_id, rustix::fs::Mode::from_raw_mode(0o700)) { - Ok(()) | Err(rustix::io::Errno::EXIST) => {} - Err(e) => return Err(e.into()), - } - Ok(socket_root.join(sandbox_id)) -} - -fn remove_sandbox_socket_dir(root_fd: &OwnedFd, sandbox_id: &str) { - if let Ok(leaf_fd) = rustix::fs::openat( - root_fd, - sandbox_id, - rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY | rustix::fs::OFlags::NOFOLLOW, - rustix::fs::Mode::empty(), - ) { - let _ = rustix::fs::unlinkat(&leaf_fd, VM_CONTROL_SOCKET, rustix::fs::AtFlags::empty()); - let _ = rustix::fs::unlinkat(&leaf_fd, "ssh.sock", rustix::fs::AtFlags::empty()); - } - let _ = rustix::fs::unlinkat(root_fd, sandbox_id, rustix::fs::AtFlags::REMOVEDIR); -} - -#[allow(clippy::result_large_err)] -fn sandbox_state_dir(root: &Path, sandbox_id: &str) -> Result { - validate_sandbox_id(sandbox_id)?; - Ok(sandboxes_root_dir(root).join(sandbox_id)) -} - -fn sandbox_overlay_image(state_dir: &Path) -> PathBuf { - state_dir.join(SANDBOX_OVERLAY_IMAGE) -} - -fn overlay_template_image(root: &Path, size_bytes: u64) -> PathBuf { - image_cache_root_dir(root) - .join(OVERLAY_TEMPLATE_CACHE_DIR) - .join(OVERLAY_TEMPLATE_CACHE_LAYOUT_VERSION) - .join(format!("{size_bytes}.ext4")) -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct SandboxRuntimeDiskPaths { - overlay_disk: PathBuf, -} - -fn sandbox_runtime_disk_paths(state_dir: &Path) -> SandboxRuntimeDiskPaths { - SandboxRuntimeDiskPaths { - overlay_disk: sandbox_overlay_image(state_dir), - } -} - -/// Select the exact identity the guest must use for this overlay and whether a -/// successful preparation must create or upgrade its state marker. -/// -/// Persisted overlays are resolved only from concrete state. In particular, -/// absence of a marker is not evidence that an overlay used the historical -/// 10001 identity: it can also mean fresh provisioning was interrupted. -async fn sandbox_owner_state_for_launch( - state_dir: &Path, - overlay_disk: &Path, - owner_source_disk: &Path, - config: &VmDriverConfig, - preparation: OverlayPreparation, -) -> Result<(SandboxOwnerIdentity, bool), String> { - let marker_path = state_dir.join(SANDBOX_OWNER_STATE_FILE); - match tokio::fs::read_to_string(&marker_path).await { - Ok(contents) if contents.trim() == SANDBOX_OWNER_STATE_V1 => { - // The v1 marker recorded no identity. Resolve it through the same - // evidence-based migration path as an unmarked overlay. - } - Ok(contents) => { - let identity = parse_sandbox_owner_state(&contents).map_err(|error| { - format!( - "invalid sandbox owner state {}: {error}", - marker_path.display() - ) - })?; - return Ok((identity, false)); - } - Err(error) if error.kind() != std::io::ErrorKind::NotFound => { - return Err(format!( - "read sandbox owner state {}: {error}", - marker_path.display() - )); - } - Err(_) => {} - } - - let overlay_exists = match tokio::fs::metadata(overlay_disk).await { - Ok(metadata) => metadata.is_file(), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, - Err(error) => { - return Err(format!( - "stat overlay disk {}: {error}", - overlay_disk.display() - )); - } - }; - - if preparation == OverlayPreparation::PreserveExisting && overlay_exists { - match sandbox_owner_identity_from_overlay(overlay_disk).await { - Ok(Some(identity)) => return Ok((identity, true)), - Ok(None) => {} - Err(error) => warn!( - overlay_path = %overlay_disk.display(), - error = %error, - "could not read sandbox identity from VM overlay upper layer" - ), - } - if let Some(identity) = persisted_sandbox_owner_identity(state_dir, config).await? { - return Ok((identity, true)); - } - if let Some((uid, gid)) = configured_sandbox_identity(config) { - return Ok((SandboxOwnerIdentity { uid, gid }, true)); - } - return sandbox_owner_identity_from_image(owner_source_disk) - .await - .map(|identity| (identity, true)); - } - - if let Some((uid, gid)) = configured_sandbox_identity(config) { - return Ok((SandboxOwnerIdentity { uid, gid }, true)); - } - sandbox_owner_identity_from_image(owner_source_disk) - .await - .map(|identity| (identity, true)) -} - -async fn persisted_sandbox_owner_identity( - state_dir: &Path, - config: &VmDriverConfig, -) -> Result, String> { - let prior_identity = match tokio::fs::read_to_string(state_dir.join(IMAGE_IDENTITY_FILE)).await - { - Ok(identity) if !identity.trim().is_empty() => identity, - Ok(_) => String::new(), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(), - Err(error) => return Err(format!("read persisted VM image identity: {error}")), - }; - - if !prior_identity.is_empty() { - let prior_disk = image_cache_rootfs_image(&config.state_dir, prior_identity.trim()); - if tokio::fs::metadata(&prior_disk).await.is_ok() { - match sandbox_owner_identity_from_image(&prior_disk).await { - Ok(identity) => return Ok(Some(identity)), - Err(error) => warn!( - image_path = %prior_disk.display(), - error = %error, - "could not read sandbox identity from persisted VM rootfs; using compatibility fallback" - ), - } - } - } - - Ok(None) -} - -/// Reconstruct status from the owner chosen during preparation, never from a -/// new driver default or a status embedded in the persisted create request. -/// Missing or v1 markers do not contain an identity to report. Invalid owner -/// data must not be published as a resolved identity. -async fn read_persisted_workload_identity( - state_dir: &Path, -) -> Result, String> { - let contents = match tokio::fs::read_to_string(state_dir.join(SANDBOX_OWNER_STATE_FILE)).await { - Ok(contents) if contents.trim() == SANDBOX_OWNER_STATE_V1 => return Ok(None), - Ok(contents) => contents, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) => return Err(format!("read sandbox owner state: {error}")), - }; - let owner = parse_sandbox_owner_state(&contents) - .map_err(|error| format!("invalid sandbox owner state: {error}"))?; - let resource_digest = match read_persisted_image_identity(state_dir).await { - Ok(identity) => identity, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(), - Err(error) => return Err(format!("read persisted VM image identity: {error}")), - }; - Ok(Some(ResolvedWorkloadIdentity { - uid: owner.uid, - gid: owner.gid, - supplementary_gids: Vec::new(), - source: "vm-config".into(), - resource_digest, - })) -} - -async fn sandbox_owner_identity_from_image( - image_path: &Path, -) -> Result { - let image_path = image_path.to_path_buf(); - let identity = - tokio::task::spawn_blocking(move || sandbox_guest_user_ids_from_image(&image_path)) - .await - .map_err(|error| format!("read sandbox identity task failed: {error}"))??; - let (uid, gid) = identity.unwrap_or((DEFAULT_SANDBOX_UID, DEFAULT_SANDBOX_UID)); - validate_sandbox_owner_identity(uid, gid)?; - Ok(SandboxOwnerIdentity { uid, gid }) -} - -async fn sandbox_owner_identity_from_overlay( - overlay_path: &Path, -) -> Result, String> { - let overlay_path = overlay_path.to_path_buf(); - let identity = tokio::task::spawn_blocking(move || { - sandbox_guest_user_ids_from_overlay_image(&overlay_path) - }) - .await - .map_err(|error| format!("read sandbox overlay identity task failed: {error}"))??; - identity - .map(|(uid, gid)| { - validate_sandbox_owner_identity(uid, gid)?; - Ok(SandboxOwnerIdentity { uid, gid }) - }) - .transpose() -} - -fn parse_sandbox_owner_state(contents: &str) -> Result { - let mut fields = contents.trim().split(':'); - if fields.next() != Some(SANDBOX_OWNER_STATE_V2) { - return Err("unsupported version".to_string()); - } - let uid = fields - .next() - .ok_or_else(|| "missing uid".to_string())? - .parse::() - .map_err(|error| format!("invalid uid: {error}"))?; - let gid = fields - .next() - .ok_or_else(|| "missing gid".to_string())? - .parse::() - .map_err(|error| format!("invalid gid: {error}"))?; - if fields.next().is_some() { - return Err("unexpected fields".to_string()); - } - validate_sandbox_owner_identity(uid, gid)?; - Ok(SandboxOwnerIdentity { uid, gid }) -} - -async fn write_sandbox_owner_state( - state_dir: &Path, - identity: SandboxOwnerIdentity, -) -> Result<(), String> { - validate_sandbox_owner_identity(identity.uid, identity.gid)?; - let marker_path = state_dir.join(SANDBOX_OWNER_STATE_FILE); - let sequence = OWNER_STATE_WRITE_COUNTER.fetch_add(1, Ordering::Relaxed); - let temporary_path = state_dir.join(format!( - ".{SANDBOX_OWNER_STATE_FILE}.{}.{sequence}.tmp", - std::process::id() - )); - write_private_file(&temporary_path, identity.marker_contents().into_bytes()) - .await - .map_err(|err| format!("write temporary sandbox owner state: {err}"))?; - if let Err(error) = tokio::fs::rename(&temporary_path, &marker_path).await { - let _ = tokio::fs::remove_file(&temporary_path).await; - return Err(format!("install sandbox owner state: {error}")); - } - Ok(()) -} - -fn validate_sandbox_owner_identity(uid: u32, gid: u32) -> Result<(), String> { - let range = openshell_policy::MIN_SANDBOX_UID..=openshell_policy::MAX_SANDBOX_UID; - if !range.contains(&uid) { - return Err(format!( - "uid {uid} is outside the allowed range [{}, {}]", - openshell_policy::MIN_SANDBOX_UID, - openshell_policy::MAX_SANDBOX_UID - )); - } - if !range.contains(&gid) { - return Err(format!( - "gid {gid} is outside the allowed range [{}, {}]", - openshell_policy::MIN_SANDBOX_UID, - openshell_policy::MAX_SANDBOX_UID - )); - } - Ok(()) -} - -#[allow(clippy::result_large_err)] -fn validate_sandbox_state_dir(root: &Path, state_dir: &Path) -> Result<(), Status> { - let sandboxes_root = sandboxes_root_dir(root); - let relative = state_dir.strip_prefix(&sandboxes_root).map_err(|_| { - Status::internal(format!( - "refusing to use sandbox state path outside vm state root: {}", - state_dir.display() - )) - })?; - - let mut components = relative.components(); - match components.next() { - Some(Component::Normal(_)) => {} - _ => { - return Err(Status::internal(format!( - "refusing to use malformed sandbox state path: {}", - state_dir.display() - ))); - } - } - if components.next().is_some() { - return Err(Status::internal(format!( - "refusing to use nested sandbox state path: {}", - state_dir.display() - ))); - } - - Ok(()) -} - -async fn remove_sandbox_state_dir(root: &Path, state_dir: &Path) -> Result<(), Status> { - validate_sandbox_state_dir(root, state_dir)?; - - let metadata = match tokio::fs::symlink_metadata(state_dir).await { - Ok(metadata) => metadata, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(err) => { - return Err(Status::internal(format!( - "failed to stat sandbox state dir: {err}" - ))); - } - }; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - return Err(Status::internal(format!( - "refusing to remove symlinked sandbox state dir: {}", - state_dir.display() - ))); - } - if !file_type.is_dir() { - return Err(Status::internal(format!( - "sandbox state path is not a directory: {}", - state_dir.display() - ))); - } - - tokio::fs::remove_dir_all(state_dir) - .await - .map_err(|err| Status::internal(format!("failed to remove state dir: {err}"))) -} - -fn image_cache_root_dir(root: &Path) -> PathBuf { - root.join(IMAGE_CACHE_ROOT_DIR) -} - -fn image_cache_dir(root: &Path, image_identity: &str) -> PathBuf { - image_cache_root_dir(root).join(sanitize_image_identity(image_identity)) -} - -fn image_cache_rootfs_image(root: &Path, image_identity: &str) -> PathBuf { - image_cache_dir(root, image_identity).join(IMAGE_CACHE_ROOTFS_IMAGE) -} - -fn image_cache_staging_dir(root: &Path, image_identity: &str) -> PathBuf { - image_cache_root_dir(root).join(format!( - "{}.staging-{}", - sanitize_image_identity(image_identity), - unique_image_cache_suffix() - )) -} - -fn oci_layout_blobs_dir(layout_dir: &Path) -> PathBuf { - layout_dir.join("blobs").join("sha256") -} - -fn oci_layout_blob_path(layout_dir: &Path, digest: &str) -> Result { - let hex = sha256_digest_hex(digest)?; - Ok(oci_layout_blobs_dir(layout_dir).join(hex)) -} - -fn sha256_digest_hex(digest: &str) -> Result<&str, String> { - let Some((algorithm, hex)) = digest.split_once(':') else { - return Err(format!("digest '{digest}' is missing an algorithm")); - }; - if algorithm != "sha256" { - return Err(format!("unsupported digest algorithm '{algorithm}'")); - } - if hex.is_empty() || !hex.chars().all(|ch| ch.is_ascii_hexdigit()) { - return Err(format!("digest '{digest}' is not a valid sha256 digest")); - } - Ok(hex) -} - -fn write_oci_layout_for_manifest( - layout_dir: &Path, - ref_name: &str, - manifest: &OciImageManifest, -) -> Result<(), String> { - fs::create_dir_all(oci_layout_blobs_dir(layout_dir)) - .map_err(|err| format!("create OCI layout blobs dir failed: {err}"))?; - - fs::write( - layout_dir.join("oci-layout"), - br#"{"imageLayoutVersion":"1.0.0"}"#, - ) - .map_err(|err| format!("write OCI layout marker failed: {err}"))?; - - let manifest_bytes = serde_json::to_vec(manifest) - .map_err(|err| format!("serialize OCI manifest failed: {err}"))?; - let manifest_digest = format!("sha256:{}", compute_bytes_sha256_hex(&manifest_bytes)); - let manifest_blob = oci_layout_blob_path(layout_dir, &manifest_digest) - .map_err(|err| format!("compute OCI manifest blob path failed: {err}"))?; - fs::write(&manifest_blob, &manifest_bytes) - .map_err(|err| format!("write OCI manifest blob failed: {err}"))?; - - let media_type = manifest - .media_type - .clone() - .unwrap_or_else(|| OCI_IMAGE_MEDIA_TYPE.to_string()); - let index = serde_json::json!({ - "schemaVersion": 2, - "manifests": [ - { - "mediaType": media_type, - "digest": manifest_digest, - "size": manifest_bytes.len(), - "annotations": { - "org.opencontainers.image.ref.name": ref_name - } - } - ] - }); - let index_bytes = serde_json::to_vec_pretty(&index) - .map_err(|err| format!("serialize OCI index failed: {err}"))?; - fs::write(layout_dir.join("index.json"), index_bytes) - .map_err(|err| format!("write OCI index failed: {err}"))?; - - Ok(()) -} - -fn bootstrap_image_cache_identity(image_identity: &str) -> String { - // Bound new cache/staging filenames even for long source digests such as - // SHA-512. Persisted identities still use the unchanged path lookup. - let image_identity = compute_bytes_sha256_hex(image_identity.as_bytes()); - format!( - "{BOOTSTRAP_IMAGE_CACHE_LAYOUT_VERSION}:openshell-{}:guest-{}:{image_identity}", - openshell_core::VERSION, - sandbox_guest_runtime_identity() - ) -} - -fn configured_sandbox_identity(config: &VmDriverConfig) -> Option<(u32, u32)> { - (config.sandbox_uid.is_some() || config.sandbox_gid.is_some()).then(|| { - let uid = config.sandbox_uid.unwrap_or(DEFAULT_SANDBOX_UID); - (uid, config.sandbox_gid.unwrap_or(uid)) - }) -} - -fn prepared_image_cache_identity(image_identity: &str, config: &VmDriverConfig) -> String { - let image_identity = compute_bytes_sha256_hex(image_identity.as_bytes()); - let identity = configured_sandbox_identity(config).map_or_else( - || "image-account".to_string(), - |(uid, gid)| format!("configured-{uid}-{gid}"), - ); - format!( - "{PREPARED_IMAGE_CACHE_LAYOUT_VERSION}:openshell-{}:{identity}:{image_identity}", - openshell_core::VERSION - ) -} - -fn registry_layer_download_concurrency() -> usize { - let value = std::env::var("OPENSHELL_VM_IMAGE_PULL_CONCURRENCY").ok(); - registry_layer_download_concurrency_value(value.as_deref()) -} - -fn registry_layer_download_concurrency_value(value: Option<&str>) -> usize { - value - .and_then(|value| value.parse::().ok()) - .filter(|value| *value > 0) - .map_or(DEFAULT_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY, |value| { - value.min(MAX_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY) - }) -} - -fn sanitize_image_identity(image_identity: &str) -> String { - image_identity - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.' { - ch - } else { - '-' - } - }) - .collect() -} - -fn unique_image_cache_suffix() -> String { - let counter = IMAGE_CACHE_BUILD_COUNTER.fetch_add(1, Ordering::Relaxed); - format!("{}-{counter}", openshell_core::time::now_ms()) -} - -async fn write_sandbox_image_metadata( - state_dir: &Path, - image_ref: &str, - image_identity: &str, -) -> Result<(), std::io::Error> { - tokio::fs::write( - state_dir.join(IMAGE_IDENTITY_FILE), - format!("{image_identity}\n"), - ) - .await?; - tokio::fs::write( - state_dir.join(IMAGE_REFERENCE_FILE), - format!("{image_ref}\n"), - ) - .await?; - - Ok(()) -} - -async fn read_persisted_image_identity(state_dir: &Path) -> Result { - let raw = tokio::fs::read_to_string(state_dir.join(IMAGE_IDENTITY_FILE)).await?; - Ok(raw.trim().to_string()) -} - -async fn write_sandbox_request(state_dir: &Path, sandbox: &Sandbox) -> Result<(), std::io::Error> { - restrict_owner_only_dir(state_dir).await?; - let destination = state_dir.join(SANDBOX_REQUEST_FILE); - let sequence = IMAGE_CACHE_BUILD_COUNTER.fetch_add(1, Ordering::Relaxed); - let temporary = state_dir.join(format!( - ".{SANDBOX_REQUEST_FILE}.{}.{}.tmp", - std::process::id(), - sequence - )); - if let Err(error) = write_private_file(&temporary, sandbox.encode_to_vec()).await { - let _ = tokio::fs::remove_file(&temporary).await; - return Err(error); - } - if let Err(error) = tokio::fs::rename(&temporary, destination).await { - let _ = tokio::fs::remove_file(&temporary).await; - return Err(error); - } - Ok(()) -} - -async fn read_sandbox_request(path: &Path) -> Result { - let bytes = tokio::fs::read(path).await?; - Sandbox::decode(bytes.as_slice()).map_err(|err| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("decode persisted sandbox request: {err}"), - ) - }) -} - -async fn write_private_file(path: &Path, bytes: Vec) -> Result<(), std::io::Error> { - tokio::fs::write(path, bytes).await?; - restrict_owner_read_write(path).await -} - -async fn remove_runtime_generation_material(state_dir: &Path) -> Result<(), String> { - let generation_path = state_dir.join(HOST_BOUNDARY_GENERATION_FILE); - let generation = match tokio::fs::read_to_string(&generation_path).await { - Ok(generation) => generation.trim().to_string(), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(), - Err(error) => return Err(format!("read boundary generation marker: {error}")), - }; - if !generation.is_empty() { - let overlay = sandbox_runtime_disk_paths(state_dir).overlay_disk; - let generation_for_cleanup = generation.clone(); - tokio::task::spawn_blocking(move || { - let tls = guest_boundary_tls_paths(&generation_for_cleanup); - for guest_path in [ - PathBuf::from(guest_boundary_config_path(&generation_for_cleanup)), - tls.certificate_chain_path, - tls.private_key_path, - ] { - remove_rootfs_image_file( - &overlay, - &overlay_upper_path(&guest_path.to_string_lossy()), - )?; - } - Ok::<(), String>(()) - }) - .await - .map_err(|error| format!("guest authentication cleanup task failed: {error}"))??; - } - for path in [ - state_dir.join(HOST_AUTH_BUNDLE_FILE), - state_dir.join(HOST_RUNTIME_DESCRIPTOR_FILE), - generation_path, - ] { - match tokio::fs::remove_file(&path).await { - Ok(()) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(format!("remove {}: {error}", path.display())), - } - } - Ok(()) -} - -async fn clear_explicit_start_markers(state_dir: &Path) -> Result<(), std::io::Error> { - // Remove the terminal marker first. If clearing the durable stop marker - // fails, the sandbox remains stopped and a later start can safely retry. - for marker in [MAIN_PROCESS_EXITED_FILE, SANDBOX_STOPPED_FILE] { - match tokio::fs::remove_file(state_dir.join(marker)).await { - Ok(()) => {} - Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} - Err(err) => return Err(err), - } - } - Ok(()) -} - -#[cfg(unix)] -async fn restrict_owner_read_write(path: &Path) -> Result<(), std::io::Error> { - tokio::fs::set_permissions(path, fs::Permissions::from_mode(0o600)).await -} - -#[cfg(not(unix))] -async fn restrict_owner_read_write(_path: &Path) -> Result<(), std::io::Error> { - Ok(()) -} - -#[allow(clippy::result_large_err)] -fn validate_restored_sandbox_state( - root: &Path, - state_dir: &Path, - sandbox: &Sandbox, -) -> Result<(), Status> { - validate_sandbox_id(&sandbox.id)?; - validate_sandbox_state_dir(root, state_dir)?; - let Some(dir_name) = state_dir.file_name().and_then(|name| name.to_str()) else { - return Err(Status::internal(format!( - "sandbox state path has no valid directory name: {}", - state_dir.display() - ))); - }; - if dir_name != sandbox.id { - return Err(Status::internal(format!( - "sandbox state dir '{}' does not match persisted sandbox id '{}'", - dir_name, sandbox.id - ))); - } - Ok(()) -} - -async fn overlay_template_image_ready(path: &Path, size_bytes: u64) -> Result { - match tokio::fs::metadata(path).await { - Ok(metadata) => Ok(metadata.is_file() && metadata.len() == size_bytes), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(false), - Err(err) => Err(format!("stat overlay template {}: {err}", path.display())), - } -} - -fn ensure_sandbox_overlay_template_image( - cache_root: &Path, - template_path: &Path, - size_bytes: u64, - staging_dir: &Path, -) -> Result<(), String> { - if let Ok(metadata) = fs::metadata(template_path) - && metadata.is_file() - && metadata.len() == size_bytes - { - return Ok(()); - } - - let parent = template_path.parent().ok_or_else(|| { - format!( - "overlay template path has no parent: {}", - template_path.display() - ) - })?; - fs::create_dir_all(parent).map_err(|err| { - format!( - "create overlay template cache dir {}: {err}", - parent.display() - ) - })?; - - fs::create_dir_all(staging_dir).map_err(|error| error.to_string())?; - let staging_image = staging_dir.join("overlay-template.ext4"); - - let result = (|| { - create_empty_sandbox_overlay_image(&staging_image, size_bytes)?; - preparation::publish_cache_file(cache_root, &staging_image, template_path, Some(size_bytes)) - .map_err(|err| { - format!( - "move overlay template {} to {}: {err}", - staging_image.display(), - template_path.display() - ) - }) - })(); - - // A competing publisher may have won; only our private staged file is disposable. - let _ = fs::remove_file(&staging_image); - result -} - -fn create_empty_sandbox_overlay_image(overlay_disk: &Path, size_bytes: u64) -> Result<(), String> { - let staging_dir = overlay_staging_dir(overlay_disk); - if staging_dir.exists() { - fs::remove_dir_all(&staging_dir) - .map_err(|err| format!("remove stale overlay staging dir: {err}"))?; - } - - let result = (|| { - fs::create_dir_all(staging_dir.join("upper")) - .map_err(|err| format!("create overlay upper dir: {err}"))?; - fs::create_dir_all(staging_dir.join("work")) - .map_err(|err| format!("create overlay work dir: {err}"))?; - fs::create_dir_all(staging_dir.join("config")) - .map_err(|err| format!("create overlay config dir: {err}"))?; - - create_ext4_image_from_dir_with_size(&staging_dir, overlay_disk, size_bytes) - })(); - - let _ = fs::remove_dir_all(&staging_dir); - result -} - -fn create_sandbox_overlay_image_from_template( - template_path: &Path, - overlay_disk: &Path, -) -> Result<(), String> { - clone_or_copy_sparse_file(template_path, overlay_disk) -} - -fn prepare_sandbox_overlay_image( - template_path: &Path, - overlay_disk: &Path, - preparation: OverlayPreparation, - expected_size_bytes: u64, -) -> Result<(), String> { - if preparation == OverlayPreparation::PreserveExisting { - match fs::metadata(overlay_disk) { - Ok(metadata) if metadata.is_file() && metadata.len() == expected_size_bytes => { - return Ok(()); - } - Ok(metadata) if metadata.is_file() => { - return Err(format!( - "existing overlay disk '{}' has size {}, expected {}", - overlay_disk.display(), - metadata.len(), - expected_size_bytes - )); - } - Ok(_) => { - return Err(format!( - "existing overlay path '{}' is not a file", - overlay_disk.display() - )); - } - Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} - Err(err) => { - return Err(format!( - "stat overlay disk {}: {err}", - overlay_disk.display() - )); - } - } - } - - create_sandbox_overlay_image_from_template(template_path, overlay_disk) -} - -fn inject_guest_boundary_bundle( - overlay_disk: &Path, - guest_path: &str, - config: &BoundaryConfig, - material: &SandboxTlsMaterial, -) -> Result<(), String> { - let tls = match &config.listener { - BoundaryListener::Unix { tls, .. } - | BoundaryListener::TlsTcp { tls, .. } - | BoundaryListener::Vsock { tls, .. } - | BoundaryListener::RuntimeInitiatedTlsTcp { tls, .. } - | BoundaryListener::RuntimeInitiatedUnix { tls, .. } - | BoundaryListener::RuntimeInitiatedVsock { tls, .. } => tls.clone(), - }; - let encoded_config = config - .encode() - .map_err(|error| format!("encode VM boundary configuration: {error}"))?; - let config_path = overlay_upper_path(guest_path); - write_rootfs_image_file(overlay_disk, &config_path, &encoded_config)?; - set_rootfs_image_file_mode(overlay_disk, &config_path, 0o600)?; - for (guest_path, contents) in [ - ( - tls.certificate_chain_path, - material.certificate_chain_pem.as_bytes(), - ), - (tls.private_key_path, material.private_key_pem.as_bytes()), - ] { - let path = overlay_upper_path(guest_path.to_string_lossy().as_ref()); - write_rootfs_image_file(overlay_disk, &path, contents)?; - set_rootfs_image_file_mode(overlay_disk, &path, 0o600)?; - } - Ok(()) -} - -fn inject_guest_mount_manifest( - overlay_disk: &Path, - mounts: &[VmMountConfig], -) -> Result<(), String> { - let manifest = render_mount_manifest(mounts); - let guest_path = overlay_upper_path("/.openshell/mounts.manifest"); - write_rootfs_image_file(overlay_disk, &guest_path, manifest.as_bytes())?; - set_rootfs_image_file_mode(overlay_disk, &guest_path, 0o644)?; - Ok(()) -} - -fn guest_boundary_config_path(generation: &str) -> String { - format!("{GUEST_BOUNDARY_CONFIG_DIR}/bootstrap-{generation}.json") -} - -fn guest_boundary_tls_paths(generation: &str) -> SandboxTlsServerConfig { - SandboxTlsServerConfig { - certificate_chain_path: PathBuf::from(format!( - "{GUEST_BOUNDARY_CONFIG_DIR}/sandbox-{generation}.crt" - )), - private_key_path: PathBuf::from(format!( - "{GUEST_BOUNDARY_CONFIG_DIR}/sandbox-{generation}.key" - )), - } -} - -#[allow(clippy::result_large_err)] -#[tracing::instrument( - name = "vm.prepare_guest", - skip(dropins), - fields( - otel.name = "vm.prepare_guest", - otel.status_code = tracing::field::Empty, - overlay.path = %overlay_disk.display(), - dropin.count = dropins.len(), - ) -)] -fn inject_guest_init_dropins( - overlay_disk: &Path, - dropins: &[GuestInitDropin], -) -> Result<(), Status> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - validate_guest_init_dropins(dropins).map_err(Status::failed_precondition)?; - - // Drop-ins are *executed* in a child shell by run_openshell_init_dropins - // in the guest init script, not sourced into the parent. Mode 0o755 is - // required (the runner skips anything that is not `-x`) and is the - // contract drop-in authors should rely on. - for dropin in dropins { - let guest_path = overlay_upper_path(&format!("{GUEST_INIT_DROPIN_DIR}/{}", dropin.name)); - write_rootfs_image_file(overlay_disk, &guest_path, &dropin.contents).map_err(|err| { - Status::internal(format!( - "write VM guest init drop-in '{}' failed: {err}", - dropin.name - )) - })?; - set_rootfs_image_file_mode(overlay_disk, &guest_path, 0o755).map_err(|err| { - Status::internal(format!( - "set VM guest init drop-in '{}' executable failed: {err}", - dropin.name - )) - })?; - } - - // Write the allow-list manifest the guest runner consults. We write it - // unconditionally — including an empty manifest when no drop-ins were - // injected — so the guest always fails closed: only names the driver - // explicitly injected this launch are eligible to run, and a guest - // image cannot smuggle in extra `init.d` entries. - write_guest_init_dropin_manifest(overlay_disk, dropins)?; - span_status.finish(Ok(())) -} - -/// Build the corporate upstream-proxy arguments passed to host control. -/// -/// This operator-owned egress boundary travels on the supervisor's argv, -/// which sandbox spec/template environment and image `ENV` cannot influence. -/// Credentials are never on argv; the supervisor reads them from the -/// operator-owned host file. -fn upstream_proxy_cli_args(config: &VmDriverConfig) -> Result, String> { - let mut args = Vec::new(); - if let Some(url) = &config.upstream_proxy.https_proxy { - args.push("--upstream-proxy".to_string()); - args.push(url.clone()); - let proxy_url = Url::parse(url) - .map_err(|error| format!("invalid upstream proxy endpoint '{url}': {error}"))?; - if proxy_url - .host_str() - .is_some_and(|host| HOST_LOOPBACK_ALIASES.contains(&host)) - { - args.push("--upstream-proxy-dial-ip".to_string()); - args.push("127.0.0.1".to_string()); - } - } - if let Some(list) = &config.upstream_proxy.no_proxy { - args.push("--upstream-no-proxy".to_string()); - args.push(list.clone()); - } - if let Some(path) = &config.upstream_proxy.proxy_auth_file { - args.push("--upstream-proxy-auth-file".to_string()); - args.push(path.display().to_string()); - } - // Config validation guarantees the acknowledgement is `true` whenever an - // auth file is configured against an http:// proxy; the supervisor - // independently refuses credentials without it. - if config.upstream_proxy.proxy_auth_allow_insecure == Some(true) { - args.push("--upstream-proxy-auth-allow-insecure".to_string()); - } - // Absent means the default validated-IP CONNECT binding; only the - // explicit hostname opt-in is passed through. - if config.upstream_proxy.proxy_connect_by_hostname == Some(true) { - args.push("--upstream-proxy-connect-by-hostname".to_string()); - } - if let Some(path) = &config.proxy_ca_bundle { - args.push("--upstream-proxy-ca-bundle".to_string()); - args.push(path.display().to_string()); - } - Ok(args) -} - -/// Render the drop-in allow-list as newline-separated, ASCII-sorted, -/// de-duplicated names. Names are already validated to be path-safe by -/// [`validate_guest_init_dropins`]. -fn render_guest_init_dropin_manifest(dropins: &[GuestInitDropin]) -> Vec { - let mut names: Vec<&str> = dropins.iter().map(|d| d.name.as_str()).collect(); - names.sort_unstable(); - names.dedup(); - let mut body = names.join("\n"); - if !body.is_empty() { - body.push('\n'); - } - body.into_bytes() -} - -#[allow(clippy::result_large_err)] -fn write_guest_init_dropin_manifest( - overlay_disk: &Path, - dropins: &[GuestInitDropin], -) -> Result<(), Status> { - let guest_path = overlay_upper_path(GUEST_INIT_DROPIN_MANIFEST); - let contents = render_guest_init_dropin_manifest(dropins); - write_rootfs_image_file(overlay_disk, &guest_path, &contents).map_err(|err| { - Status::internal(format!( - "write VM guest init drop-in manifest failed: {err}" - )) - })?; - set_rootfs_image_file_mode(overlay_disk, &guest_path, 0o644).map_err(|err| { - Status::internal(format!( - "set VM guest init drop-in manifest mode failed: {err}" - )) - })?; - Ok(()) -} - -fn validate_guest_init_dropins(dropins: &[GuestInitDropin]) -> Result<(), String> { - let mut names = HashSet::new(); - for dropin in dropins { - validate_guest_init_dropin_name(&dropin.name)?; - if !names.insert(dropin.name.clone()) { - return Err(format!("duplicate VM guest init drop-in '{}'", dropin.name)); - } - } - Ok(()) -} - -fn validate_guest_init_dropin_name(name: &str) -> Result<(), String> { - if name.is_empty() || name == "." || name == ".." { - return Err("VM guest init drop-in name is empty or reserved".to_string()); - } - if !name - .chars() - .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.') - { - return Err(format!( - "VM guest init drop-in name '{name}' must contain only ASCII letters, numbers, '.', '-', or '_'" - )); - } - Ok(()) -} - -fn overlay_upper_path(guest_path: &str) -> String { - format!("/upper/{}", guest_path.trim_start_matches('/')) -} - -fn create_image_prep_disk( - image_path: &Path, - size_bytes: u64, - payload: &GuestImagePayload, -) -> Result<(), String> { - let staging_dir = overlay_staging_dir(image_path); - if staging_dir.exists() { - fs::remove_dir_all(&staging_dir) - .map_err(|err| format!("remove stale image-prep staging dir: {err}"))?; - } - - let result = (|| { - fs::create_dir_all(staging_dir.join("upper").join("srv")) - .map_err(|err| format!("create image-prep env dir: {err}"))?; - fs::create_dir_all(staging_dir.join("work")) - .map_err(|err| format!("create image-prep work dir: {err}"))?; - fs::create_dir_all(staging_dir.join("config")) - .map_err(|err| format!("create image-prep config dir: {err}"))?; - stage_guest_image_payload(&staging_dir, payload)?; - create_ext4_image_from_dir_with_size(&staging_dir, image_path, size_bytes) - })(); - - let _ = fs::remove_dir_all(&staging_dir); - result -} - -fn stage_guest_image_payload( - staging_dir: &Path, - payload: &GuestImagePayload, -) -> Result<(), String> { - let image_dir = staging_dir.join("config").join(GUEST_IMAGE_CONFIG_DIR); - fs::create_dir_all(&image_dir).map_err(|err| { - format!( - "create guest image config dir {}: {err}", - image_dir.display() - ) - })?; - fs::write(image_dir.join("ref"), payload.image_ref.as_bytes()) - .map_err(|err| format!("write guest image ref: {err}"))?; - fs::write( - image_dir.join("identity"), - payload.image_identity.as_bytes(), - ) - .map_err(|err| format!("write guest image identity: {err}"))?; - - match &payload.source { - GuestImagePayloadSource::RegistryOciLayout { layout_dir } => { - fs::write(image_dir.join("source"), b"oci-layout") - .map_err(|err| format!("write guest image source: {err}"))?; - copy_dir_recursive(layout_dir, &image_dir.join(GUEST_IMAGE_OCI_LAYOUT_DIR))?; - } - GuestImagePayloadSource::LocalDocker { rootfs_archive } => { - fs::write(image_dir.join("source"), b"local-docker") - .map_err(|err| format!("write guest image source: {err}"))?; - let dest = image_dir.join(IMAGE_EXPORT_ROOTFS_ARCHIVE); - fs::copy(rootfs_archive, &dest).map_err(|err| { - format!( - "copy guest image rootfs archive {} to {}: {err}", - rootfs_archive.display(), - dest.display() - ) - })?; - } - } - - Ok(()) -} - -fn copy_dir_recursive(source: &Path, dest: &Path) -> Result<(), String> { - fs::create_dir_all(dest).map_err(|err| format!("create {}: {err}", dest.display()))?; - for entry in fs::read_dir(source).map_err(|err| format!("read {}: {err}", source.display()))? { - let entry = entry.map_err(|err| format!("read {}: {err}", source.display()))?; - let source_path = entry.path(); - let dest_path = dest.join(entry.file_name()); - let metadata = fs::symlink_metadata(&source_path) - .map_err(|err| format!("stat {}: {err}", source_path.display()))?; - if metadata.file_type().is_dir() { - copy_dir_recursive(&source_path, &dest_path)?; - } else if metadata.file_type().is_file() { - if let Some(parent) = dest_path.parent() { - fs::create_dir_all(parent) - .map_err(|err| format!("create {}: {err}", parent.display()))?; - } - fs::copy(&source_path, &dest_path).map_err(|err| { - format!( - "copy {} to {}: {err}", - source_path.display(), - dest_path.display() - ) - })?; - } else { - return Err(format!( - "unsupported payload entry type at {}", - source_path.display() - )); - } - } - Ok(()) -} - -fn prepared_image_disk_size_bytes( - payload: &GuestImagePayload, - minimum_size_bytes: u64, -) -> Result { - let payload_size = match &payload.source { - GuestImagePayloadSource::RegistryOciLayout { layout_dir } => dir_size_bytes(layout_dir)?, - GuestImagePayloadSource::LocalDocker { rootfs_archive } => fs::metadata(rootfs_archive) - .map_err(|err| format!("stat {}: {err}", rootfs_archive.display()))? - .len(), - }; - // The payload and the unpacked rootfs coexist until the guest deletes the - // payload, and compressed layers commonly expand 2.5-3x. The disk file is - // sparse, so extra headroom costs no host disk space. - let requested = payload_size - .saturating_mul(4) - .saturating_add(1024 * 1024 * 1024); - Ok(minimum_size_bytes.max(requested)) -} - -fn dir_size_bytes(path: &Path) -> Result { - let metadata = - fs::symlink_metadata(path).map_err(|err| format!("stat {}: {err}", path.display()))?; - if metadata.file_type().is_file() { - return Ok(metadata.len()); - } - if metadata.file_type().is_symlink() { - return Ok(0); - } - let mut total = 0_u64; - for entry in fs::read_dir(path).map_err(|err| format!("read {}: {err}", path.display()))? { - let entry = entry.map_err(|err| format!("read {}: {err}", path.display()))?; - total = total.saturating_add(dir_size_bytes(&entry.path())?); - } - Ok(total) -} - -fn overlay_staging_dir(overlay_disk: &Path) -> PathBuf { - let parent = overlay_disk.parent().unwrap_or_else(|| Path::new(".")); - parent.join(format!( - ".openshell-overlay-staging-{}-{}", - std::process::id(), - openshell_core::time::now_ms() - )) -} - -/// Grace after SIGTERM before killing a host process. -const PROCESS_TERMINATION_GRACE: Duration = Duration::from_secs(5); - -/// Mirrors the supervisor's workload SIGTERM grace. -const SUPERVISOR_WORKLOAD_TERM_SECS: u64 = 5; -/// Guest process-tree termination grace plus forced-kill reap time. -const GUEST_PROCESS_TREE_SECS: u64 = DEFAULT_STOP_TIMEOUT_SECS as u64 + 2; -/// Mirrors the guest's filesystem flush timeout. -const GUEST_FLUSH_SECS: u64 = 3; -/// Allow control round trips and scheduling between shutdown stages. -const SHUTDOWN_SCHEDULING_SECS: u64 = 2; - -/// Budget for workload termination, guest process cleanup and filesystem flush. -/// The cap may interrupt slow shutdown or log draining. Only the stop timeout -/// is shared; changes to the other stage limits must be reflected here. -const SUPERVISOR_SHUTDOWN_GRACE: Duration = Duration::from_secs( - SUPERVISOR_WORKLOAD_TERM_SECS - + GUEST_PROCESS_TREE_SECS - + GUEST_FLUSH_SECS - + SHUTDOWN_SCHEDULING_SECS, -); - -/// Mirrors the gateway's stop deadline when reclaiming expired provisioning. -const STOP_CALLER_DEADLINE: Duration = Duration::from_secs(30); - -// The longest stop is the supervisor's grace plus the VM's. -const _: () = assert!( - SUPERVISOR_SHUTDOWN_GRACE.as_secs() + PROCESS_TERMINATION_GRACE.as_secs() - < STOP_CALLER_DEADLINE.as_secs() -); - -async fn terminate_vm_process(child: &mut Child) -> Result<(), std::io::Error> { - terminate_vm_process_within(child, PROCESS_TERMINATION_GRACE) - .await - .map(|_| ()) -} - -async fn terminate_vm_process_within( - child: &mut Child, - grace: Duration, -) -> Result { - if let Some(pid) = child.id() - && let Err(err) = kill(Pid::from_raw(pid.cast_signed()), Signal::SIGTERM) - && err != Errno::ESRCH - { - return Err(std::io::Error::other(format!( - "send SIGTERM to vm process {pid}: {err}" - ))); - } - - if let Ok(status) = tokio::time::timeout(grace, child.wait()).await { - status - } else { - child.kill().await?; - child.wait().await - } -} - -/// Stop the host supervisor first, then the VM it was supervising. -/// -/// Keep liveness open until the supervisor exits: EOF skips orderly workload -/// teardown, the guest filesystem flush and the supervisor's log export drain. -async fn terminate_sandbox_processes(process: &mut VmProcess) -> Result<(), std::io::Error> { - terminate_sandbox_processes_within(process, SUPERVISOR_SHUTDOWN_GRACE).await -} - -async fn terminate_sandbox_processes_within( - process: &mut VmProcess, - supervisor_grace: Duration, -) -> Result<(), std::io::Error> { - let supervisor_pid = process.supervisor.id(); - let supervisor_error = terminate_vm_process_within(&mut process.supervisor, supervisor_grace) - .await - .inspect(|status| { - // An orderly shutdown returns the workload's exit code, which can - // be nonzero even after the guest acknowledges termination. - if status.signal().is_some() { - warn!( - ?supervisor_pid, - %status, - "VM host supervisor was terminated by a signal; guest filesystem flush was not confirmed and recent writes may be lost" - ); - } - }) - .err(); - process.supervisor_liveness.take(); - let vm_error = terminate_vm_process(&mut process.child).await.err(); - - match (supervisor_error, vm_error) { - (None, None) => Ok(()), - (Some(error), None) => Err(std::io::Error::other(format!("stop supervisor: {error}"))), - (None, Some(error)) => Err(std::io::Error::other(format!("stop vm: {error}"))), - (Some(supervisor), Some(vm)) => Err(std::io::Error::other(format!( - "stop supervisor: {supervisor}; stop vm: {vm}" - ))), - } -} - -fn absolute_state_dir(state_dir: &Path) -> Result { - if state_dir.is_absolute() { - return Ok(state_dir.to_path_buf()); - } - std::env::current_dir() - .map(|working_dir| working_dir.join(state_dir)) - .map_err(|err| format!("failed to resolve VM driver state directory: {err}")) -} - -fn isolate_host_control_environment(command: &mut Command) { - command.env_clear(); -} - -/// Environment that lets the supervisor export spans, joining the current -/// trace, OCSF events, and relayed workload traces, identifying the gateway -/// that launched it. -fn supervisor_otlp_environment(config: &VmDriverConfig) -> Vec<(&'static str, String)> { - let mut environment = config.supervisor_otlp.environment(); - if config.supervisor_otlp.traces.is_some() { - environment.extend(openshell_otel::current_trace_context_environment()); - } - if let Some(name) = &config.supervisor_gateway_name { - environment.push((openshell_core::sandbox_env::GATEWAY_NAME, name.clone())); - } - environment -} - -#[tracing::instrument( - name = "vm.launch", - skip(command), - fields( - otel.name = "vm.launch", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox_id, - vm.backend = ?backend, - ) -)] -#[allow(dead_code)] -fn spawn_vm_launcher( - command: &mut Command, - sandbox_id: &str, - backend: &VmBackend, -) -> Result { - openshell_otel::record_error_result(command.spawn()) -} - -fn sandbox_snapshot(sandbox: &Sandbox, condition: SandboxCondition, deleting: bool) -> Sandbox { - Sandbox { - id: sandbox.id.clone(), - name: sandbox.name.clone(), - namespace: sandbox.namespace.clone(), - workspace: sandbox.workspace.clone(), - status: Some(SandboxStatus { - name: sandbox.name.clone(), - instance_id: String::new(), - agent_fd: String::new(), - sandbox_fd: String::new(), - conditions: vec![condition], - deleting, - ..Default::default() - }), - ..Default::default() - } -} - -fn status_with_condition( - snapshot: &Sandbox, - condition: SandboxCondition, - deleting: bool, -) -> SandboxStatus { - SandboxStatus { - name: snapshot.name.clone(), - instance_id: String::new(), - agent_fd: String::new(), - sandbox_fd: String::new(), - conditions: vec![condition], - deleting, - ..snapshot.status.clone().unwrap_or_default() - } -} - -/// VM init reconciles the named `sandbox` account to this overlay's owner. -/// Numeric selectors assert that same immutable identity; they cannot select -/// a new owner. Each empty selector independently accepts the driver default. -fn validate_vm_workload_identity( - request: Option<&WorkloadIdentityRequest>, - owner: SandboxOwnerIdentity, -) -> Result<(), String> { - let Some(request) = request else { - return Ok(()); - }; - for (field, selector, expected) in [ - ("run_as_user", request.user.as_str(), owner.uid), - ("run_as_group", request.group.as_str(), owner.gid), - ] { - if selector.is_empty() || selector == "sandbox" || selector.parse::() == Ok(expected) { - continue; - } - return Err(format!( - "VM {field} '{selector}' conflicts with the resolved workload identity {}:{}; omit the selector or request the driver-owned identity", - owner.uid, owner.gid - )); - } - Ok(()) -} - -fn provisioning_condition() -> SandboxCondition { - SandboxCondition { - r#type: "Ready".to_string(), - status: "False".to_string(), - reason: "Starting".to_string(), - message: "VM is starting".to_string(), - transition_time: None, - } -} - -fn deleting_condition() -> SandboxCondition { - SandboxCondition { - r#type: "Ready".to_string(), - status: "False".to_string(), - reason: "Deleting".to_string(), - message: "Sandbox is being deleted".to_string(), - transition_time: None, - } -} - -fn stopped_condition() -> SandboxCondition { - SandboxCondition { - r#type: "Stopped".to_string(), - status: "True".to_string(), - reason: "ComputeStopped".to_string(), - message: "VM compute is stopped and persistent state is retained".to_string(), - transition_time: None, - } -} - -fn error_condition(reason: &str, message: &str) -> SandboxCondition { - SandboxCondition { - r#type: "Ready".to_string(), - status: "False".to_string(), - reason: reason.to_string(), - message: message.to_string(), - transition_time: None, - } -} - -fn platform_event(source: &str, event_type: &str, reason: &str, message: String) -> PlatformEvent { - let mut event = PlatformEvent { - event_time: openshell_core::time::timestamp_from_millis(openshell_core::time::now_ms()) - .ok(), - source: source.to_string(), - r#type: event_type.to_string(), - reason: reason.to_string(), - message, - metadata: HashMap::new(), - }; - attach_vm_progress_metadata(&mut event); - event -} - -fn attach_vm_progress_metadata(event: &mut PlatformEvent) { - if event.source != "vm" { - return; - } - - match event.reason.as_str() { - "Scheduled" => { - mark_progress_complete( - &mut event.metadata, - PROGRESS_STEP_REQUESTING_SANDBOX, - "Sandbox allocated", - ); - mark_progress_active(&mut event.metadata, PROGRESS_STEP_PULLING_IMAGE); - } - "Pulling" => { - mark_progress_active(&mut event.metadata, PROGRESS_STEP_PULLING_IMAGE); - if let Some(image_ref) = event.metadata.get("image_ref").cloned() { - mark_progress_detail(&mut event.metadata, image_ref); - } else if let Some(image_ref) = pulling_image_from_message(&event.message) { - mark_progress_detail(&mut event.metadata, image_ref); - } - } - "Pulled" => { - let label = pulled_label(event); - mark_progress_complete(&mut event.metadata, PROGRESS_STEP_PULLING_IMAGE, label); - mark_progress_active(&mut event.metadata, PROGRESS_STEP_STARTING_SANDBOX); - } - "PullingLayer" => { - if let Some(detail) = pulling_layer_detail(&event.metadata) { - mark_progress_detail(&mut event.metadata, detail); - } - } - "ResolvingImage" => mark_progress_detail(&mut event.metadata, "Resolving image"), - "AuthenticatingRegistry" => { - mark_progress_detail(&mut event.metadata, "Authenticating registry"); - } - "FetchingManifest" => mark_progress_detail(&mut event.metadata, "Fetching image manifest"), - "CacheHit" => mark_progress_detail(&mut event.metadata, "Using cached root disk"), - "CacheMiss" => mark_progress_detail(&mut event.metadata, "Preparing image cache"), - "WaitingForImageCacheLock" => { - mark_progress_detail(&mut event.metadata, "Waiting for image cache lock"); - } - "ExportingRootfs" => { - mark_progress_detail(&mut event.metadata, "Exporting local image rootfs"); - } - "PreparingRootfs" => mark_progress_detail(&mut event.metadata, "Preparing rootfs"), - "CreatingRootDisk" => mark_progress_detail(&mut event.metadata, "Formatting root disk"), - "PreparingOverlay" => mark_progress_detail(&mut event.metadata, "Preparing overlay disk"), - "Started" => mark_progress_detail(&mut event.metadata, "Waiting for VM supervisor"), - _ => {} - } -} - -fn pulling_image_from_message(message: &str) -> Option { - let image = message - .strip_prefix("Pulling image ") - .map(str::trim) - .map(|value| value.trim_matches('"'))?; - (!image.is_empty()).then(|| image.to_string()) -} - -fn pulled_label(event: &PlatformEvent) -> String { - event - .metadata - .get("image_size_bytes") - .and_then(|value| value.parse::().ok()) - .map_or_else( - || "Image pulled".to_string(), - |bytes| format!("Image pulled ({})", format_bytes(bytes)), - ) -} - -fn pulling_layer_detail(metadata: &HashMap) -> Option { - let index = metadata.get("layer_index")?; - let total = metadata.get("layer_total")?; - let size = metadata - .get("layer_size_bytes") - .and_then(|value| value.parse::().ok()) - .map(format_bytes); - Some(size.map_or_else( - || format!("Layer {index}/{total}"), - |size| format!("Layer {index}/{total} ({size})"), - )) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::gpu::allocate_vsock_cid; - use openshell_core::progress::{ - PROGRESS_ACTIVE_DETAIL_KEY, PROGRESS_ACTIVE_STEP_KEY, PROGRESS_COMPLETE_LABEL_KEY, - PROGRESS_COMPLETE_STEP_KEY, - }; - use openshell_core::proto::compute::v1::{ - DriverSandboxSpec as SandboxSpec, DriverSandboxTemplate as SandboxTemplate, - GpuResourceRequirements, ResourceRequirements, - }; - use prost_types::{Struct, Value, value::Kind}; - use rcgen::{BasicConstraints, CertificateParams, IsCa, KeyPair}; - use std::fs; - use std::path::{Path, PathBuf}; - use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; - use std::time::{SystemTime, UNIX_EPOCH}; - use tonic::Code; - - fn test_socket_root() -> (PathBuf, Arc) { - let dir = std::env::temp_dir().join(format!( - "os-test-{:016x}", - u64::from_ne_bytes(openshell_crypto::random_bytes::<8>().expect("test entropy")) - )); - std::fs::create_dir(&dir).expect("create test socket root"); - std::fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)) - .expect("set test socket root permissions"); - let fd = rustix::fs::open( - &dir, - rustix::fs::OFlags::RDONLY - | rustix::fs::OFlags::DIRECTORY - | rustix::fs::OFlags::NOFOLLOW, - rustix::fs::Mode::empty(), - ) - .expect("open test socket root"); - (dir, Arc::new(fd)) - } - - static ENV_LOCK: std::sync::LazyLock> = - std::sync::LazyLock::new(|| std::sync::Mutex::new(())); - - #[test] - fn vm_console_diagnostic_is_bounded_to_the_tail() { - let directory = tempfile::tempdir().unwrap(); - let console = directory.path().join("rootfs-console.log"); - fs::write(&console, b"discard-this\nFATAL: sandbox startup failed\n").unwrap(); - - assert_eq!( - read_vm_console_tail(&console, 30).as_deref(), - Some("FATAL: sandbox startup failed") - ); - assert_eq!(read_vm_console_tail(&console, 0), None); - assert_eq!( - read_vm_console_tail(&directory.path().join("missing"), 30), - None - ); - } - - #[test] - fn registry_throttling_errors_are_retryable() { - let error = OciDistributionError::RegistryError { - envelope: oci_client::errors::OciEnvelope { - errors: vec![oci_client::errors::OciError { - code: OciErrorCode::Toomanyrequests, - message: "retry-after: 829.756µs, allowed: 44000/minute".to_string(), - detail: serde_json::Value::Null, - }], - }, - url: "https://ghcr.io/v2/example/manifests/latest".to_string(), - }; - - assert!(registry_error_is_retryable(&error)); - } - - #[test] - fn permanent_registry_errors_are_not_retryable() { - let error = OciDistributionError::UnauthorizedError { - url: "https://example.invalid/v2/image/manifests/latest".to_string(), - }; - - assert!(!registry_error_is_retryable(&error)); - } - - #[tokio::test] - async fn registry_request_retries_transient_errors_until_success() { - let attempts = AtomicUsize::new(0); - let result = retry_registry_request_with_delay("test request", Duration::ZERO, || async { - let attempt = attempts.fetch_add(1, Ordering::Relaxed); - if attempt < 2 { - Err(OciDistributionError::ServerError { - code: 503, - url: "https://example.invalid/v2/".to_string(), - message: "temporarily unavailable".to_string(), - }) - } else { - Ok("success") - } - }) - .await; - - assert_eq!(result.unwrap(), "success"); - assert_eq!(attempts.load(Ordering::Relaxed), 3); - } - - #[test] - fn vm_config_uses_canonical_grpc_endpoint_name() { - let config = VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - ..Default::default() - }; - let serialized = serde_json::to_value(&config).unwrap(); - assert_eq!(serialized["grpc_endpoint"], "http://127.0.0.1:8080"); - assert!(serialized.get("openshell_endpoint").is_none()); - - let parsed: VmDriverConfig = serde_json::from_value(serialized).unwrap(); - assert_eq!(parsed.grpc_endpoint, "http://127.0.0.1:8080"); - } - - #[test] - fn vm_config_rejects_legacy_openshell_endpoint() { - let config = VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - ..Default::default() - }; - let mut serialized = serde_json::to_value(config).unwrap(); - serialized.as_object_mut().unwrap().insert( - "openshell_endpoint".to_string(), - serde_json::json!("http://127.0.0.1:8080"), - ); - - let error = serde_json::from_value::(serialized) - .expect_err("legacy openshell_endpoint must be rejected as unknown"); - assert!(error.to_string().contains("openshell_endpoint")); - } - - fn normalized_test_network_ca_bundle(certificate_count: usize) -> Vec { - let mut pem = String::new(); - for _ in 0..certificate_count { - let mut params = CertificateParams::new(Vec::::new()).unwrap(); - params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); - let key = KeyPair::generate().unwrap(); - pem.push_str(¶ms.self_signed(&key).unwrap().pem()); - } - pem.into_bytes() - } - - fn write_gateway_network_ca_artifact(path: &Path, pem: &[u8]) { - let _ = fs::remove_file(path); - fs::write(path, pem).unwrap(); - #[cfg(unix)] - fs::set_permissions(path, fs::Permissions::from_mode(0o444)).unwrap(); - } - - fn network_ca_config(path: PathBuf, pem: &[u8], certificate_count: usize) -> VmDriverConfig { - VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - additional_ca_bundle: Some(path), - additional_ca_digest: Some(format!("sha256:{:x}", Sha256::digest(pem))), - additional_ca_certificate_count: Some(certificate_count), - ..Default::default() - } - } - - #[test] - fn additional_ca_launch_options_are_all_or_none_and_snapshot_is_driver_owned() { - let path = PathBuf::from("/gateway/artifact/additional-ca.crt"); - let digest = format!("sha256:{}", "a".repeat(64)); - for config in [ - VmDriverConfig { - additional_ca_bundle: Some(path.clone()), - ..Default::default() - }, - VmDriverConfig { - additional_ca_digest: Some(digest.clone()), - ..Default::default() - }, - VmDriverConfig { - additional_ca_certificate_count: Some(1), - ..Default::default() - }, - VmDriverConfig { - additional_ca_bundle: Some(path.clone()), - additional_ca_digest: Some(digest.clone()), - ..Default::default() - }, - VmDriverConfig { - additional_ca_bundle: Some(path), - additional_ca_certificate_count: Some(1), - ..Default::default() - }, - VmDriverConfig { - additional_ca_digest: Some(digest), - additional_ca_certificate_count: Some(1), - ..Default::default() - }, - ] { - let mut config = config; - let error = initialize_additional_ca_snapshot(&mut config) - .expect_err("partial private launch metadata must be rejected"); - assert!(error.contains("must be supplied together"), "{error}"); - } - - let mut no_trust = VmDriverConfig::default(); - initialize_additional_ca_snapshot(&mut no_trust) - .expect("all absent is the explicit no-trust state"); - assert!(no_trust.additional_ca_snapshot.is_none()); - - let supplied_snapshot = VmNetworkSupervisorTrustSnapshot { - bundle: NetworkSupervisorTrustBundle::new( - b"-----BEGIN CERTIFICATE-----\nprivate-fixture-bytes\n-----END CERTIFICATE-----\n" - .to_vec(), - 1, - format!("sha256:{}", "b".repeat(64)), - PathBuf::from("/untrusted/caller-snapshot"), - ), - }; - let mut caller_snapshot = VmDriverConfig { - additional_ca_snapshot: Some(supplied_snapshot.clone()), - ..Default::default() - }; - let error = initialize_additional_ca_snapshot(&mut caller_snapshot) - .expect_err("callers must not preload driver-owned snapshot bytes"); - assert!(error.contains("driver-owned"), "{error}"); - - let result = VmDriver::new(VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - bootstrap_image: "bootstrap:latest".to_string(), - additional_ca_snapshot: Some(supplied_snapshot), - ..Default::default() - }); - let error = futures::executor::block_on(result) - .err() - .expect("driver initialization must reject caller-provided snapshot state"); - assert!(error.contains("driver-owned"), "{error}"); - } - - #[test] - fn additional_ca_snapshot_verifies_normalized_digest_and_certificate_count() { - let directory = tempfile::tempdir().unwrap(); - let artifact = directory.path().join("gateway-additional-ca.crt"); - let pem = normalized_test_network_ca_bundle(1); - write_gateway_network_ca_artifact(&artifact, &pem); - - let mut accepted = network_ca_config(artifact.clone(), &pem, 1); - initialize_additional_ca_snapshot(&mut accepted) - .expect("gateway-normalized artifact should produce a snapshot"); - let snapshot = accepted.additional_ca_snapshot.as_ref().expect("snapshot"); - assert_eq!(snapshot.normalized_pem(), pem); - assert_eq!(snapshot.certificate_count(), 1); - assert!(accepted.additional_ca_bundle.is_none()); - assert!(accepted.additional_ca_digest.is_none()); - assert!(accepted.additional_ca_certificate_count.is_none()); - - let mut non_normalized_digest = network_ca_config(artifact.clone(), &pem, 1); - non_normalized_digest.additional_ca_digest = Some(format!("sha256:{}", "A".repeat(64))); - let error = initialize_additional_ca_snapshot(&mut non_normalized_digest) - .expect_err("digest must use normalized lowercase hexadecimal"); - assert!(error.contains("normalized lowercase"), "{error}"); - - let tampered = b"private replacement CA bytes must not be disclosed\n"; - fs::remove_file(&artifact).unwrap(); - fs::write(&artifact, tampered).unwrap(); - #[cfg(unix)] - fs::set_permissions(&artifact, fs::Permissions::from_mode(0o444)).unwrap(); - let mut tampered_config = network_ca_config(artifact.clone(), &pem, 1); - let error = initialize_additional_ca_snapshot(&mut tampered_config) - .expect_err("a changed gateway artifact must fail closed"); - assert!(error.contains("does not match expected digest"), "{error}"); - assert!(!error.contains("private replacement"), "{error}"); - - write_gateway_network_ca_artifact(&artifact, &pem); - let mut wrong_count = network_ca_config(artifact, &pem, 2); - let error = initialize_additional_ca_snapshot(&mut wrong_count) - .expect_err("wrong certificate count must fail closed"); - assert!(error.contains("certificate count 1, expected 2"), "{error}"); - } - - #[cfg(unix)] - #[test] - fn additional_ca_snapshot_read_is_bounded_and_never_follows_symlinks() { - use std::os::unix::fs::symlink; - - let directory = tempfile::tempdir().unwrap(); - let too_large = directory.path().join("too-large.crt"); - let bytes = vec![b'x'; MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES + 1]; - write_gateway_network_ca_artifact(&too_large, &bytes); - let mut oversized = network_ca_config(too_large, &bytes, 1); - let error = initialize_additional_ca_snapshot(&mut oversized) - .expect_err("oversized gateway artifact must be rejected before reading it"); - assert!(error.contains("exceeds the"), "{error}"); - - let target = directory.path().join("target.crt"); - let target_pem = normalized_test_network_ca_bundle(1); - write_gateway_network_ca_artifact(&target, &target_pem); - let link = directory.path().join("symlink.crt"); - symlink(&target, &link).unwrap(); - let mut symlinked = network_ca_config(link, &target_pem, 1); - let error = initialize_additional_ca_snapshot(&mut symlinked) - .expect_err("gateway artifact symlink must not be followed"); - assert!(error.contains("not a regular file"), "{error}"); - } - - #[test] - fn additional_ca_staging_uses_immutable_snapshot_and_host_supervisor_argv() { - let directory = tempfile::tempdir().unwrap(); - let artifact = directory.path().join("gateway-additional-ca.crt"); - let pem = normalized_test_network_ca_bundle(1); - write_gateway_network_ca_artifact(&artifact, &pem); - let mut config = network_ca_config(artifact.clone(), &pem, 1); - initialize_additional_ca_snapshot(&mut config).unwrap(); - let snapshot = config.additional_ca_snapshot.as_ref().unwrap(); - - // Change the original path after initialization. Staging must copy the - // retained Arc-backed bytes rather than reread this mutable source. - fs::remove_file(&artifact).unwrap(); - fs::write( - &artifact, - b"private source replacement must not reach a launch\n", - ) - .unwrap(); - #[cfg(unix)] - fs::set_permissions(&artifact, fs::Permissions::from_mode(0o444)).unwrap(); - - let state_dir = directory.path().join("sandbox-state"); - fs::create_dir(&state_dir).unwrap(); - let staged = stage_additional_ca_snapshot(&state_dir, Some(snapshot)) - .expect("stage captured bytes") - .expect("configured snapshot stages a host file"); - assert_eq!(fs::read(&staged).unwrap(), pem); - #[cfg(unix)] - assert_eq!( - fs::metadata(&staged).unwrap().permissions().mode() & 0o777, - 0o600 - ); - assert!( - !state_dir.join("overlay.ext4").exists(), - "destination trust must never be written to a guest overlay" - ); - - let args = additional_ca_supervisor_args(Some(snapshot), Some(&staged)).unwrap(); - assert_eq!( - args, - ["--additional-ca-bundle", staged.to_string_lossy().as_ref(),] - ); - let diagnostic = format!("{config:?} {snapshot:?} {args:?}"); - assert!( - !diagnostic.contains("private source replacement"), - "{diagnostic}" - ); - assert!( - !diagnostic.contains("BEGIN CERTIFICATE"), - "PEM bytes must not appear in diagnostics or argv: {diagnostic}" - ); - - let guest_env = build_guest_environment( - &Sandbox { - id: "network-ca-sandbox".to_string(), - ..Default::default() - }, - &config, - ); - assert!( - !guest_env - .iter() - .any(|entry| entry.contains("additional-ca") - || entry.contains("BEGIN CERTIFICATE")), - "destination trust must not enter guest launch environment: {guest_env:?}" - ); - } - - #[test] - fn additional_ca_staging_clears_stale_host_material_for_no_trust() { - let directory = tempfile::tempdir().unwrap(); - let artifact = directory.path().join("gateway-additional-ca.crt"); - let pem = normalized_test_network_ca_bundle(1); - write_gateway_network_ca_artifact(&artifact, &pem); - let mut config = network_ca_config(artifact, &pem, 1); - initialize_additional_ca_snapshot(&mut config).unwrap(); - let snapshot = config.additional_ca_snapshot.as_ref().unwrap(); - let state_dir = directory.path().join("sandbox-state"); - fs::create_dir(&state_dir).unwrap(); - - let staged = stage_additional_ca_snapshot(&state_dir, Some(snapshot)) - .unwrap() - .unwrap(); - assert!(staged.is_file()); - let stale_temporary = state_dir.join(format!( - "{HOST_ADDITIONAL_CA_TEMP_PREFIX}stale{HOST_ADDITIONAL_CA_TEMP_SUFFIX}" - )); - fs::write(&stale_temporary, b"stale trust bytes").unwrap(); - - assert_eq!( - stage_additional_ca_snapshot(&state_dir, None).unwrap(), - None - ); - assert!(!staged.exists()); - assert!(!stale_temporary.exists()); - assert!( - additional_ca_supervisor_args(None, None) - .unwrap() - .is_empty() - ); - - // A subsequent configured generation recreates only the host file; - // no guest-overlay state participates in either transition. - let recreated = stage_additional_ca_snapshot(&state_dir, Some(snapshot)) - .unwrap() - .unwrap(); - assert_eq!(fs::read(recreated).unwrap(), pem); - assert!(!state_dir.join("overlay.ext4").exists()); - } - - struct TestTracing { - exporter: opentelemetry_sdk::trace::InMemorySpanExporter, - _provider: opentelemetry_sdk::trace::SdkTracerProvider, - dispatch: tracing::Dispatch, - } - - impl TestTracing { - fn new() -> Self { - use opentelemetry::trace::TracerProvider as _; - use tracing_subscriber::layer::SubscriberExt as _; - - let exporter = opentelemetry_sdk::trace::InMemorySpanExporterBuilder::new().build(); - let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder() - .with_simple_exporter(exporter.clone()) - .build(); - let subscriber = tracing_subscriber::registry().with( - tracing_opentelemetry::layer().with_tracer(provider.tracer("vm-driver-test")), - ); - Self { - exporter, - _provider: provider, - dispatch: tracing::Dispatch::new(subscriber), - } - } - } - - fn assert_is_root(span: &opentelemetry_sdk::trace::SpanData) { - assert_eq!( - span.parent_span_id, - opentelemetry::trace::SpanId::INVALID, - "{:?} should be a trace root", - span.name - ); - } - - fn assert_has_parent(span: &opentelemetry_sdk::trace::SpanData) { - assert_ne!( - span.parent_span_id, - opentelemetry::trace::SpanId::INVALID, - "{:?} should have a parent", - span.name - ); - } - - fn request_with_traceparent(message: T) -> Request { - let mut request = Request::new(message); - request.metadata_mut().insert( - "traceparent", - "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" - .parse() - .unwrap(), - ); - request - } - - type TestDriverClient = - openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient< - tonic::transport::Channel, - >; - - struct TracedDriverClient { - client: TestDriverClient, - shutdown: tokio::sync::oneshot::Sender<()>, - server: JoinHandle>, - } - - impl std::ops::Deref for TracedDriverClient { - type Target = TestDriverClient; - - fn deref(&self) -> &Self::Target { - &self.client - } - } - - impl std::ops::DerefMut for TracedDriverClient { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.client - } - } - - impl TracedDriverClient { - async fn shutdown(self) { - let Self { - client, - shutdown, - server, - } = self; - drop(client); - let _ = shutdown.send(()); - tokio::time::timeout(Duration::from_secs(5), server) - .await - .expect("traced driver test server should stop") - .expect("traced driver test server task should not panic") - .expect("traced driver test server should stop cleanly"); - } - } - - async fn traced_driver_client(driver: VmDriver) -> TracedDriverClient { - use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; - - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let (shutdown, shutdown_rx) = tokio::sync::oneshot::channel(); - let server = tokio::spawn(async move { - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(ComputeDriverServer::new(driver)) - .serve_with_incoming_shutdown( - tokio_stream::wrappers::TcpListenerStream::new(listener), - async { - let _ = shutdown_rx.await; - }, - ) - .await - }); - - let client = TestDriverClient::connect(format!("http://{address}")) - .await - .unwrap(); - TracedDriverClient { - client, - shutdown, - server, - } - } - - #[tokio::test] - async fn compute_driver_rpc_span_continues_the_gateway_trace() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - let mut client = traced_driver_client(driver).await; - - client - .get_capabilities(request_with_traceparent(GetCapabilitiesRequest { - gateway: Some(openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - )), - })) - .await - .unwrap(); - client.shutdown().await; - - let spans = traced.exporter.get_finished_spans().unwrap(); - let rpc_spans = spans - .iter() - .filter(|span| span.name == "openshell.compute.v1.ComputeDriver/GetCapabilities") - .collect::>(); - assert_eq!( - rpc_spans.len(), - 1, - "middleware should create exactly one VM driver RPC span, got {:?}", - spans.iter().map(|span| &span.name).collect::>() - ); - let span = rpc_spans[0]; - assert_eq!( - span.span_context.trace_id().to_string(), - "4bf92f3577b34da6a3ce929d0e0e4736" - ); - assert_eq!(span.parent_span_id.to_string(), "00f067aa0ba902b7"); - } - - #[tokio::test] - async fn compute_driver_rpcs_record_server_spans_and_error_status() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - let mut client = traced_driver_client(driver).await; - - client - .get_capabilities(request_with_traceparent(GetCapabilitiesRequest { - gateway: Some(openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - )), - })) - .await - .unwrap(); - assert!( - client - .validate_sandbox_create(request_with_traceparent(ValidateSandboxCreateRequest { - sandbox: None, - })) - .await - .is_err() - ); - assert!( - client - .create_sandbox(request_with_traceparent(CreateSandboxRequest { - sandbox: None, - })) - .await - .is_err() - ); - assert!( - client - .get_sandbox(request_with_traceparent(GetSandboxRequest { - sandbox_id: String::new(), - name: String::new(), - })) - .await - .is_err() - ); - client - .list_sandboxes(request_with_traceparent(ListSandboxesRequest {})) - .await - .unwrap(); - assert!( - client - .stop_sandbox(request_with_traceparent(StopSandboxRequest { - sandbox_id: String::new(), - name: String::new(), - })) - .await - .is_err() - ); - client - .delete_sandbox(request_with_traceparent(DeleteSandboxRequest { - sandbox_id: String::new(), - name: String::new(), - })) - .await - .unwrap(); - let watch = client - .watch_sandboxes(request_with_traceparent(WatchSandboxesRequest {})) - .await - .unwrap(); - drop(watch); - client.shutdown().await; - - let spans = traced.exporter.get_finished_spans().unwrap(); - let expected = [ - "openshell.compute.v1.ComputeDriver/GetCapabilities", - "openshell.compute.v1.ComputeDriver/ValidateSandboxCreate", - "openshell.compute.v1.ComputeDriver/CreateSandbox", - "openshell.compute.v1.ComputeDriver/GetSandbox", - "openshell.compute.v1.ComputeDriver/ListSandboxes", - "openshell.compute.v1.ComputeDriver/StopSandbox", - "openshell.compute.v1.ComputeDriver/DeleteSandbox", - "openshell.compute.v1.ComputeDriver/WatchSandboxes", - ]; - for name in expected { - let span = spans - .iter() - .find(|span| span.name == name) - .unwrap_or_else(|| panic!("missing {name} span")); - assert_eq!(span.span_kind, opentelemetry::trace::SpanKind::Server); - assert_has_parent(span); - } - for name in [ - "openshell.compute.v1.ComputeDriver/ValidateSandboxCreate", - "openshell.compute.v1.ComputeDriver/CreateSandbox", - "openshell.compute.v1.ComputeDriver/GetSandbox", - "openshell.compute.v1.ComputeDriver/StopSandbox", - ] { - let span = spans.iter().find(|span| span.name == name).unwrap(); - assert!( - matches!(span.status, opentelemetry::trace::Status::Error { .. }), - "{name} should record an error status, got {:?}", - span.status - ); - } - let delete_rpc = spans - .iter() - .find(|span| span.name == "openshell.compute.v1.ComputeDriver/DeleteSandbox") - .expect("delete RPC span"); - let cleanup = spans - .iter() - .find(|span| { - span.name == "vm.teardown" - && span.span_context.trace_id() == delete_rpc.span_context.trace_id() - }) - .expect("delete cleanup span"); - assert_has_parent(cleanup); - } - - #[tokio::test] - async fn spawned_provisioning_and_phases_have_parents() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - driver.config.bootstrap_image = "invalid bootstrap image reference".to_string(); - let sandbox = Sandbox { - id: "sb-spawned-trace".to_string(), - name: "spawned-trace".to_string(), - spec: Some(SandboxSpec { - launch_authentication: test_launch_authentication("spawned-trace").0, - template: Some(SandboxTemplate { - image: "invalid image reference".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let request = request_with_traceparent(CreateSandboxRequest { - sandbox: Some(sandbox), - }); - - let mut client = traced_driver_client(driver.clone()).await; - client.create_sandbox(request).await.unwrap(); - driver - .wait_for_provisioning_for_test("sb-spawned-trace") - .await; - client.shutdown().await; - - let spans = traced.exporter.get_finished_spans().unwrap(); - let provisioning = spans - .iter() - .find(|span| span.name == "vm.provision") - .expect("spawned provisioning span"); - assert_has_parent(provisioning); - let prepare_images = spans - .iter() - .find(|span| span.name == "vm.prepare_images") - .expect("image preparation span"); - assert_has_parent(prepare_images); - let resolve_bootstrap = spans - .iter() - .find(|span| span.name == "vm.resolve_bootstrap_image") - .expect("bootstrap image resolution span"); - assert_has_parent(resolve_bootstrap); - } - - #[tokio::test] - async fn startup_reconciliation_is_root_and_restore_operations_have_parents() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - for suffix in ["a", "b"] { - let sandbox = Sandbox { - id: format!("sb-restored-trace-{suffix}"), - name: format!("restored-trace-{suffix}"), - spec: Some(SandboxSpec { - launch_authentication: test_launch_authentication(suffix).0, - template: Some(SandboxTemplate { - image: "invalid image reference".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let state_dir = temp.path().join("sandboxes").join(&sandbox.id); - tokio::fs::create_dir_all(&state_dir).await.unwrap(); - write_sandbox_request(&state_dir, &sandbox).await.unwrap(); - } - - driver.restore_persisted_sandboxes().await; - for suffix in ["a", "b"] { - driver - .wait_for_provisioning_for_test(&format!("sb-restored-trace-{suffix}")) - .await; - } - - let spans = traced.exporter.get_finished_spans().unwrap(); - - let reconciliations = spans - .iter() - .filter(|span| span.name == "reconcile.sandboxes") - .collect::>(); - assert_eq!( - reconciliations.len(), - 1, - "startup should reconcile all persisted sandboxes in one trace" - ); - let reconciliation = reconciliations[0]; - assert_is_root(reconciliation); - let restorations = spans - .iter() - .filter(|span| span.name == "vm.restore") - .collect::>(); - assert_eq!(restorations.len(), 2); - for restoration in restorations { - assert_has_parent(restoration); - } - let provisioning = spans - .iter() - .filter(|span| span.name == "vm.provision") - .collect::>(); - assert_eq!(provisioning.len(), 2); - for span in provisioning { - assert_has_parent(span); - } - let prepare_images = spans - .iter() - .filter(|span| span.name == "vm.prepare_images") - .collect::>(); - assert_eq!(prepare_images.len(), 2); - for span in prepare_images { - assert_has_parent(span); - } - } - - async fn assert_inactive_restore_retains_identity(marker: &str, reason: &str) { - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - // Current driver defaults and serialized status are not evidence of - // the identity that owns an already prepared overlay. - driver.config.sandbox_uid = Some(9000); - driver.config.sandbox_gid = Some(9001); - let sandbox = Sandbox { - id: "sb-inactive-identity".into(), - name: "inactive-identity".into(), - status: Some(SandboxStatus { - resolved_identity: Some(ResolvedWorkloadIdentity { - uid: 8000, - gid: 8001, - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let state_dir = sandboxes_root_dir(temp.path()).join(&sandbox.id); - tokio::fs::create_dir_all(&state_dir).await.unwrap(); - write_sandbox_request(&state_dir, &sandbox).await.unwrap(); - write_sandbox_owner_state( - &state_dir, - SandboxOwnerIdentity { - uid: 4242, - gid: 4343, - }, - ) - .await - .unwrap(); - write_sandbox_image_metadata(&state_dir, "unused-image", "sha256:original-image") - .await - .unwrap(); - tokio::fs::write(state_dir.join(marker), b"inactive\n") - .await - .unwrap(); - let mut events = driver.events.subscribe(); - - driver.restore_persisted_sandboxes().await; - - let restored = driver - .get_sandbox(&sandbox.id, &sandbox.name) - .await - .unwrap() - .unwrap(); - let status = restored.status.as_ref().unwrap(); - assert_eq!(status.conditions[0].reason, reason); - let identity = status - .resolved_identity - .as_ref() - .expect("restored overlay owner"); - assert_eq!((identity.uid, identity.gid), (4242, 4343)); - assert!(identity.supplementary_gids.is_empty()); - assert_eq!(identity.source, "vm-config"); - assert_eq!(identity.resource_digest, "sha256:original-image"); - let registry = driver.registry.lock().await; - let record = registry.get(&sandbox.id).unwrap(); - assert!(record.process.is_none()); - assert!(record.provisioning_task.is_none()); - drop(registry); - let event = events.try_recv().expect("restored snapshot event"); - let Some(watch_sandboxes_event::Payload::Sandbox(event)) = event.payload else { - panic!("expected sandbox snapshot event"); - }; - assert_eq!(event.sandbox.as_ref(), Some(&restored)); - assert_eq!( - tokio::fs::read_to_string(state_dir.join(SANDBOX_OWNER_STATE_FILE)) - .await - .unwrap(), - "sandbox-owner-v2:4242:4343\n" - ); - assert!(state_dir.join(marker).exists()); - } - - #[tokio::test] - async fn stopped_restore_retains_persisted_workload_identity() { - assert_inactive_restore_retains_identity(SANDBOX_STOPPED_FILE, "ComputeStopped").await; - } - - #[tokio::test] - async fn terminal_restore_retains_persisted_workload_identity() { - assert_inactive_restore_retains_identity(MAIN_PROCESS_EXITED_FILE, "ProcessExited").await; - } - - #[tokio::test] - async fn inactive_restore_keeps_invalid_metadata_manageable() { - for (marker, reason) in [ - (SANDBOX_STOPPED_FILE, "ComputeStopped"), - (MAIN_PROCESS_EXITED_FILE, "ProcessExited"), - ] { - for invalid_owner in [true, false] { - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - let sandbox = Sandbox { - id: "sb-invalid-owner".into(), - name: "invalid-owner".into(), - ..Default::default() - }; - let state_dir = sandboxes_root_dir(temp.path()).join(&sandbox.id); - tokio::fs::create_dir_all(&state_dir).await.unwrap(); - write_sandbox_request(&state_dir, &sandbox).await.unwrap(); - tokio::fs::write(state_dir.join(marker), b"inactive\n") - .await - .unwrap(); - let owner = if invalid_owner { - "sandbox-owner-v2:0:4343\n" - } else { - "sandbox-owner-v2:4242:4343\n" - }; - tokio::fs::write(state_dir.join(SANDBOX_OWNER_STATE_FILE), owner) - .await - .unwrap(); - if !invalid_owner { - // A directory deterministically fails read_to_string on every test host. - tokio::fs::create_dir(state_dir.join(IMAGE_IDENTITY_FILE)) - .await - .unwrap(); - } - let mut events = driver.events.subscribe(); - - driver.restore_persisted_sandboxes().await; - - let restored = driver - .get_sandbox(&sandbox.id, &sandbox.name) - .await - .unwrap() - .expect("inactive sandbox remains manageable"); - let status = restored.status.as_ref().unwrap(); - assert_eq!(status.conditions[0].reason, reason); - assert!(status.resolved_identity.is_none()); - let registry = driver.registry.lock().await; - let record = registry.get(&sandbox.id).unwrap(); - assert!(record.process.is_none()); - assert!(record.provisioning_task.is_none()); - drop(registry); - let event = events.try_recv().expect("inactive snapshot event"); - let Some(watch_sandboxes_event::Payload::Sandbox(event)) = event.payload else { - panic!("expected sandbox snapshot"); - }; - assert_eq!(event.sandbox.as_ref(), Some(&restored)); - assert!(state_dir.join(marker).exists()); - assert_eq!( - tokio::fs::read_to_string(state_dir.join(SANDBOX_OWNER_STATE_FILE)) - .await - .unwrap(), - owner - ); - assert!( - driver - .delete_sandbox(&sandbox.id, &sandbox.name) - .await - .unwrap() - .deleted - ); - assert!( - !state_dir.exists(), - "explicit delete removes retained state" - ); - } - } - } - - #[tokio::test] - async fn startup_does_not_restore_terminal_canonical_process() { - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - let sandbox = Sandbox { - id: "sb-terminal-main".to_string(), - name: "terminal-main".to_string(), - spec: Some(SandboxSpec { - template: Some(SandboxTemplate { - image: "unused-image".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let state_dir = temp.path().join("sandboxes").join(&sandbox.id); - tokio::fs::create_dir_all(&state_dir).await.unwrap(); - write_sandbox_request(&state_dir, &sandbox).await.unwrap(); - write_private_file( - &state_dir.join(MAIN_PROCESS_EXITED_FILE), - b"terminal\n".to_vec(), - ) - .await - .unwrap(); - - driver.restore_persisted_sandboxes().await; - - let registry = driver.registry.lock().await; - let record = registry.get(&sandbox.id).expect("terminal record"); - assert!(record.process.is_none()); - assert!(record.provisioning_task.is_none()); - let status = record.snapshot.status.as_ref().expect("terminal status"); - assert!( - status.resolved_identity.is_none(), - "an absent owner marker must not invent an identity" - ); - assert!(status.conditions.iter().any(|condition| { - condition.reason == "ProcessExited" && condition.status == "False" - })); - } - - #[tokio::test] - async fn process_exit_status_omits_guest_console_output() { - let running_child = || { - Command::new("sleep") - .arg("30") - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .kill_on_drop(true) - .spawn() - .unwrap() - }; - for (component, child) in [ - ("VM", spawn_exited_child()), - ("host supervisor", running_child()), - ] { - let temp = tempfile::tempdir().unwrap(); - std::fs::write(temp.path().join("rootfs-console.log"), "agent output\n").unwrap(); - std::fs::write(temp.path().join("supervisor.err.log"), "supervisor error\n").unwrap(); - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - let mut events = driver.events.subscribe(); - insert_test_record(&driver, "sb-exit", temp.path().to_path_buf(), child).await; - - driver.monitor_sandbox("sb-exit".to_string()).await; - - let condition = driver.registry.lock().await["sb-exit"] - .snapshot - .status - .as_ref() - .and_then(|status| { - status - .conditions - .iter() - .find(|condition| condition.reason == "ProcessExited") - .cloned() - }) - .expect("ProcessExited condition"); - let mut event_message = None; - while let Ok(event) = events.try_recv() { - if let Some(watch_sandboxes_event::Payload::PlatformEvent(platform)) = event.payload - && let Some(event) = platform.event - && event.reason == "ProcessExited" - { - event_message = Some(event.message); - } - } - let event_message = event_message.expect("ProcessExited platform event"); - for message in [&condition.message, &event_message] { - assert!(message.starts_with(&format!("{component} process exited"))); - assert!(!message.contains("agent output"), "{component}: {message}"); - } - if component == "host supervisor" { - assert!(condition.message.contains("supervisor error")); - } - } - } - - #[tokio::test] - async fn background_provisioning_does_not_extend_the_rpc_span_lifetime() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let rpc = tracing::info_span!("openshell.compute.v1.ComputeDriver/CreateSandbox"); - let entered = rpc.enter(); - let provisioning = - provisioning_span(&rpc.context(), "sb-lifetime", "invalid image reference"); - drop(entered); - drop(rpc); - - assert!( - traced - .exporter - .get_finished_spans() - .unwrap() - .iter() - .any(|span| span.name == "openshell.compute.v1.ComputeDriver/CreateSandbox"), - "the RPC span should finish while background provisioning is still active" - ); - drop(provisioning); - } - - #[tokio::test] - async fn overlay_preparation_records_a_provisioning_phase_span() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.overlay_disk_mib = u64::MAX; - let parent = tracing::info_span!("vm.provision"); - - let result = driver - .prepare_runtime_overlay( - Path::new("/unused"), - Path::new("/unused"), - Path::new("/unused"), - OverlayPreparation::Fresh, - None, - ) - .instrument(parent) - .await; - assert!(result.is_err(), "overflow should stop before disk I/O"); - - let spans = traced.exporter.get_finished_spans().unwrap(); - let overlay = spans - .iter() - .find(|span| span.name == "vm.prepare_overlay") - .expect("overlay preparation span"); - assert_has_parent(overlay); - assert!( - matches!(overlay.status, opentelemetry::trace::Status::Error { .. }), - "failed overlay preparation should mark its phase span, got {:?}", - overlay.status - ); - } - - #[tokio::test] - async fn post_overlay_provisioning_stages_record_child_spans() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::with(vec![Arc::new( - AlwaysFailsExtension, - )])); - let sandbox = Sandbox { - id: "sb-post-overlay".to_string(), - ..Default::default() - }; - let mut plan = driver - .build_vm_launch_plan(&sandbox.id, false, false, None) - .unwrap(); - let provisioning = tracing::info_span!("vm.provision"); - - async { - driver - .lifecycle_extensions - .configure_launch(&sandbox, Path::new("/unused"), &mut plan) - .await - .unwrap(); - let before_launch = driver - .lifecycle_extensions - .before_launch(&sandbox, Path::new("/unused"), &mut plan) - .await; - assert!( - before_launch.is_err(), - "the lifecycle hook should reject launch" - ); - let invalid_dropin = GuestInitDropin::new("../invalid", Vec::new()); - assert!( - inject_guest_init_dropins(Path::new("/unused"), &[invalid_dropin]).is_err(), - "an invalid drop-in should fail after creating its span" - ); - } - .instrument(provisioning) - .await; - - let spans = traced.exporter.get_finished_spans().unwrap(); - for name in [ - "vm.configure_launch", - "vm.before_launch", - "vm.prepare_guest", - ] { - let span = spans - .iter() - .find(|span| span.name == name) - .unwrap_or_else(|| panic!("missing {name} span")); - assert_has_parent(span); - } - for name in ["vm.before_launch", "vm.prepare_guest"] { - let span = spans.iter().find(|span| span.name == name).unwrap(); - assert!( - matches!(span.status, opentelemetry::trace::Status::Error { .. }), - "{name} should record an error status, got {:?}", - span.status - ); - } - } - - #[tokio::test] - async fn launcher_spawn_failure_records_a_failed_provisioning_phase_span() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let provisioning = tracing::info_span!("vm.provision"); - let mut command = Command::new("/openshell-test/nonexistent-vm-launcher"); - - let result = - async { spawn_vm_launcher(&mut command, "sb-launch-trace", &VmBackend::Libkrun) } - .instrument(provisioning) - .await; - assert!(result.is_err(), "the nonexistent launcher should fail"); - - let spans = traced.exporter.get_finished_spans().unwrap(); - let launch = spans - .iter() - .find(|span| span.name == "vm.launch") - .expect("launcher span"); - assert_has_parent(launch); - assert!( - matches!(launch.status, opentelemetry::trace::Status::Error { .. }), - "failed launcher spawn should mark its phase span, got {:?}", - launch.status - ); - } - - #[tokio::test] - async fn delete_failure_marks_the_delete_span() { - let traced = TestTracing::new(); - let _dispatch = tracing::dispatcher::set_default(&traced.dispatch); - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - - assert!(driver.delete_sandbox("../invalid", "").await.is_err()); - - let spans = traced.exporter.get_finished_spans().unwrap(); - let deletion = spans - .iter() - .find(|span| span.name == "vm.teardown") - .expect("delete span"); - assert!( - matches!(deletion.status, opentelemetry::trace::Status::Error { .. }), - "failed deletion should mark its span, got {:?}", - deletion.status - ); - } - - fn gpu_device_ids_config(device_ids: &[&str]) -> Struct { - list_string_driver_config("gpu_device_ids", device_ids) - } - - fn gpu_device_id_typo_config(device_ids: &[&str]) -> Struct { - list_string_driver_config("gpu_device_id", device_ids) - } - - fn list_string_driver_config(field: &str, values: &[&str]) -> Struct { - Struct { - fields: std::iter::once(( - field.to_string(), - Value { - kind: Some(Kind::ListValue(prost_types::ListValue { - values: values - .iter() - .map(|device_id| Value { - kind: Some(Kind::StringValue((*device_id).to_string())), - }) - .collect(), - })), - }, - )) - .collect(), - } - } - - fn gpu_resources(count: Option) -> ResourceRequirements { - ResourceRequirements { - gpu: Some(GpuResourceRequirements { count }), - } - } - - #[test] - fn vm_pulling_layer_event_adds_progress_detail_metadata() { - let mut event = platform_event( - "vm", - "Normal", - "PullingLayer", - "Pulling layer 3/8 for image".to_string(), - ); - event.metadata = HashMap::from([ - ("layer_index".to_string(), "3".to_string()), - ("layer_total".to_string(), "8".to_string()), - ("layer_size_bytes".to_string(), "44040192".to_string()), - ]); - - attach_vm_progress_metadata(&mut event); - - assert_eq!( - event - .metadata - .get(PROGRESS_ACTIVE_DETAIL_KEY) - .map(String::as_str), - Some("Layer 3/8 (42 MB)") - ); - } - - #[test] - fn vm_pulled_event_adds_completed_image_progress_metadata() { - let mut event = platform_event( - "vm", - "Normal", - "Pulled", - "Successfully pulled image".to_string(), - ); - event - .metadata - .insert("image_size_bytes".to_string(), "44040192".to_string()); - - attach_vm_progress_metadata(&mut event); - - assert_eq!( - event - .metadata - .get(PROGRESS_COMPLETE_STEP_KEY) - .map(String::as_str), - Some(PROGRESS_STEP_PULLING_IMAGE) - ); - assert_eq!( - event - .metadata - .get(PROGRESS_COMPLETE_LABEL_KEY) - .map(String::as_str), - Some("Image pulled (42 MB)") - ); - assert_eq!( - event - .metadata - .get(PROGRESS_ACTIVE_STEP_KEY) - .map(String::as_str), - Some(PROGRESS_STEP_STARTING_SANDBOX) - ); - } - - #[test] - fn validate_vm_sandbox_rejects_gpu_when_not_enabled() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }), - ..Default::default() - }; - let err = validate_vm_sandbox(&sandbox, false) - .expect_err("gpu should be rejected when not enabled"); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("GPU support is not enabled")); - } - - #[test] - fn validate_vm_sandbox_rejects_missing_gpu_support_before_request_shape() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(Some(2))), - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_ids_config(&["0000:2d:00.0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = validate_vm_sandbox(&sandbox, false) - .expect_err("missing GPU support should be rejected before request shape"); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("GPU support is not enabled")); - } - - #[test] - fn validate_vm_sandbox_accepts_gpu_when_enabled() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(None)), - ..Default::default() - }), - ..Default::default() - }; - validate_vm_sandbox(&sandbox, true).expect("gpu should be accepted when enabled"); - } - - #[test] - fn validate_vm_sandbox_accepts_gpu_count_one() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(Some(1))), - ..Default::default() - }), - ..Default::default() - }; - validate_vm_sandbox(&sandbox, true).expect("one GPU should be accepted when enabled"); - } - - #[test] - fn validate_vm_sandbox_accepts_single_gpu_device_without_gpu_count() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_ids_config(&["0000:2d:00.0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - validate_vm_sandbox(&sandbox, true) - .expect("single exact GPU device should be compatible with a default GPU request"); - } - - #[test] - fn validate_vm_sandbox_rejects_multiple_gpu_device_ids_without_gpu_count() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_ids_config(&["0000:2d:00.0", "0000:31:00.0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = validate_vm_sandbox(&sandbox, true) - .expect_err("multiple GPU device IDs without count should be rejected"); - - assert_eq!(err.code(), Code::InvalidArgument); - assert!( - err.message() - .contains("gpu count (1) must match driver_config.gpu_device_ids length (2)") - ); - } - - #[test] - fn validate_vm_sandbox_accepts_gpu_count_matching_device_id() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(Some(1))), - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_ids_config(&["0000:2d:00.0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - validate_vm_sandbox(&sandbox, true) - .expect("matching explicit GPU device count should be accepted"); - } - - #[test] - fn validate_vm_sandbox_rejects_gpu_count_above_one() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(Some(2))), - ..Default::default() - }), - ..Default::default() - }; - let err = validate_vm_sandbox(&sandbox, true) - .expect_err("multiple GPU VM request should be rejected"); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("support only one GPU")); - } - - #[test] - fn validate_vm_sandbox_rejects_gpu_count_mismatched_device_id() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(Some(2))), - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_ids_config(&["0000:2d:00.0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = validate_vm_sandbox(&sandbox, true) - .expect_err("mismatched explicit GPU device count should be rejected"); - - assert_eq!(err.code(), Code::InvalidArgument); - assert!( - err.message() - .contains("gpu count (2) must match driver_config.gpu_device_ids length (1)") - ); - } - - #[test] - fn validate_vm_sandbox_rejects_gpu_device_without_gpu_request() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_ids_config(&["0000:2d:00.0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = validate_vm_sandbox(&sandbox, true) - .expect_err("gpu_device_ids without a GPU request should be rejected"); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("requires a gpu request")); - } - - #[test] - fn validate_vm_sandbox_rejects_multiple_gpu_device_ids() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(Some(2))), - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_ids_config(&["0000:2d:00.0", "0000:31:00.0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = - validate_vm_sandbox(&sandbox, true).expect_err("multiple GPUs should be rejected"); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("at most one gpu_device_ids")); - } - - #[test] - fn validate_vm_sandbox_rejects_empty_gpu_device_ids() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_ids_config(&[])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = - validate_vm_sandbox(&sandbox, true).expect_err("empty GPU IDs should be rejected"); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("non-empty list")); - } - - #[test] - fn validate_vm_sandbox_rejects_unknown_driver_config_fields() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(SandboxTemplate { - driver_config: Some(gpu_device_id_typo_config(&["0000:2d:00.0"])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = - validate_vm_sandbox(&sandbox, true).expect_err("unknown field should be rejected"); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("unknown field")); - } - - #[test] - fn validate_vm_sandbox_rejects_template_errors_before_device_config() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - resource_requirements: Some(gpu_resources(None)), - template: Some(SandboxTemplate { - agent_socket_path: "/tmp/agent.sock".to_string(), - driver_config: Some(gpu_device_ids_config(&[])), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = - validate_vm_sandbox(&sandbox, true).expect_err("template error should be rejected"); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("agent_socket_path")); - } - - #[test] - fn validate_vm_sandbox_rejects_platform_config() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - template: Some(SandboxTemplate { - platform_config: Some(Struct { - fields: std::iter::once(( - "runtime_class_name".to_string(), - Value { - kind: Some(Kind::StringValue("kata".to_string())), - }, - )) - .collect(), - }), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = - validate_vm_sandbox(&sandbox, false).expect_err("platform config should be rejected"); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("platform_config")); - } - - #[test] - fn validate_vm_sandbox_accepts_template_image() { - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - template: Some(SandboxTemplate { - image: "ghcr.io/example/sandbox:latest".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - validate_vm_sandbox(&sandbox, false).expect("template.image should be accepted"); - } - - #[test] - fn validate_vm_sandbox_accepts_template_resources_as_noop() { - use openshell_core::proto::compute::v1::DriverResourceRequirements; - - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - template: Some(SandboxTemplate { - resources: Some(DriverResourceRequirements { - cpu_limit: "2".to_string(), - memory_limit: "4Gi".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - validate_vm_sandbox(&sandbox, false) - .expect("template.resources should be accepted and ignored"); - } - - #[test] - fn validate_vm_sandbox_rejects_path_unsafe_ids() { - let mut unsafe_ids = [ - "", - ".", - "..", - "../escape", - "/tmp/escape", - "nested/path", - "nested\\path", - "bad\nid", - "bad id", - "unicodé", - ] - .into_iter() - .map(str::to_string) - .collect::>(); - unsafe_ids.push("a".repeat(129)); - - for sandbox_id in unsafe_ids { - let sandbox = Sandbox { - id: sandbox_id.clone(), - spec: Some(SandboxSpec { - template: Some(SandboxTemplate { - image: "ghcr.io/example/sandbox:latest".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let err = validate_vm_sandbox(&sandbox, false) - .expect_err("path-unsafe sandbox id should be rejected"); - assert_eq!(err.code(), Code::InvalidArgument, "id={sandbox_id:?}"); - assert!(err.message().contains("sandbox id"), "id={sandbox_id:?}"); - } - } - - #[tokio::test] - async fn conflicting_vm_identity_preserves_overlay_and_owner() { - let directory = tempfile::tempdir().unwrap(); - let owner = SandboxOwnerIdentity { - uid: 1000, - gid: 1001, - }; - write_sandbox_owner_state(directory.path(), owner) - .await - .unwrap(); - let overlay = directory.path().join(SANDBOX_OVERLAY_IMAGE); - std::fs::write(&overlay, b"existing overlay must not be touched").unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.sandbox_uid = Some(10000); - driver.config.sandbox_gid = Some(10001); - let request = WorkloadIdentityRequest { - user: "10000".into(), - group: "10001".into(), - }; - let error = driver - .prepare_runtime_overlay( - directory.path(), - &overlay, - Path::new("/must-not-read-image"), - OverlayPreparation::PreserveExisting, - Some(&request), - ) - .await - .unwrap_err(); - assert!(error.contains("run_as_user '10000'"), "{error}"); - assert!(error.contains("1000:1001"), "{error}"); - assert_eq!( - std::fs::read(&overlay).unwrap(), - b"existing overlay must not be touched" - ); - assert_eq!( - std::fs::read_to_string(directory.path().join(SANDBOX_OWNER_STATE_FILE)).unwrap(), - owner.marker_contents() - ); - } - - #[tokio::test] - async fn overlay_worker_rejects_identity_conflicts_before_disk_changes() { - let directory = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = directory.path().to_path_buf(); - // A changed host default must not replace the persisted owner's identity. - driver.config.sandbox_uid = Some(10000); - driver.config.sandbox_gid = Some(10001); - let sandbox_id = "identity-worker"; - let state_dir = sandbox_state_dir(directory.path(), sandbox_id).unwrap(); - create_private_dir_all(&state_dir).await.unwrap(); - let owner = SandboxOwnerIdentity { - uid: 1000, - gid: 1001, - }; - write_sandbox_owner_state(&state_dir, owner).await.unwrap(); - let overlay_disk = sandbox_runtime_disk_paths(&state_dir).overlay_disk; - std::fs::write(&overlay_disk, b"existing overlay must not be touched").unwrap(); - - for (user, group, field) in [ - ("10000", "", "run_as_user"), - ("sandbox", "10001", "run_as_group"), - ] { - let requested_identity = WorkloadIdentityRequest { - user: user.into(), - group: group.into(), - }; - let request = preparation::OverlayRequest { - source_disk: image_cache_root_dir(directory.path()).join("must-not-read-image"), - preparation: OverlayPreparation::PreserveExisting, - requested_identity: Some(preparation::WorkloadIdentitySelectors::from( - &requested_identity, - )), - }; - // Exercise the serialized request and the same entry point the - // worker uses, so dropping either selector cannot weaken the check. - let wire = serde_json::to_vec(&request).unwrap(); - let decoded = serde_json::from_slice(&wire).unwrap(); - let error = driver - .prepare_requested_overlay(sandbox_id, decoded) - .await - .unwrap_err(); - assert!(error.message().contains(field), "{error}"); - assert!(error.message().contains("1000:1001"), "{error}"); - assert_eq!( - std::fs::read(&overlay_disk).unwrap(), - b"existing overlay must not be touched" - ); - assert_eq!( - std::fs::read_to_string(state_dir.join(SANDBOX_OWNER_STATE_FILE)).unwrap(), - owner.marker_contents() - ); - } - } - - #[test] - fn vm_workload_identity_checks_independent_numeric_and_symbolic_selectors() { - let owner = SandboxOwnerIdentity { - uid: 1000, - gid: 1001, - }; - validate_vm_workload_identity(None, owner).unwrap(); - for (user, group) in [ - ("", ""), - ("1000", ""), - ("", "1001"), - ("sandbox", "1001"), - ("1000", "sandbox"), - ("sandbox", "sandbox"), - ] { - validate_vm_workload_identity( - Some(&WorkloadIdentityRequest { - user: user.into(), - group: group.into(), - }), - owner, - ) - .unwrap(); - } - for (user, group, field) in [ - ("10000", "", "run_as_user"), - ("", "10001", "run_as_group"), - ("sandbox", "10001", "run_as_group"), - ("nobody", "", "run_as_user"), - ] { - let error = validate_vm_workload_identity( - Some(&WorkloadIdentityRequest { - user: user.into(), - group: group.into(), - }), - owner, - ) - .unwrap_err(); - assert!(error.contains(field), "{error}"); - assert!(error.contains("1000:1001"), "{error}"); - } - } - - #[test] - fn vm_lifecycle_status_retains_resolved_workload_identity() { - let identity = ResolvedWorkloadIdentity { - uid: 1000, - gid: 1001, - source: "vm-config".into(), - resource_digest: "sha256:image".into(), - ..Default::default() - }; - let snapshot = Sandbox { - status: Some(SandboxStatus { - resolved_identity: Some(identity.clone()), - ..Default::default() - }), - ..Default::default() - }; - for condition in [ - provisioning_condition(), - stopped_condition(), - deleting_condition(), - error_condition("ProcessExited", "exited"), - ] { - let status = status_with_condition(&snapshot, condition, false); - assert_eq!(status.resolved_identity.as_ref(), Some(&identity)); - } - } - - #[tokio::test] - async fn unmarked_overlay_uses_current_image_instead_of_blind_legacy_identity() { - let dir = unique_temp_dir(); - std::fs::create_dir_all(&dir).unwrap(); - let overlay = dir.join(SANDBOX_OVERLAY_IMAGE); - std::fs::write(&overlay, b"unreadable partial overlay").unwrap(); - let source = dir.join("current-rootfs-source"); - std::fs::create_dir_all(source.join("etc")).unwrap(); - std::fs::write( - source.join("etc/passwd"), - "root:x:0:0:root:/root:/bin/sh\nsandbox:x:4242:4343:Sandbox:/sandbox:/bin/sh\n", - ) - .unwrap(); - let current_rootfs = dir.join("current-rootfs.ext4"); - create_ext4_image_from_dir_with_size(&source, ¤t_rootfs, 32 * 1024 * 1024).unwrap(); - let config = VmDriverConfig { - state_dir: dir.clone(), - ..Default::default() - }; - - let (identity, write_marker) = sandbox_owner_state_for_launch( - &dir, - &overlay, - ¤t_rootfs, - &config, - OverlayPreparation::PreserveExisting, - ) - .await - .unwrap(); - - assert_eq!( - identity, - SandboxOwnerIdentity { - uid: 4242, - gid: 4343, - } - ); - assert!(write_marker); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn unmarked_overlay_without_identity_evidence_fails_safely() { - let dir = unique_temp_dir(); - std::fs::create_dir_all(&dir).unwrap(); - let overlay = dir.join(SANDBOX_OVERLAY_IMAGE); - std::fs::write(&overlay, b"unreadable partial overlay").unwrap(); - let config = VmDriverConfig { - state_dir: dir.clone(), - ..Default::default() - }; - - let error = sandbox_owner_state_for_launch( - &dir, - &overlay, - Path::new("/missing-current-rootfs"), - &config, - OverlayPreparation::PreserveExisting, - ) - .await - .expect_err("ambiguous overlay must not receive a guessed identity"); - - assert!(error.contains("missing-current-rootfs")); - assert!(!error.contains("10001")); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn fresh_overlay_uses_explicit_identity_without_image_inspection() { - let dir = unique_temp_dir(); - std::fs::create_dir_all(&dir).unwrap(); - let config = VmDriverConfig { - state_dir: dir.clone(), - sandbox_uid: Some(2000), - sandbox_gid: Some(3000), - ..Default::default() - }; - - let (identity, write_marker) = sandbox_owner_state_for_launch( - &dir, - &dir.join(SANDBOX_OVERLAY_IMAGE), - Path::new("/missing-current-rootfs"), - &config, - OverlayPreparation::Fresh, - ) - .await - .unwrap(); - - assert_eq!( - identity, - SandboxOwnerIdentity { - uid: 2000, - gid: 3000 - } - ); - assert!(write_marker); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn fresh_image_without_sandbox_account_uses_default_identity() { - let dir = unique_temp_dir(); - let source = dir.join("rootfs-source"); - std::fs::create_dir_all(source.join("etc")).unwrap(); - std::fs::write(source.join("etc/passwd"), "root:x:0:0:root:/root:/bin/sh\n").unwrap(); - let rootfs = dir.join("rootfs.ext4"); - create_ext4_image_from_dir_with_size(&source, &rootfs, 32 * 1024 * 1024).unwrap(); - let config = VmDriverConfig { - state_dir: dir.clone(), - ..Default::default() - }; - - let (identity, _) = sandbox_owner_state_for_launch( - &dir, - &dir.join(SANDBOX_OVERLAY_IMAGE), - &rootfs, - &config, - OverlayPreparation::Fresh, - ) - .await - .unwrap(); - - assert_eq!( - identity, - SandboxOwnerIdentity { - uid: DEFAULT_SANDBOX_UID, - gid: DEFAULT_SANDBOX_UID, - } - ); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn unmarked_legacy_overlay_uses_explicit_config_when_old_rootfs_is_missing() { - let dir = unique_temp_dir(); - std::fs::create_dir_all(&dir).unwrap(); - let overlay = dir.join(SANDBOX_OVERLAY_IMAGE); - std::fs::write(&overlay, b"legacy overlay").unwrap(); - let config = VmDriverConfig { - state_dir: dir.clone(), - sandbox_uid: Some(2000), - sandbox_gid: Some(3000), - ..Default::default() - }; - - let (identity, write_marker) = sandbox_owner_state_for_launch( - &dir, - &overlay, - Path::new("/missing-current-rootfs"), - &config, - OverlayPreparation::PreserveExisting, - ) - .await - .unwrap(); - - assert_eq!( - identity, - SandboxOwnerIdentity { - uid: 2000, - gid: 3000, - } - ); - assert!(write_marker); - let _ = std::fs::remove_dir_all(dir); - } - - #[test] - fn sandbox_owner_marker_rejects_malformed_or_unknown_state() { - for marker in [ - "sandbox-owner-v3:1000:1000", - "sandbox-owner-v2", - "sandbox-owner-v2:nope:1000", - "sandbox-owner-v2:0:1000", - "sandbox-owner-v2:1000:0", - "sandbox-owner-v2:1000:1000:extra", - ] { - assert!( - parse_sandbox_owner_state(marker).is_err(), - "marker should be rejected: {marker}" - ); - } - } - - #[tokio::test] - async fn image_and_overlay_owner_evidence_rejects_root_identity() { - let dir = unique_temp_dir(); - let image_source = dir.join("image-source"); - std::fs::create_dir_all(image_source.join("etc")).unwrap(); - std::fs::write( - image_source.join("etc/passwd"), - "root:x:0:0:root:/root:/bin/sh\nsandbox:x:0:0:Sandbox:/sandbox:/bin/sh\n", - ) - .unwrap(); - let image = dir.join("rootfs.ext4"); - create_ext4_image_from_dir_with_size(&image_source, &image, 32 * 1024 * 1024).unwrap(); - let image_error = sandbox_owner_identity_from_image(&image) - .await - .expect_err("root image identity must be rejected"); - assert!(image_error.contains("uid 0 is outside the allowed range")); - - let overlay_source = dir.join("overlay-source"); - std::fs::create_dir_all(overlay_source.join("upper/etc")).unwrap(); - std::fs::write( - overlay_source.join("upper/etc/passwd"), - "root:x:0:0:root:/root:/bin/sh\nsandbox:x:0:0:Sandbox:/sandbox:/bin/sh\n", - ) - .unwrap(); - let overlay = dir.join(SANDBOX_OVERLAY_IMAGE); - create_ext4_image_from_dir_with_size(&overlay_source, &overlay, 32 * 1024 * 1024).unwrap(); - let overlay_error = sandbox_owner_identity_from_overlay(&overlay) - .await - .expect_err("root overlay identity must be rejected"); - assert!(overlay_error.contains("uid 0 is outside the allowed range")); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn legacy_owner_marker_uses_evidence_migration_and_new_markers_are_private() { - let dir = unique_temp_dir(); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write( - dir.join(SANDBOX_OWNER_STATE_FILE), - format!("{SANDBOX_OWNER_STATE_V1}\n"), - ) - .unwrap(); - let overlay = dir.join(SANDBOX_OVERLAY_IMAGE); - std::fs::write(&overlay, b"legacy overlay").unwrap(); - let config = VmDriverConfig { - sandbox_uid: Some(2000), - sandbox_gid: Some(3000), - ..Default::default() - }; - - let (identity, write_marker) = sandbox_owner_state_for_launch( - &dir, - &overlay, - Path::new("/missing-rootfs"), - &config, - OverlayPreparation::PreserveExisting, - ) - .await - .unwrap(); - assert_eq!( - identity, - SandboxOwnerIdentity { - uid: 2000, - gid: 3000 - } - ); - assert!(write_marker); - - write_sandbox_owner_state(&dir, identity).await.unwrap(); - let marker = dir.join(SANDBOX_OWNER_STATE_FILE); - assert_eq!( - std::fs::read_to_string(&marker).unwrap(), - "sandbox-owner-v2:2000:3000\n" - ); - assert_eq!( - std::fs::metadata(marker).unwrap().permissions().mode() & 0o777, - 0o600 - ); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn persisted_owner_marker_preserves_exact_identity() { - let dir = unique_temp_dir(); - std::fs::create_dir_all(&dir).unwrap(); - let overlay = dir.join(SANDBOX_OVERLAY_IMAGE); - std::fs::write(&overlay, b"current overlay").unwrap(); - let expected = SandboxOwnerIdentity { - uid: 4242, - gid: 4343, - }; - write_sandbox_owner_state(&dir, expected).await.unwrap(); - let config = VmDriverConfig { - state_dir: dir.clone(), - ..Default::default() - }; - - let (identity, write_marker) = sandbox_owner_state_for_launch( - &dir, - &overlay, - Path::new("/missing-current-rootfs"), - &config, - OverlayPreparation::PreserveExisting, - ) - .await - .unwrap(); - - assert_eq!(identity, expected); - assert!(!write_marker); - assert_eq!( - std::fs::read_to_string(dir.join(SANDBOX_OWNER_STATE_FILE)).unwrap(), - "sandbox-owner-v2:4242:4343\n" - ); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn unmarked_overlay_recovers_identity_from_upper_passwd() { - let dir = unique_temp_dir(); - let overlay_source = dir.join("overlay-source"); - std::fs::create_dir_all(overlay_source.join("upper/etc")).unwrap(); - std::fs::write( - overlay_source.join("upper/etc/passwd"), - "root:x:0:0:root:/root:/bin/sh\nsandbox:x:10001:10001:Sandbox:/sandbox:/bin/sh\n", - ) - .unwrap(); - let overlay = dir.join(SANDBOX_OVERLAY_IMAGE); - create_ext4_image_from_dir_with_size(&overlay_source, &overlay, 32 * 1024 * 1024).unwrap(); - let config = VmDriverConfig { - state_dir: dir.clone(), - ..Default::default() - }; - - let (identity, write_marker) = sandbox_owner_state_for_launch( - &dir, - &overlay, - Path::new("/missing-current-rootfs"), - &config, - OverlayPreparation::PreserveExisting, - ) - .await - .unwrap(); - - assert_eq!( - identity, - SandboxOwnerIdentity { - uid: 10001, - gid: 10001, - } - ); - assert!(write_marker); - let _ = std::fs::remove_dir_all(dir); - } - - #[tokio::test] - async fn unmarked_overlay_recovers_identity_from_persisted_rootfs() { - let root = unique_temp_dir(); - let state_dir = root.join("sandboxes/sandbox-1"); - std::fs::create_dir_all(&state_dir).unwrap(); - let overlay = state_dir.join(SANDBOX_OVERLAY_IMAGE); - std::fs::write(&overlay, b"legacy overlay").unwrap(); - let prior_identity = "legacy-cache:sha256:abc"; - std::fs::write( - state_dir.join(IMAGE_IDENTITY_FILE), - format!("{prior_identity}\n"), - ) - .unwrap(); - let source = root.join("legacy-rootfs-source"); - std::fs::create_dir_all(source.join("etc")).unwrap(); - std::fs::write( - source.join("etc/passwd"), - "root:x:0:0:root:/root:/bin/sh\nsandbox:x:4242:4343:Sandbox:/sandbox:/bin/sh\n", - ) - .unwrap(); - let prior_disk = image_cache_rootfs_image(&root, prior_identity); - create_ext4_image_from_dir_with_size(&source, &prior_disk, 32 * 1024 * 1024).unwrap(); - let config = VmDriverConfig { - state_dir: root.clone(), - ..Default::default() - }; - - let (identity, write_marker) = sandbox_owner_state_for_launch( - &state_dir, - &overlay, - Path::new("/missing-current-rootfs"), - &config, - OverlayPreparation::PreserveExisting, - ) - .await - .unwrap(); - - assert_eq!( - identity, - SandboxOwnerIdentity { - uid: 4242, - gid: 4343, - } - ); - assert!(write_marker); - let _ = std::fs::remove_dir_all(root); - } - - #[test] - fn create_sandbox_socket_dir_rejects_over_long_ids() { - let (root, fd) = test_socket_root(); - let err = create_sandbox_socket_dir(&fd, &root, &"x".repeat(128)).unwrap_err(); - assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); - assert!(!root.join("x".repeat(128)).exists()); - let _ = std::fs::remove_dir_all(root); - } - - #[test] - fn sandbox_socket_dir_fits_macos_sun_path() { - let sandbox_id = "3eb2ad45-bead-4c2e-bd10-1a4a7f3a2721"; - let worst_root = "/tmp/os-4294967295-00000000000000000000000000000000"; - let control = sandbox_socket_dir(Path::new(worst_root), sandbox_id).join(VM_CONTROL_SOCKET); - let ssh = sandbox_socket_dir(Path::new(worst_root), sandbox_id).join("ssh.sock"); - assert!( - control.as_os_str().len() < 104, - "control socket path exceeds macOS sun_path: {}", - control.display() - ); - assert!( - ssh.as_os_str().len() < 104, - "ssh socket path exceeds macOS sun_path: {}", - ssh.display() - ); - } - - #[test] - fn allocate_socket_root_returns_distinct_roots() { - let tmp = tempfile::tempdir().unwrap(); - let mut counter = 0u64; - let (root_a, _fd_a) = allocate_socket_root_with(tmp.path(), || { - counter += 1; - Ok(format!("root-{counter}")) - }) - .unwrap(); - let (root_b, _fd_b) = allocate_socket_root_with(tmp.path(), || { - counter += 1; - Ok(format!("root-{counter}")) - }) - .unwrap(); - assert_ne!( - root_a, root_b, - "two allocations must produce distinct roots" - ); - } - - #[test] - fn allocate_socket_root_retries_on_occupied_name() { - let tmp = tempfile::tempdir().unwrap(); - let victim = tmp.path().join("victim"); - std::fs::create_dir(&victim).unwrap(); - let original_mode = std::fs::metadata(&victim).unwrap().permissions().mode() & 0o777; - - // attempt-0: symlink to victim directory - std::os::unix::fs::symlink(&victim, tmp.path().join("attempt-0")).unwrap(); - // attempt-1: existing directory (simulates foreign-owned pre-creation) - std::fs::create_dir(tmp.path().join("attempt-1")).unwrap(); - - let call_count = AtomicUsize::new(0); - let (root, _fd) = allocate_socket_root_with(tmp.path(), || { - let n = call_count.fetch_add(1, Ordering::SeqCst); - Ok(format!("attempt-{n}")) - }) - .expect("should succeed after retries"); - - assert_eq!(root, tmp.path().join("attempt-2")); - assert_eq!(call_count.load(Ordering::SeqCst), 3); - assert!( - tmp.path() - .join("attempt-0") - .symlink_metadata() - .unwrap() - .file_type() - .is_symlink(), - "pre-created symlink must not be removed" - ); - assert!( - tmp.path().join("attempt-1").exists(), - "pre-created directory must not be removed" - ); - let after_mode = std::fs::metadata(&victim).unwrap().permissions().mode() & 0o777; - assert_eq!( - original_mode, after_mode, - "victim directory permissions must not change" - ); - } - - #[test] - fn allocate_socket_root_propagates_name_generation_failure() { - let tmp = tempfile::tempdir().unwrap(); - let err = allocate_socket_root_with(tmp.path(), || { - Err(std::io::Error::other(openshell_crypto::CryptoError::Random)) - }) - .expect_err("entropy failure must stop allocation"); - assert_eq!(err.kind(), std::io::ErrorKind::Other); - assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0); - } - - #[test] - fn allocate_socket_root_exhaustion_returns_error() { - let tmp = tempfile::tempdir().unwrap(); - let blocked = tmp.path().join("blocked"); - std::fs::create_dir(&blocked).unwrap(); - - let err = allocate_socket_root_with(tmp.path(), || Ok("blocked".to_string())) - .expect_err("should fail when all names are occupied"); - assert_eq!(err.kind(), std::io::ErrorKind::AlreadyExists); - } - - #[test] - fn sandbox_state_dir_rejects_path_unsafe_ids() { - let err = sandbox_state_dir(Path::new("/tmp/openshell-vm"), "../escape") - .expect_err("path traversal should be rejected"); - assert_eq!(err.code(), Code::InvalidArgument); - } - - #[test] - fn sandbox_runtime_disk_paths_use_per_sandbox_overlay() { - let driver_state = Path::new("/tmp/openshell-vm"); - let state_dir = driver_state.join("sandboxes").join("sandbox-123"); - - let disks = sandbox_runtime_disk_paths(&state_dir); - - assert_eq!(disks.overlay_disk, state_dir.join(SANDBOX_OVERLAY_IMAGE)); - } - - #[test] - fn overlay_template_image_is_keyed_by_size_and_layout() { - let path = overlay_template_image(Path::new("/tmp/openshell-vm"), 4 * 1024 * 1024); - - assert_eq!( - path, - Path::new("/tmp/openshell-vm") - .join(IMAGE_CACHE_ROOT_DIR) - .join(OVERLAY_TEMPLATE_CACHE_DIR) - .join(OVERLAY_TEMPLATE_CACHE_LAYOUT_VERSION) - .join("4194304.ext4") - ); - } - - #[cfg(unix)] - #[tokio::test] - async fn host_state_dirs_stay_private() { - use std::os::unix::fs::PermissionsExt as _; - - let base = unique_temp_dir(); - let dir = base.join("sandboxes").join("sandbox-123"); - create_private_dir_all(&dir).await.unwrap(); - - let mode = std::fs::metadata(&dir).unwrap().permissions().mode(); - assert_eq!(mode & 0o777, 0o700); - let _ = std::fs::remove_dir_all(base); - } - - #[tokio::test] - async fn sandbox_request_metadata_round_trips_for_start() { - let base = unique_temp_dir(); - let state_dir = base.join("sandboxes").join("sandbox-123"); - std::fs::create_dir_all(&state_dir).unwrap(); - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - name: "start-sandbox".to_string(), - namespace: "vm-dev".to_string(), - spec: Some(SandboxSpec { - environment: HashMap::from([("KEY".to_string(), "value".to_string())]), - template: Some(SandboxTemplate { - image: "ghcr.io/example/sandbox:latest".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - - write_sandbox_request(&state_dir, &sandbox) - .await - .expect("write sandbox request"); - let restored = read_sandbox_request(&state_dir.join(SANDBOX_REQUEST_FILE)) - .await - .expect("read sandbox request"); - - assert_eq!(restored, sandbox); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - - let dir_mode = std::fs::metadata(&state_dir).unwrap().permissions().mode() & 0o777; - let file_mode = std::fs::metadata(state_dir.join(SANDBOX_REQUEST_FILE)) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(dir_mode, 0o700); - assert_eq!(file_mode, 0o600); - } - validate_restored_sandbox_state(&base, &state_dir, &restored) - .expect("restored state should validate"); - - let _ = std::fs::remove_dir_all(base); - } - - #[tokio::test] - async fn failed_start_preserves_stopped_state() { - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - let (old_authentication, old_session) = test_launch_authentication("old"); - let sandbox = Sandbox { - id: "sandbox-stopped".to_string(), - name: "stopped".to_string(), - spec: Some(SandboxSpec { - launch_authentication: old_authentication, - ..Default::default() - }), - ..Default::default() - }; - let state_dir = temp.path().join("sandboxes").join(&sandbox.id); - create_private_dir_all(&state_dir).await.unwrap(); - write_sandbox_request(&state_dir, &sandbox).await.unwrap(); - tokio::fs::write(state_dir.join(SANDBOX_STOPPED_FILE), b"stopped\n") - .await - .unwrap(); - tokio::fs::write(state_dir.join(MAIN_PROCESS_EXITED_FILE), b"terminal\n") - .await - .unwrap(); - let snapshot = sandbox_snapshot(&sandbox, stopped_condition(), false); - driver.registry.lock().await.insert( - sandbox.id.clone(), - SandboxRecord { - snapshot, - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - - let (fresh_authentication, _) = test_launch_authentication("fresh"); - let err = driver - .start_sandbox( - &sandbox.id, - &sandbox.name, - "g0000000000000001", - fresh_authentication, - ) - .await - .expect_err("start without an image should fail"); - - assert_eq!(err.code(), Code::FailedPrecondition); - assert!( - tokio::fs::metadata(state_dir.join(SANDBOX_STOPPED_FILE)) - .await - .is_ok(), - "failed start must retain its durable stop marker" - ); - assert!( - tokio::fs::metadata(state_dir.join(MAIN_PROCESS_EXITED_FILE)) - .await - .is_ok(), - "failed start must retain its terminal marker" - ); - let restored = driver - .get_sandbox(&sandbox.id, &sandbox.name) - .await - .unwrap() - .expect("failed start must retain its stopped registry record"); - let condition = restored - .status - .as_ref() - .and_then(|status| status.conditions.first()) - .expect("stopped condition"); - assert_eq!(condition.r#type, "Stopped"); - assert_eq!(condition.status, "True"); - let persisted = read_sandbox_request(&state_dir.join(SANDBOX_REQUEST_FILE)) - .await - .expect("persisted sandbox request"); - let persisted_authentication = - serde_json::from_slice::( - &persisted - .spec - .expect("persisted sandbox spec") - .launch_authentication, - ) - .expect("persisted launch authentication"); - assert_eq!(persisted_authentication.supervisor.session_id, old_session); - } - - #[tokio::test] - async fn already_running_start_noop_does_not_require_admission_provenance() { - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - let sandbox = Sandbox { - id: "sandbox-running".to_string(), - name: "running".to_string(), - ..Default::default() - }; - let state_dir = temp.path().join("sandboxes").join(&sandbox.id); - create_private_dir_all(&state_dir).await.unwrap(); - tokio::fs::write( - state_dir.join(HOST_BOUNDARY_GENERATION_FILE), - b"g0000000000000001\n", - ) - .await - .unwrap(); - let provisioning_task = tokio::spawn(std::future::pending()); - let snapshot = sandbox_snapshot(&sandbox, provisioning_condition(), false); - driver.registry.lock().await.insert( - sandbox.id.clone(), - SandboxRecord { - snapshot, - state_dir, - process: None, - provisioning_task: Some(provisioning_task), - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - - driver - .start_sandbox(&sandbox.id, &sandbox.name, "g0000000000000001", Vec::new()) - .await - .expect("matching already-running start must remain an idempotent no-op"); - - let task = driver - .registry - .lock() - .await - .remove(&sandbox.id) - .and_then(|record| record.provisioning_task) - .unwrap(); - task.abort(); - } - - #[tokio::test] - async fn blocked_worker_does_not_delay_independent_image_and_overlay_requests() { - let root = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = root.path().to_path_buf(); - driver.config.bootstrap_image = "test-bootstrap".to_string(); - driver.launcher_bin = root.path().join("worker"); - let cached_root = root.path().join("images/warm/rootfs.ext4"); - fs::create_dir_all(cached_root.parent().unwrap()).unwrap(); - fs::write(&cached_root, b"cached bootstrap").unwrap(); - let images = - preparation::Message::Complete(Ok(preparation::Output::Images(RuntimeImagePlan { - root_disk: cached_root.clone(), - image_disk: None, - image_identity: "warm".to_string(), - bootstrap_image_identity: "warm".to_string(), - }))); - let overlay = preparation::Message::Complete(Ok(preparation::Output::Overlay( - SandboxOwnerIdentity { - uid: 1000, - gid: 1000, - }, - ))); - fs::write( - root.path().join("images.json"), - serde_json::to_vec(&images).unwrap(), - ) - .unwrap(); - fs::write( - root.path().join("overlay.json"), - serde_json::to_vec(&overlay).unwrap(), - ) - .unwrap(); - fs::write( - &driver.launcher_bin, - r#"#!/bin/sh - control=$(dirname "$0") - request=$(cat "$2") - case "$request" in - *'"sandbox_id":"slow-a"'*) - : > "$control/ready" - exec sleep 300 - ;; - *'"overlay":null'*) cat "$control/images.json" ;; - *) cat "$control/overlay.json" ;; - esac - printf '\n' - "#, - ) - .unwrap(); - fs::set_permissions(&driver.launcher_bin, fs::Permissions::from_mode(0o700)).unwrap(); - for id in ["slow-a", "warm-b"] { - let state_dir = sandboxes_root_dir(root.path()).join(id); - create_private_dir_all(&state_dir).await.unwrap(); - driver.registry.lock().await.insert( - id.to_string(), - SandboxRecord { - snapshot: Sandbox { - id: id.to_string(), - ..Default::default() - }, - state_dir, - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - } - - let slow_driver = driver.clone(); - let slow = tokio::spawn(async move { - slow_driver - .prepare_images_in_worker("slow-a", "test-bootstrap", None, true) - .await - }); - let warm_driver = driver.clone(); - let ready = root.path().join("ready"); - let mut warm = tokio::spawn(async move { - while !ready.exists() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - let plan = warm_driver - .prepare_images_in_worker("warm-b", "test-bootstrap", None, true) - .await - .map_err(|error| error.to_string())?; - if plan.root_disk != cached_root { - return Err("warm image result was not preserved".to_string()); - } - let owner = warm_driver - .prepare_overlay_in_worker( - "warm-b", - &plan.root_disk, - OverlayPreparation::Fresh, - None, - ) - .await - .map_err(|error| error.to_string())?; - if owner - != (SandboxOwnerIdentity { - uid: 1000, - gid: 1000, - }) - { - return Err("warm overlay result was not preserved".to_string()); - } - Ok::<(), String>(()) - }); - let outcome = match tokio::time::timeout(Duration::from_secs(10), &mut warm).await { - Ok(Ok(result)) => result, - Ok(Err(error)) => Err(format!("warm task failed: {error}")), - Err(_) => { - warm.abort(); - let _ = warm.await; - Err("warm request waited for the unrelated slow worker".to_string()) - } - }; - let slow_still_running = !slow.is_finished(); - slow.abort(); - let _ = slow.await; - let warm_cleanup = driver.cleanup_image_preparation("warm-b").await; - let slow_cleanup = driver.cleanup_image_preparation("slow-a").await; - warm_cleanup.expect("warm worker cleanup"); - slow_cleanup.expect("slow worker cleanup"); - outcome.expect("independent image and overlay requests must complete"); - assert!( - slow_still_running, - "the slow worker must remain blocked during the proof" - ); - } - - async fn lifecycle_cancels_image_preparation(delete: bool) { - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - let id = "sandbox-cancel-image"; - let state_dir = sandboxes_root_dir(temp.path()).join(id); - create_private_dir_all(&state_dir).await.unwrap(); - let launcher = temp.path().join("worker"); - fs::write(&launcher, "#!/bin/sh\nroot=$(dirname \"$2\")\nsleep 300 &\nprintf ready > \"$root/ready\"\nwait\n").unwrap(); - fs::set_permissions(&launcher, fs::Permissions::from_mode(0o700)).unwrap(); - let cache = image_cache_root_dir(temp.path()); - let mut attempt = preparation::Attempt::create(&cache).unwrap(); - let directory = attempt.directory.clone(); - let _stdout = attempt - .spawn( - &launcher, - preparation::Request { - config: driver.config.clone(), - sandbox_id: id.to_string(), - image_ref: "test-image".to_string(), - rootfs_tar: None, - bootstrap_only: false, - overlay: None, - lease_fd: -1, - parent_pid: 0, - }, - ) - .unwrap(); - tokio::time::timeout(Duration::from_secs(5), async { - while !directory.join("ready").exists() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("preparation worker readiness"); - let attempt = Arc::new(Mutex::new(attempt)); - driver.registry.lock().await.insert( - id.to_string(), - SandboxRecord { - snapshot: Sandbox { - id: id.to_string(), - name: "cancel-image".to_string(), - ..Default::default() - }, - state_dir: state_dir.clone(), - process: None, - provisioning_task: Some(tokio::spawn(std::future::pending())), - preparation: Some(attempt.clone()), - gpu_bdf: None, - deleting: false, - }, - ); - if delete { - let response = driver.delete_sandbox(id, "").await.unwrap(); - assert!(response.deleted); - assert!(!state_dir.exists()); - } else { - driver.stop_sandbox(id, "").await.unwrap(); - assert!(state_dir.join(SANDBOX_STOPPED_FILE).exists()); - } - assert!( - !directory.exists(), - "lifecycle completion must reclaim preparation staging" - ); - attempt - .lock() - .await - .cleanup() - .await - .expect("worker was reaped and cleanup is idempotent"); - } - - #[tokio::test] - async fn stop_waits_for_image_preparation_cleanup() { - lifecycle_cancels_image_preparation(false).await; - } - - #[tokio::test] - async fn delete_waits_for_image_preparation_cleanup() { - lifecycle_cancels_image_preparation(true).await; - } - - #[tokio::test] - async fn incomplete_preparation_cleanup_failure_preserves_sandbox_state() { - let temp = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = temp.path().to_path_buf(); - let id = "sandbox-incomplete-cleanup"; - let state_dir = sandboxes_root_dir(temp.path()).join(id); - create_private_dir_all(&state_dir).await.unwrap(); - let overlay = state_dir.join(SANDBOX_OVERLAY_IMAGE); - fs::write(&overlay, b"owned overlay").unwrap(); - let attempt = Arc::new(Mutex::new( - preparation::Attempt::create(&image_cache_root_dir(temp.path())).unwrap(), - )); - driver.registry.lock().await.insert( - id.to_string(), - SandboxRecord { - snapshot: Sandbox { - id: id.to_string(), - ..Default::default() - }, - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: Some(attempt), - gpu_bdf: None, - deleting: false, - }, - ); - - // Failed worker cleanup retains the registered attempt. Its failure - // epilogue must not remove state that a descendant could still write. - driver - .fail_provisioning( - id, - &state_dir, - "PreparationFailed", - "image preparation descendants still own staging; files retained", - true, - ) - .await; - let retained = fs::read(&overlay); - driver.cleanup_image_preparation(id).await.unwrap(); - assert_eq!(retained.unwrap(), b"owned overlay"); - - driver - .fail_provisioning(id, &state_dir, "PreparationFailed", "worker stopped", true) - .await; - assert!( - !state_dir.exists(), - "successful worker cleanup permits removing failed sandbox state" - ); - } - - #[tokio::test] - async fn malformed_start_preserves_active_and_stopped_generation_material() { - for active in [false, true] { - let directory = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = directory.path().to_path_buf(); - driver.config.default_image = "test/image:latest".to_string(); - let sandbox = Sandbox { - id: "sb-auth-start".to_string(), - name: "auth-start".to_string(), - spec: Some(SandboxSpec { - launch_authentication: test_launch_authentication("existing").0, - ..Default::default() - }), - ..Default::default() - }; - let state_dir = directory.path().join("sandbox"); - create_private_dir_all(&state_dir).await.unwrap(); - write_sandbox_request(&state_dir, &sandbox).await.unwrap(); - // An empty marker on the stopped fixture avoids invoking debugfs if - // the guard regresses, so the test reaches the destructive host cleanup. - let generation = if active { "g0000000000000001" } else { "" }; - std::fs::write(state_dir.join(HOST_BOUNDARY_GENERATION_FILE), generation).unwrap(); - std::fs::write( - state_dir.join(HOST_AUTH_BUNDLE_FILE), - b"retained authentication", - ) - .unwrap(); - let task = active.then(|| tokio::spawn(std::future::pending())); - driver.registry.lock().await.insert( - sandbox.id.clone(), - SandboxRecord { - snapshot: sandbox.clone(), - state_dir: state_dir.clone(), - process: None, - provisioning_task: task, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - let error = driver - .start_sandbox( - &sandbox.id, - &sandbox.name, - "g0000000000000001", - br#"{"secret-marker-that-must-not-be-logged":true}"#.to_vec(), - ) - .await - .unwrap_err(); - assert_eq!(error.code(), Code::FailedPrecondition); - assert_eq!( - error.message(), - "VM sandbox launch authentication is malformed" - ); - assert_eq!( - std::fs::read_to_string(state_dir.join(HOST_BOUNDARY_GENERATION_FILE)).unwrap(), - generation - ); - assert_eq!( - std::fs::read(state_dir.join(HOST_AUTH_BUNDLE_FILE)).unwrap(), - b"retained authentication" - ); - let record = driver.registry.lock().await.remove(&sandbox.id).unwrap(); - assert_eq!(record.snapshot, sandbox); - assert_eq!(record.provisioning_task.is_some(), active); - if let Some(task) = record.provisioning_task { - assert!(!task.is_finished()); - task.abort(); - } - } - } - - fn test_launch_authentication(label: &str) -> (Vec, openshell_core::SandboxSessionId) { - use openshell_core::jwt::{ - SandboxLaunchAuthentication, SecretJwt, SessionVerificationKey, SupervisorAuthBundle, - }; - - let session_id = openshell_core::SandboxSessionId::new(); - let authentication = SandboxLaunchAuthentication { - supervisor: SupervisorAuthBundle { - session_id, - runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( - "generation-1", - ) - .expect("runtime generation"), - session_rotation: openshell_core::jwt::SessionRotation::new(1) - .expect("session rotation"), - auth_epoch: openshell_core::jwt::CredentialEpoch::new(1).expect("auth epoch"), - gateway_token: SecretJwt::parse(format!("gateway-{label}")).expect("gateway token"), - gateway_expires_at: 1, - sandbox_token: SecretJwt::parse(format!("sandbox-{label}")).expect("sandbox token"), - sandbox_expires_at: 1, - ssh_host_private_key: None, - traces_otlp_headers: None, - ocsf_otlp_headers: None, - agent_otlp_headers: None, - otlp_tls: Vec::new(), - traces_otlp_tls: None, - ocsf_otlp_tls: None, - agent_otlp_tls: None, - }, - gateway_id: "gateway-a".to_string(), - verification_keys: vec![SessionVerificationKey { - key_id: "key-a".to_string(), - public_key_pem: b"public-key".to_vec(), - }], - }; - ( - serde_json::to_vec(&authentication).expect("encode launch authentication"), - session_id, - ) - } - - #[tokio::test] - async fn explicit_start_clears_stop_and_terminal_markers() { - let temp = tempfile::tempdir().unwrap(); - let state_dir = temp.path().join("sandbox"); - tokio::fs::create_dir_all(&state_dir).await.unwrap(); - tokio::fs::write(state_dir.join(SANDBOX_STOPPED_FILE), b"stopped\n") - .await - .unwrap(); - tokio::fs::write(state_dir.join(MAIN_PROCESS_EXITED_FILE), b"terminal\n") - .await - .unwrap(); - - clear_explicit_start_markers(&state_dir).await.unwrap(); - - assert!( - !tokio::fs::try_exists(state_dir.join(SANDBOX_STOPPED_FILE)) - .await - .unwrap() - ); - assert!( - !tokio::fs::try_exists(state_dir.join(MAIN_PROCESS_EXITED_FILE)) - .await - .unwrap() - ); - } - - #[test] - fn prepare_sandbox_overlay_preserves_existing_overlay_on_start() { - let base = unique_temp_dir(); - std::fs::create_dir_all(&base).unwrap(); - let template = base.join("template.ext4"); - let overlay = base.join("overlay.ext4"); - std::fs::write(&template, b"fresh-overlay").unwrap(); - std::fs::write(&overlay, b"saved-overlay").unwrap(); - - prepare_sandbox_overlay_image( - &template, - &overlay, - OverlayPreparation::PreserveExisting, - "saved-overlay".len() as u64, - ) - .expect("preserve existing overlay"); - - assert_eq!(std::fs::read(&overlay).unwrap(), b"saved-overlay"); - - let _ = std::fs::remove_dir_all(base); - } - - #[test] - fn prepare_sandbox_overlay_creates_missing_overlay_on_start() { - let base = unique_temp_dir(); - std::fs::create_dir_all(&base).unwrap(); - let template = base.join("template.ext4"); - let overlay = base.join("overlay.ext4"); - std::fs::write(&template, b"fresh-overlay").unwrap(); - - prepare_sandbox_overlay_image( - &template, - &overlay, - OverlayPreparation::PreserveExisting, - "fresh-overlay".len() as u64, - ) - .expect("create missing overlay"); - - assert_eq!(std::fs::read(&overlay).unwrap(), b"fresh-overlay"); - - let _ = std::fs::remove_dir_all(base); - } - - #[test] - fn overlay_upper_path_targets_overlay_upperdir() { - assert_eq!( - overlay_upper_path(&guest_boundary_config_path("generation-123")), - "/upper/.openshell/state/bootstrap-generation-123.json" - ); - } - - #[test] - fn capabilities_report_configured_default_image() { - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig { - default_image: "openshell/sandbox:dev".to_string(), - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("/tmp/openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events: broadcast::channel(WATCH_BUFFER).0, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - - assert_eq!(driver.capabilities().default_image, "openshell/sandbox:dev"); - let gateway = openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - ); - let negotiated = openshell_core::extension_protocol::negotiate( - openshell_core::extension_protocol::ExtensionFamily::Compute, - "vm", - &gateway, - driver.capabilities().extension, - ) - .unwrap(); - assert!(negotiated.required_capabilities.iter().any(|capability| { - capability == openshell_core::extension_protocol::COMPUTE_LAUNCH_AUTHENTICATION - })); - } - - #[tokio::test] - async fn launch_authentication_is_checked_before_create_side_effects() { - let directory = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = directory.path().to_path_buf(); - driver.config.default_image = "invalid image reference".to_string(); - let mut events = driver.events.subscribe(); - let mut invalid_fields: serde_json::Value = - serde_json::from_slice(&test_launch_authentication("invalid-fields").0).unwrap(); - invalid_fields["verification_keys"] = serde_json::json!([]); - let malformed = br#"{"secret-marker-that-must-not-be-logged":true}"#.to_vec(); - - for (authentication, diagnostic) in [ - (Vec::new(), "is required"), - (malformed, "is malformed"), - ( - serde_json::to_vec(&invalid_fields).unwrap(), - "has invalid fields", - ), - ] { - let sandbox = Sandbox { - id: "sb-auth-preflight".to_string(), - name: "auth-preflight".to_string(), - spec: Some(SandboxSpec { - launch_authentication: authentication, - ..Default::default() - }), - ..Default::default() - }; - let error = driver - .create_sandbox(&sandbox) - .await - .expect_err("invalid launch material must fail synchronously"); - assert_eq!(error.code(), Code::FailedPrecondition); - assert!(error.message().contains(diagnostic), "{error}"); - assert!(!error.message().contains("secret-marker")); - assert!(driver.registry.lock().await.is_empty()); - assert!(directory.path().read_dir().unwrap().next().is_none()); - assert!(matches!( - events.try_recv(), - Err(broadcast::error::TryRecvError::Empty) - )); - } - } - - #[tokio::test] - async fn provisioning_rechecks_launch_authentication_before_resolving_images() { - let directory = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = directory.path().to_path_buf(); - driver.config.bootstrap_image = "invalid bootstrap image reference".to_string(); - let sandbox = Sandbox { - id: "sb-auth-recovery".to_string(), - name: "auth-recovery".to_string(), - spec: Some(SandboxSpec::default()), - ..Default::default() - }; - let state_dir = directory.path().join("sandbox"); - driver.registry.lock().await.insert( - sandbox.id.clone(), - SandboxRecord { - snapshot: sandbox.clone(), - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - let mut events = driver.events.subscribe(); - let error = driver - .provision_sandbox_inner( - sandbox, - "invalid image reference".to_string(), - state_dir, - None, - OverlayPreparation::PreserveExisting, - ) - .await - .unwrap_err(); - assert!( - error - .message() - .contains("VM sandbox launch authentication is required") - ); - assert!(matches!( - events.try_recv(), - Err(broadcast::error::TryRecvError::Empty) - )); - assert!(directory.path().read_dir().unwrap().next().is_none()); - } - - #[tokio::test] - async fn recovery_rejects_invalid_launch_authentication_before_side_effects() { - #[derive(Debug, Default)] - struct RestoreObserver { - calls: AtomicUsize, - } - - #[tonic::async_trait] - impl LifecycleExtension for RestoreObserver { - fn name(&self) -> &'static str { - "restore-observer" - } - - async fn before_restore(&self, _sandbox: &RestoreContext) -> LifecycleResult<()> { - self.calls.fetch_add(1, Ordering::Relaxed); - Ok(()) - } - } - - for scan_at_startup in [true, false] { - for authentication in [ - Vec::new(), - br#"{"secret-marker-that-must-not-be-logged":true}"#.to_vec(), - ] { - let directory = tempfile::tempdir().unwrap(); - let observer = Arc::new(RestoreObserver::default()); - let mut driver = - test_driver_with_extensions(LifecycleExtensionRegistry::with(vec![ - observer.clone(), - ])); - driver.config.state_dir = directory.path().to_path_buf(); - driver.config.default_image = "invalid image reference".to_string(); - let sandbox = Sandbox { - id: "sb-auth-restore".to_string(), - name: "auth-restore".to_string(), - spec: Some(SandboxSpec { - launch_authentication: authentication, - ..Default::default() - }), - ..Default::default() - }; - let state_dir = sandbox_state_dir(directory.path(), &sandbox.id).unwrap(); - create_private_dir_all(&state_dir).await.unwrap(); - write_sandbox_request(&state_dir, &sandbox).await.unwrap(); - fs::write(state_dir.join("overlay.ext4"), b"retained overlay").unwrap(); - fs::write(state_dir.join(HOST_AUTH_BUNDLE_FILE), b"retained auth").unwrap(); - if !scan_at_startup { - fs::write(state_dir.join(SANDBOX_STOPPED_FILE), b"stopped\n").unwrap(); - } - let mut original_files = fs::read_dir(&state_dir) - .unwrap() - .map(|entry| { - let entry = entry.unwrap(); - (entry.file_name(), fs::read(entry.path()).unwrap()) - }) - .collect::>(); - original_files.sort(); - let mut events = driver.events.subscribe(); - - let accepted = if scan_at_startup { - driver.restore_persisted_sandboxes().await; - false - } else { - driver - .restore_persisted_sandbox( - sandbox.clone(), - state_dir.clone(), - true, - &tracing::Span::current(), - ) - .await - }; - // If validation regresses, join the failed provisioning task so - // its later cleanup cannot race with the state assertions. - let task = driver - .registry - .lock() - .await - .get_mut(&sandbox.id) - .and_then(|record| record.provisioning_task.take()); - if let Some(task) = task { - task.await.unwrap(); - } - - assert!( - !accepted, - "invalid launch credentials must deny restoration" - ); - assert_eq!( - observer.calls.load(Ordering::Relaxed), - 0, - "launch authentication must precede lifecycle extension hooks" - ); - assert!(driver.registry.lock().await.is_empty()); - assert!(matches!( - events.try_recv(), - Err(broadcast::error::TryRecvError::Empty) - )); - assert!( - !extension_state_dir(&state_dir, "restore-observer") - .unwrap() - .exists() - ); - let mut retained_files = fs::read_dir(&state_dir) - .unwrap() - .map(|entry| { - let entry = entry.unwrap(); - (entry.file_name(), fs::read(entry.path()).unwrap()) - }) - .collect::>(); - retained_files.sort(); - assert_eq!(retained_files, original_files); - } - } - } - - #[test] - fn host_control_receives_driver_owned_completion_marker() { - let mut command = Command::new("openshell-sandbox"); - configure_main_exit_marker(&mut command, Path::new("/private/sandboxes/sb-1")); - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--main-exit-marker".to_string(), - "/private/sandboxes/sb-1/main-process-exited".to_string(), - ] - ); - } - - #[test] - fn resolved_sandbox_image_prefers_template_image() { - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig { - default_image: "openshell/sandbox:default".to_string(), - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("/tmp/openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events: broadcast::channel(WATCH_BUFFER).0, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - let sandbox = Sandbox { - spec: Some(SandboxSpec { - template: Some(SandboxTemplate { - image: "ghcr.io/example/custom:latest".to_string(), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - - assert_eq!( - driver.resolved_sandbox_image(&sandbox).as_deref(), - Some("ghcr.io/example/custom:latest") - ); - } - - #[test] - fn resolved_sandbox_image_falls_back_to_driver_default() { - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig { - default_image: "openshell/sandbox:default".to_string(), - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("/tmp/openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events: broadcast::channel(WATCH_BUFFER).0, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - let sandbox = Sandbox { - spec: Some(SandboxSpec { - template: Some(SandboxTemplate::default()), - ..Default::default() - }), - ..Default::default() - }; - - assert_eq!( - driver.resolved_sandbox_image(&sandbox).as_deref(), - Some("openshell/sandbox:default") - ); - } - - #[test] - fn resolved_sandbox_image_returns_none_without_template_or_default() { - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig::default(), - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("/tmp/openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events: broadcast::channel(WATCH_BUFFER).0, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - let sandbox = Sandbox { - spec: Some(SandboxSpec { - template: Some(SandboxTemplate::default()), - ..Default::default() - }), - ..Default::default() - }; - - assert!(driver.resolved_sandbox_image(&sandbox).is_none()); - } - - #[test] - fn bootstrap_image_ref_prefers_explicit_bootstrap_image() { - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig { - default_image: "openshell/sandbox:default".to_string(), - bootstrap_image: "openshell/sandbox-bootstrap:latest".to_string(), - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("/tmp/openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events: broadcast::channel(WATCH_BUFFER).0, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - - assert_eq!( - driver.bootstrap_image_ref().unwrap(), - "openshell/sandbox-bootstrap:latest" - ); - } - - #[test] - fn bootstrap_image_ref_falls_back_to_default_image() { - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig { - default_image: "openshell/sandbox:default".to_string(), - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("/tmp/openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events: broadcast::channel(WATCH_BUFFER).0, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - - assert_eq!( - driver.bootstrap_image_ref().unwrap(), - "openshell/sandbox:default" - ); - } - - #[test] - fn bootstrap_image_ref_rejects_missing_trusted_image() { - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig::default(), - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("/tmp/openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events: broadcast::channel(WATCH_BUFFER).0, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - - let error = driver - .bootstrap_image_ref() - .expect_err("sandbox images must not become VM bootstrap images"); - assert_eq!(error.code(), Code::FailedPrecondition); - assert!(error.message().contains("sandbox image cannot be used")); - } - - #[tokio::test] - async fn vm_driver_startup_rejects_missing_trusted_bootstrap_image() { - let Err(error) = VmDriver::new(VmDriverConfig::default()).await else { - panic!("driver startup must reject an empty bootstrap configuration"); - }; - assert!(error.contains("sandbox image cannot be used")); - } - - #[test] - fn bootstrap_image_config_requires_a_trusted_image() { - let error = VmDriverConfig::default() - .validate_bootstrap_image_config() - .expect_err("an empty bootstrap configuration must fail closed"); - assert!(error.contains("sandbox image cannot be used")); - - VmDriverConfig { - default_image: "openshell/sandbox:default".to_string(), - ..Default::default() - } - .validate_bootstrap_image_config() - .expect("the operator-controlled default image is a valid fallback"); - - VmDriverConfig { - bootstrap_image: "openshell/sandbox-bootstrap:latest".to_string(), - ..Default::default() - } - .validate_bootstrap_image_config() - .expect("an explicit bootstrap image is valid"); - } - - #[test] - fn merged_environment_prefers_spec_values() { - let sandbox = Sandbox { - spec: Some(SandboxSpec { - environment: HashMap::from([("A".to_string(), "spec".to_string())]), - template: Some(SandboxTemplate { - environment: HashMap::from([ - ("A".to_string(), "template".to_string()), - ("B".to_string(), "template".to_string()), - ]), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let merged = merged_environment(&sandbox); - assert_eq!(merged.get("A"), Some(&"spec".to_string())); - assert_eq!(merged.get("B"), Some(&"template".to_string())); - } - - #[test] - fn build_guest_environment_sets_sandbox_boot_metadata() { - let config = VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - ..Default::default() - }; - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - name: "breezy-rhinoceros".to_string(), - spec: Some(SandboxSpec::default()), - ..Default::default() - }; - - let env = build_guest_environment(&sandbox, &config); - assert!(env.contains(&"HOME=/root".to_string())); - assert!(env.contains(&"OPENSHELL_SANDBOX_ID=sandbox-123".to_string())); - assert!(env.contains(&"OPENSHELL_SANDBOX=breezy-rhinoceros".to_string())); - assert!( - !env.iter() - .any(|entry| entry.starts_with("OPENSHELL_ENDPOINT=")) - ); - assert!( - !env.iter() - .any(|entry| entry.starts_with("OPENSHELL_SSH_SOCKET_PATH=")) - ); - } - - #[test] - fn new_vm_sandbox_identity_defaults_to_1000() { - let config = VmDriverConfig::default(); - assert_eq!(config.resolve_sandbox_uid(), 1000); - assert_eq!( - config.resolve_sandbox_gid(config.resolve_sandbox_uid()), - 1000 - ); - } - - #[test] - fn validate_sandbox_identity_accepts_non_root_system_ids() { - let config = VmDriverConfig { - sandbox_uid: Some(500), - sandbox_gid: Some(30), - ..Default::default() - }; - assert!(config.validate_sandbox_identity().is_ok()); - } - - #[test] - fn build_guest_environment_keeps_user_values_in_child_channel() { - let config = VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - ..Default::default() - }; - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - environment: HashMap::from([ - ("LD_PRELOAD".to_string(), "/workload/evil.so".to_string()), - ("BAD;touch /root/pwned".to_string(), "value".to_string()), - ]), - ..Default::default() - }), - ..Default::default() - }; - - let env = build_guest_environment(&sandbox, &config); - - assert!(!env.iter().any(|entry| entry.starts_with("LD_PRELOAD="))); - assert!(!env.iter().any(|entry| entry.starts_with("BAD;"))); - assert!( - !env.iter() - .any(|entry| { entry.starts_with(openshell_core::sandbox_env::USER_ENVIRONMENT) }) - ); - let child_env = merged_environment(&sandbox); - assert_eq!( - child_env.get("LD_PRELOAD"), - Some(&"/workload/evil.so".to_string()) - ); - assert_eq!( - child_env.get("BAD;touch /root/pwned"), - Some(&"value".to_string()) - ); - } - - #[test] - fn build_guest_environment_excludes_all_gateway_credentials() { - let config = VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - ..Default::default() - }; - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - sandbox_token: "secret.jwt.value".to_string(), - environment: HashMap::from([( - openshell_core::sandbox_env::SANDBOX_TOKEN.to_string(), - "user-provided-token".to_string(), - )]), - ..Default::default() - }), - ..Default::default() - }; - - let env = build_guest_environment(&sandbox, &config); - - assert!(!env.iter().any(|v| v.starts_with(&format!( - "{}=", - openshell_core::sandbox_env::SANDBOX_TOKEN - )))); - assert!(!env.iter().any(|v| v.starts_with(&format!( - "{}=", - openshell_core::sandbox_env::SANDBOX_TOKEN_FILE - )))); - } - - #[test] - fn build_guest_environment_strips_gateway_tls_server_name() { - let config = VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - ..Default::default() - }; - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - environment: HashMap::from([( - openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME.to_string(), - "evil.attacker.example.com".to_string(), - )]), - ..Default::default() - }), - ..Default::default() - }; - - let env = build_guest_environment(&sandbox, &config); - - assert!( - !env.iter().any(|v| v.starts_with(&format!( - "{}=", - openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME - ))), - "GATEWAY_TLS_SERVER_NAME must be stripped from the guest environment" - ); - } - - #[test] - fn build_guest_environment_uses_deployment_telemetry_toggle() { - let _guard = ENV_LOCK.lock().unwrap(); - temp_env::with_vars( - [( - openshell_core::sandbox_env::TELEMETRY_ENABLED, - Some("false"), - )], - || { - let config = VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - ..Default::default() - }; - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - environment: HashMap::from([( - openshell_core::sandbox_env::TELEMETRY_ENABLED.to_string(), - "true".to_string(), - )]), - ..Default::default() - }), - ..Default::default() - }; - - let env = build_guest_environment(&sandbox, &config); - let telemetry_entries = env - .iter() - .filter(|entry| { - entry.starts_with(&format!( - "{}=", - openshell_core::sandbox_env::TELEMETRY_ENABLED - )) - }) - .collect::>(); - - assert_eq!(telemetry_entries.len(), 1); - assert_eq!( - telemetry_entries[0], - &format!("{}=false", openshell_core::sandbox_env::TELEMETRY_ENABLED) - ); - }, - ); - } - - #[test] - fn image_reference_registry_host_defaults_to_docker_hub() { - assert_eq!(image_reference_registry_host("ubuntu:24.04"), "docker.io"); - assert_eq!( - image_reference_registry_host("library/ubuntu:24.04"), - "docker.io" - ); - assert_eq!( - image_reference_registry_host("ghcr.io/nvidia/openshell/base:latest"), - "ghcr.io" - ); - assert_eq!( - image_reference_registry_host("localhost/example:dev"), - "localhost" - ); - assert_eq!( - image_reference_registry_host("localhost:5000/example/sandbox:dev"), - "localhost:5000" - ); - } - - #[test] - fn openshell_local_build_image_ref_matches_cli_tags() { - assert!(is_openshell_local_build_image_ref( - "openshell/sandbox-from:123" - )); - assert!(!is_openshell_local_build_image_ref("ubuntu:24.04")); - assert!(!is_openshell_local_build_image_ref( - "ghcr.io/nvidia/openshell/base:latest" - )); - } - - #[test] - fn local_image_platform_mismatch_checks_guest_platform() { - assert!( - local_image_platform_mismatch( - "openshell/sandbox-from:123", - Some("linux"), - Some(linux_oci_arch()), - ) - .is_none() - ); - - let err = local_image_platform_mismatch( - "openshell/sandbox-from:123", - Some("linux"), - Some("wrong-arch"), - ) - .expect("architecture mismatch should be reported"); - assert!(err.contains("wrong-arch")); - assert!(err.contains(linux_oci_arch())); - - let err = local_image_platform_mismatch("openshell/sandbox-from:123", None, None) - .expect("unknown platform should be reported"); - assert!(err.contains("unknown/unknown")); - } - - fn apply_layer_dir_to_rootfs(layer: &Path, rootfs: &Path) -> Result<(), String> { - BootstrapExtractionBudget::new(DEFAULT_BOOTSTRAP_EXTRACTION_MAX_BYTES) - .apply_layer(layer, rootfs) - } - - #[test] - fn apply_layer_dir_to_rootfs_honors_whiteouts() { - let base = unique_temp_dir(); - let rootfs = base.join("rootfs"); - let layer = base.join("layer"); - - fs::create_dir_all(rootfs.join("dir")).unwrap(); - fs::write(rootfs.join("removed.txt"), "old").unwrap(); - fs::write(rootfs.join("dir/old.txt"), "old").unwrap(); - - fs::create_dir_all(layer.join("dir")).unwrap(); - fs::write(layer.join(".wh.removed.txt"), "").unwrap(); - fs::write(layer.join("dir/.wh..wh..opq"), "").unwrap(); - fs::write(layer.join("dir/new.txt"), "new").unwrap(); - - apply_layer_dir_to_rootfs(&layer, &rootfs).unwrap(); - - assert!(!rootfs.join("removed.txt").exists()); - assert!(!rootfs.join("dir/old.txt").exists()); - assert_eq!( - fs::read_to_string(rootfs.join("dir/new.txt")).unwrap(), - "new" - ); - - let _ = fs::remove_dir_all(base); - } - - #[test] - fn apply_layer_dir_to_rootfs_preserves_lower_symlink_dirs() { - let base = unique_temp_dir(); - let rootfs = base.join("rootfs"); - let layer = base.join("layer"); - - fs::create_dir_all(rootfs.join("usr/bin")).unwrap(); - fs::write(rootfs.join("usr/bin/bash"), "bash").unwrap(); - std::os::unix::fs::symlink("usr/bin", rootfs.join("bin")).unwrap(); - - fs::create_dir_all(layer.join("bin")).unwrap(); - fs::write(layer.join("bin/foo"), "foo").unwrap(); - - apply_layer_dir_to_rootfs(&layer, &rootfs).unwrap(); - - assert!( - fs::symlink_metadata(rootfs.join("bin")) - .unwrap() - .file_type() - .is_symlink(), - "lower /bin symlink should be preserved" - ); - assert_eq!( - fs::read_to_string(rootfs.join("usr/bin/bash")).unwrap(), - "bash" - ); - assert_eq!( - fs::read_to_string(rootfs.join("usr/bin/foo")).unwrap(), - "foo" - ); - - let _ = fs::remove_dir_all(base); - } - - #[cfg(unix)] - #[test] - fn apply_layer_dir_to_rootfs_does_not_write_through_escaping_symlink() { - let base = unique_temp_dir(); - let rootfs = base.join("rootfs"); - let layer = base.join("layer"); - let outside = base.join("outside"); - - fs::create_dir_all(&rootfs).unwrap(); - fs::create_dir_all(layer.join("escape")).unwrap(); - fs::create_dir_all(&outside).unwrap(); - fs::write(outside.join("sentinel"), "unchanged").unwrap(); - std::os::unix::fs::symlink(&outside, rootfs.join("escape")).unwrap(); - fs::write(layer.join("escape/payload"), "escaped").unwrap(); - - let error = apply_layer_dir_to_rootfs(&layer, &rootfs).err(); - - let sentinel = fs::read_to_string(outside.join("sentinel")).unwrap(); - let payload_escaped = outside.join("payload").exists(); - let _ = fs::remove_dir_all(base); - - let error = error.expect("escaping symlink should reject the layer"); - assert!( - error.contains("absolute symlink"), - "unexpected error: {error}" - ); - assert_eq!(sentinel, "unchanged"); - assert!( - !payload_escaped, - "upper-layer payload escaped the rootfs through a lower-layer symlink" - ); - } - - #[cfg(unix)] - #[test] - fn apply_layer_dir_to_rootfs_does_not_whiteout_through_escaping_symlink() { - let base = unique_temp_dir(); - let outside_entry = base.join("outside-entry"); - let outside_opaque = base.join("outside-opaque"); - fs::create_dir_all(&outside_entry).unwrap(); - fs::create_dir_all(&outside_opaque).unwrap(); - fs::write(outside_entry.join("victim"), "entry").unwrap(); - fs::write(outside_opaque.join("victim"), "opaque").unwrap(); - - let entry_rootfs = base.join("entry-rootfs"); - let entry_layer = base.join("entry-layer"); - fs::create_dir_all(&entry_rootfs).unwrap(); - fs::create_dir_all(entry_layer.join("escape")).unwrap(); - std::os::unix::fs::symlink(&outside_entry, entry_rootfs.join("escape")).unwrap(); - fs::write(entry_layer.join("escape/.wh.victim"), "").unwrap(); - let entry_error = apply_layer_dir_to_rootfs(&entry_layer, &entry_rootfs).err(); - - let opaque_rootfs = base.join("opaque-rootfs"); - let opaque_layer = base.join("opaque-layer"); - fs::create_dir_all(&opaque_rootfs).unwrap(); - fs::create_dir_all(opaque_layer.join("escape")).unwrap(); - std::os::unix::fs::symlink(&outside_opaque, opaque_rootfs.join("escape")).unwrap(); - fs::write(opaque_layer.join("escape/.wh..wh..opq"), "").unwrap(); - let opaque_error = apply_layer_dir_to_rootfs(&opaque_layer, &opaque_rootfs).err(); - - let entry_remained = outside_entry.join("victim").exists(); - let opaque_remained = outside_opaque.join("victim").exists(); - let _ = fs::remove_dir_all(base); - - let entry_error = - entry_error.expect("escaping symlink should reject an individual whiteout layer"); - let opaque_error = - opaque_error.expect("escaping symlink should reject an opaque whiteout layer"); - assert!( - entry_error.contains("absolute symlink"), - "unexpected error: {entry_error}" - ); - assert!( - opaque_error.contains("absolute symlink"), - "unexpected error: {opaque_error}" - ); - assert!(entry_remained, "individual whiteout escaped the rootfs"); - assert!(opaque_remained, "opaque whiteout escaped the rootfs"); - } - - #[cfg(unix)] - #[test] - fn apply_layer_dir_to_rootfs_rejects_relative_symlink_escape() { - let base = unique_temp_dir(); - let rootfs = base.join("rootfs"); - let layer = base.join("layer"); - let outside = base.join("outside"); - - fs::create_dir_all(&rootfs).unwrap(); - fs::create_dir_all(layer.join("escape")).unwrap(); - fs::create_dir_all(&outside).unwrap(); - std::os::unix::fs::symlink("../outside", rootfs.join("escape")).unwrap(); - fs::write(layer.join("escape/payload"), "escaped").unwrap(); - - let error = apply_layer_dir_to_rootfs(&layer, &rootfs).err(); - let payload_escaped = outside.join("payload").exists(); - let _ = fs::remove_dir_all(base); - - let error = error.expect("escaping symlink should reject the layer"); - assert!( - error.contains("escapes rootfs"), - "unexpected error: {error}" - ); - assert!(!payload_escaped, "relative symlink escaped the rootfs"); - } - - #[cfg(unix)] - #[test] - fn apply_layer_dir_to_rootfs_rejects_directory_symlink_cycles() { - let base = unique_temp_dir(); - let rootfs = base.join("rootfs"); - let layer = base.join("layer"); - fs::create_dir_all(&rootfs).unwrap(); - fs::create_dir_all(layer.join("a")).unwrap(); - fs::write(layer.join("a/payload"), "payload").unwrap(); - std::os::unix::fs::symlink("b", rootfs.join("a")).unwrap(); - std::os::unix::fs::symlink("a", rootfs.join("b")).unwrap(); - - let error = apply_layer_dir_to_rootfs(&layer, &rootfs) - .expect_err("directory symlink cycle must reject the layer"); - - assert!( - error.contains("too many symlinks"), - "unexpected error: {error}" - ); - let _ = fs::remove_dir_all(base); - } - - #[cfg(unix)] - #[test] - fn extracted_layers_do_not_write_through_escaping_symlink() { - let base = unique_temp_dir(); - let rootfs = base.join("rootfs"); - let lower = base.join("lower"); - let upper = base.join("upper"); - // GNU tar's legacy symlink field is limited to 100 bytes, while the - // macOS temporary directory path is already close to that limit. - let outside = Path::new("/tmp").join(format!( - "openshell-vm-layer-test-{}-{:x}", - std::process::id(), - u64::from_ne_bytes(openshell_crypto::random_bytes::<8>().expect("test entropy")) - )); - fs::create_dir_all(&outside).unwrap(); - fs::write(outside.join("sentinel"), "unchanged").unwrap(); - - let mut lower_tar = tar::Builder::new(Vec::new()); - append_test_tar_symlink(&mut lower_tar, "escape", &outside); - let lower_tar = lower_tar.into_inner().expect("finish lower tar"); - BootstrapExtractionBudget::new(DEFAULT_BOOTSTRAP_EXTRACTION_MAX_BYTES) - .unpack_tar(std::io::Cursor::new(lower_tar), &lower) - .unwrap(); - - let upper_tar = tar_bytes_with_file("escape/payload", b"escaped"); - BootstrapExtractionBudget::new(DEFAULT_BOOTSTRAP_EXTRACTION_MAX_BYTES) - .unpack_tar(std::io::Cursor::new(upper_tar), &upper) - .unwrap(); - - apply_layer_dir_to_rootfs(&lower, &rootfs).unwrap(); - let error = apply_layer_dir_to_rootfs(&upper, &rootfs) - .expect_err("upper layer must not traverse the lower absolute symlink"); - - assert!( - error.contains("absolute symlink"), - "unexpected error: {error}" - ); - assert_eq!( - fs::read_to_string(outside.join("sentinel")).unwrap(), - "unchanged" - ); - assert!(!outside.join("payload").exists()); - - let _ = fs::remove_dir_all(base); - let _ = fs::remove_dir_all(outside); - } - - #[cfg(unix)] - #[test] - fn extracted_layer_implicit_parent_preserves_lower_directory_symlink() { - let base = unique_temp_dir(); - let rootfs = base.join("rootfs"); - let lower = base.join("lower"); - let upper = base.join("upper"); - - let mut lower_tar = tar::Builder::new(Vec::new()); - append_test_tar_file(&mut lower_tar, "usr/bin/bash", b"bash"); - append_test_tar_symlink(&mut lower_tar, "bin", Path::new("usr/bin")); - let lower_tar = lower_tar.into_inner().expect("finish lower tar"); - BootstrapExtractionBudget::new(DEFAULT_BOOTSTRAP_EXTRACTION_MAX_BYTES) - .unpack_tar(std::io::Cursor::new(lower_tar), &lower) - .unwrap(); - - // The tar contains no explicit `bin/` entry. Extraction necessarily - // materializes it as an implicit parent for `bin/tool`. - let upper_tar = tar_bytes_with_file("bin/tool", b"tool"); - BootstrapExtractionBudget::new(DEFAULT_BOOTSTRAP_EXTRACTION_MAX_BYTES) - .unpack_tar(std::io::Cursor::new(upper_tar), &upper) - .unwrap(); - - apply_layer_dir_to_rootfs(&lower, &rootfs).unwrap(); - apply_layer_dir_to_rootfs(&upper, &rootfs).unwrap(); - - assert!( - fs::symlink_metadata(rootfs.join("bin")) - .unwrap() - .file_type() - .is_symlink(), - "implicit upper parent must not replace the lower /bin symlink" - ); - assert_eq!( - fs::read_to_string(rootfs.join("usr/bin/tool")).unwrap(), - "tool" - ); - - let _ = fs::remove_dir_all(base); - } - - #[test] - fn bootstrap_extraction_bounds_decoded_tar_through_eof_for_each_compression() { - let mut tar = tar_bytes_with_file("tool", b"contents"); - tar.resize(8192, 0); - let tail = b"after the tar end marker"; - let decoded_bytes = (tar.len() + tail.len()) as u64; - let gzip = [gzip_bytes(&tar), gzip_bytes(tail)].concat(); - let zstd = [ - zstd::encode_all(&tar[..], 0).unwrap(), - zstd::encode_all(&tail[..], 0).unwrap(), - ] - .concat(); - for (media, bytes) in [ - ( - "application/vnd.oci.image.layer.v1.tar", - [&tar[..], tail].concat(), - ), - ("application/vnd.oci.image.layer.v1.tar+gzip", gzip), - ("application/vnd.oci.image.layer.v1.tar+zstd", zstd), - ] { - let temp = tempfile::tempdir().unwrap(); - let blob = temp.path().join("blob"); - fs::write(&blob, bytes).unwrap(); - for limit in [decoded_bytes + 1, decoded_bytes, decoded_bytes - 1] { - let dest = temp.path().join(limit.to_string()); - let result = extract_layer_blob_to_dir( - &blob, - media, - &dest, - &mut BootstrapExtractionBudget::new(limit), - ); - if limit < decoded_bytes { - assert!(result.unwrap_err().contains("decoded layer tars")); - } else { - result.unwrap(); - assert_eq!(fs::read(dest.join("tool")).unwrap(), b"contents"); - } - } - } - } - - #[test] - fn bootstrap_extraction_counts_decoded_tar_across_layers() { - let mut tar = tar_bytes_with_file("tool", b"small"); - tar.resize(8192, 0); - let temp = tempfile::tempdir().unwrap(); - let mut budget = BootstrapExtractionBudget::new(2 * tar.len() as u64 - 1); - budget - .unpack_tar(tar.as_slice(), &temp.path().join("lower")) - .unwrap(); - let error = budget - .unpack_tar(tar.as_slice(), &temp.path().join("upper")) - .unwrap_err(); - assert!(error.to_string().contains("decoded layer tars"), "{error}"); - } - - #[test] - fn bootstrap_extraction_global_pax_header_only_spends_decoded_bytes() { - let mut builder = tar::Builder::new(Vec::new()); - let mut header = tar::Header::new_ustar(); - let comment = b"13 comment=x\n"; - header.set_entry_type(tar::EntryType::XGlobalHeader); - header.set_mode(0o644); - header.set_size(comment.len() as u64); - builder - .append_data(&mut header, "pax", &comment[..]) - .unwrap(); - append_test_tar_file(&mut builder, "payload", &[1; 8192]); - let tar = builder.into_inner().unwrap(); - let temp = tempfile::tempdir().unwrap(); - let stage = temp.path().join("layer"); - let root = temp.path().join("root"); - let mut budget = BootstrapExtractionBudget::new(2 * 8192); - budget.unpack_tar(&tar[..], &stage).unwrap(); - budget.apply_layer(&stage, &root).unwrap(); - assert_eq!(fs::read(root.join("payload")).unwrap(), [1; 8192]); - assert!(!root.join("pax").exists()); - } - - #[test] - fn bootstrap_extraction_bounds_path_entries_before_creating_parents() { - let tar = tar_bytes_with_file("a/b/c/empty", b""); - let temp = tempfile::tempdir().unwrap(); - let stage = temp.path().join("layer"); - let root = temp.path().join("root"); - let mut too_small = BootstrapExtractionBudget::new(4 * 4096 - 1); - let err = too_small.unpack_tar(&tar[..], &stage).unwrap_err(); - assert!(err.to_string().contains("filesystem output"), "{err}"); - assert!(!stage.join("a").exists()); - - let mut budget = BootstrapExtractionBudget::new(8 * 4096); - budget.unpack_tar(&tar[..], &stage).unwrap(); - budget.apply_layer(&stage, &root).unwrap(); - assert!(root.join("a/b/c/empty").is_file()); - } - - #[test] - fn bootstrap_extraction_checks_sparse_logical_size_before_creating_file() { - for logical_size in [1024 * 1024, u64::MAX] { - let mut builder = tar::Builder::new(Vec::new()); - let mut header = tar::Header::new_gnu(); - header.set_entry_type(tar::EntryType::GNUSparse); - header.set_size(1); - header.set_mode(0o644); - let gnu = header.as_gnu_mut().unwrap(); - gnu.set_real_size(logical_size); - gnu.sparse[0].set_offset(logical_size - 1); - gnu.sparse[0].set_length(1); - builder - .append_data(&mut header, "sparse", &b"x"[..]) - .unwrap(); - let tar = builder.into_inner().unwrap(); - let temp = tempfile::tempdir().unwrap(); - let dest = temp.path(); - let error = BootstrapExtractionBudget::new(1024 * 1024 - 1) - .unpack_tar(&tar[..], dest) - .unwrap_err(); - assert!(error.to_string().contains("filesystem output"), "{error}"); - assert!(!dest.join("sparse").exists()); - if logical_size == 1024 * 1024 { - BootstrapExtractionBudget::new(logical_size) - .unpack_tar(&tar[..], dest) - .unwrap(); - assert_eq!( - fs::metadata(dest.join("sparse")).unwrap().len(), - logical_size - ); - } - } - } - - #[test] - fn bootstrap_extraction_checks_pax_size_before_creating_file() { - let mut builder = tar::Builder::new(Vec::new()); - builder - .append_pax_extensions([("size", &b"8192"[..])]) - .unwrap(); - let mut header = tar::Header::new_gnu(); - header.set_size(1); - header.set_mode(0o644); - builder - .append_data(&mut header, "file", &[7; 8192][..]) - .unwrap(); - let tar = builder.into_inner().unwrap(); - let temp = tempfile::tempdir().unwrap(); - let error = BootstrapExtractionBudget::new(8191) - .unpack_tar(tar.as_slice(), temp.path()) - .unwrap_err(); - assert!(error.to_string().contains("filesystem output"), "{error}"); - assert!(!temp.path().join("file").exists()); - } - - #[test] - fn bootstrap_extraction_reserves_each_hard_link_copy_before_replacement() { - let mut builder = tar::Builder::new(Vec::new()); - append_test_tar_file(&mut builder, "a", &[3; 4096]); - for name in ["b", "c"] { - let mut header = tar::Header::new_gnu(); - header.set_entry_type(tar::EntryType::Link); - header.set_size(0); - builder.append_link(&mut header, name, "a").unwrap(); - } - let tar = builder.into_inner().unwrap(); - let temp = tempfile::tempdir().unwrap(); - let staged = temp.path().join("layer"); - let root = temp.path().join("root"); - fs::create_dir(&root).unwrap(); - fs::write(root.join("c"), b"old").unwrap(); - // Three staged entries and three merged copies each consume one block. - let mut budget = BootstrapExtractionBudget::new(6 * 4096 - 1); - budget.unpack_tar(&tar[..], &staged).unwrap(); - let error = budget.apply_layer(&staged, &root).unwrap_err(); - assert!(error.contains("filesystem output"), "{error}"); - assert_eq!(fs::read(root.join("b")).unwrap(), [3; 4096]); - assert_eq!(fs::read(root.join("c")).unwrap(), b"old"); - } - - #[test] - fn extracts_zstd_compressed_oci_layer() { - let temp = tempfile::tempdir().unwrap(); - let archive = tar_bytes_with_file("bin/tool", b"tool contents"); - let compressed = zstd::encode_all(archive.as_slice(), 0).unwrap(); - let blob = temp.path().join("layer.tar.zst"); - let extracted = temp.path().join("extracted"); - fs::write(&blob, compressed).unwrap(); - - extract_layer_blob_to_dir( - &blob, - "application/vnd.oci.image.layer.v1.tar+zstd", - &extracted, - &mut BootstrapExtractionBudget::new(DEFAULT_BOOTSTRAP_EXTRACTION_MAX_BYTES), - ) - .unwrap(); - - assert_eq!( - fs::read(extracted.join("bin/tool")).unwrap(), - b"tool contents" - ); - } - - #[test] - fn layer_compression_from_media_type_supports_common_formats() { - assert_eq!( - layer_compression_from_media_type("application/vnd.oci.image.layer.v1.tar").unwrap(), - LayerCompression::None - ); - assert_eq!( - layer_compression_from_media_type("application/vnd.oci.image.layer.v1.tar+gzip") - .unwrap(), - LayerCompression::Gzip - ); - assert_eq!( - layer_compression_from_media_type("application/vnd.oci.image.layer.v1.tar+zstd") - .unwrap(), - LayerCompression::Zstd - ); - } - - #[test] - fn build_guest_environment_keeps_tls_paths_host_side() { - let config = VmDriverConfig { - grpc_endpoint: "https://127.0.0.1:8443".to_string(), - guest_tls_ca: Some(PathBuf::from("/host/ca.crt")), - ..Default::default() - }; - let sandbox = Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - spec: Some(SandboxSpec::default()), - ..Default::default() - }; - - let env = build_guest_environment(&sandbox, &config); - assert!(!env.iter().any(|entry| entry.starts_with("OPENSHELL_TLS_"))); - } - - #[test] - fn vm_driver_config_requires_tls_materials_for_https_endpoint() { - let config = VmDriverConfig { - grpc_endpoint: "https://127.0.0.1:8443".to_string(), - ..Default::default() - }; - let err = config - .tls_paths() - .expect_err("https endpoint should require TLS materials"); - assert!(err.contains("OPENSHELL_VM_TLS_CA")); - } - - #[tokio::test] - async fn delete_sandbox_keeps_registry_entry_when_cleanup_fails() { - let base = unique_temp_dir(); - let driver_state = base.join("driver-state"); - let (events, _) = broadcast::channel(WATCH_BUFFER); - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig { - state_dir: driver_state.clone(), - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - - let state_file = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); - std::fs::create_dir_all(state_file.parent().unwrap()).unwrap(); - std::fs::write(&state_file, "not a directory").unwrap(); - - insert_test_record( - &driver, - "sandbox-123", - state_file.clone(), - spawn_exited_child(), - ) - .await; - - let err = driver - .delete_sandbox("sandbox-123", "sandbox-123") - .await - .expect_err("state dir cleanup should fail for a file path"); - assert!(err.message().contains("not a directory")); - assert!(driver.registry.lock().await.contains_key("sandbox-123")); - - std::fs::remove_file(&state_file).unwrap(); - let retry_state_dir = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); - std::fs::create_dir_all(&retry_state_dir).unwrap(); - { - let mut registry = driver.registry.lock().await; - let record = registry.get_mut("sandbox-123").unwrap(); - record.state_dir = retry_state_dir; - record.process = Some(Arc::new(Mutex::new(VmProcess { - child: spawn_exited_child(), - supervisor: spawn_exited_child(), - supervisor_liveness: None, - deleting: false, - }))); - } - - let response = driver - .delete_sandbox("sandbox-123", "sandbox-123") - .await - .expect("delete retry should succeed once cleanup works"); - assert!(response.deleted); - assert!(!driver.registry.lock().await.contains_key("sandbox-123")); - - let _ = std::fs::remove_dir_all(base); - } - - #[tokio::test] - async fn delete_sandbox_cleans_provisioning_record_without_process() { - let base = unique_temp_dir(); - let driver_state = base.join("driver-state"); - let (events, _) = broadcast::channel(WATCH_BUFFER); - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig { - state_dir: driver_state.clone(), - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - - let state_dir = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); - std::fs::create_dir_all(&state_dir).unwrap(); - { - let mut registry = driver.registry.lock().await; - registry.insert( - "sandbox-123".to_string(), - SandboxRecord { - snapshot: Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - ..Default::default() - }, - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - } - - let response = driver - .delete_sandbox("sandbox-123", "sandbox-123") - .await - .expect("delete should handle accepted-but-not-started sandboxes"); - assert!(response.deleted); - assert!(!driver.registry.lock().await.contains_key("sandbox-123")); - assert!(!state_dir.exists()); - - let _ = std::fs::remove_dir_all(base); - } - - #[tokio::test] - async fn duplicate_create_keeps_existing_state_dir() { - let base = unique_temp_dir(); - let driver_state = base.join("driver-state"); - let (events, _) = broadcast::channel(WATCH_BUFFER); - let (socket_root, socket_root_fd) = test_socket_root(); - let driver = VmDriver { - config: VmDriverConfig { - state_dir: driver_state.clone(), - default_image: "ghcr.io/example/sandbox:latest".to_string(), - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - }; - - let state_dir = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); - std::fs::create_dir_all(&state_dir).unwrap(); - std::fs::write(state_dir.join("overlay.ext4"), b"live overlay").unwrap(); - { - let mut registry = driver.registry.lock().await; - registry.insert( - "sandbox-123".to_string(), - SandboxRecord { - snapshot: Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - ..Default::default() - }, - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - } - - let err = driver - .create_sandbox(&Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - spec: Some(SandboxSpec { - launch_authentication: test_launch_authentication("duplicate").0, - ..Default::default() - }), - ..Default::default() - }) - .await - .expect_err("duplicate create should fail"); - - assert_eq!(err.code(), Code::AlreadyExists); - assert!(state_dir.join("overlay.ext4").exists()); - assert!(driver.registry.lock().await.contains_key("sandbox-123")); - - let _ = std::fs::remove_dir_all(base); - } - - #[tokio::test] - async fn remove_sandbox_state_dir_rejects_paths_outside_state_root() { - let base = unique_temp_dir(); - let state_root = base.join("driver-state"); - let outside = base.join("outside"); - std::fs::create_dir_all(&outside).unwrap(); - - let err = remove_sandbox_state_dir(&state_root, &outside) - .await - .expect_err("outside state paths should be rejected"); - assert!(err.message().contains("outside vm state root")); - - let _ = std::fs::remove_dir_all(base); - } - - #[cfg(unix)] - #[tokio::test] - async fn remove_sandbox_state_dir_rejects_symlinked_state_dir() { - let base = unique_temp_dir(); - let state_root = base.join("driver-state"); - let target = base.join("target"); - let state_dir = sandbox_state_dir(&state_root, "sandbox-123").unwrap(); - std::fs::create_dir_all(&target).unwrap(); - std::fs::create_dir_all(state_dir.parent().unwrap()).unwrap(); - std::os::unix::fs::symlink(&target, &state_dir).unwrap(); - - let err = remove_sandbox_state_dir(&state_root, &state_dir) - .await - .expect_err("symlinked state dir should be rejected"); - assert!(err.message().contains("symlinked sandbox state dir")); - - let _ = std::fs::remove_dir_all(base); - } - - #[test] - fn validate_openshell_endpoint_accepts_loopback_hosts() { - validate_openshell_endpoint("http://127.0.0.1:8080") - .expect("ipv4 loopback should be allowed for TSI"); - validate_openshell_endpoint("http://localhost:8080") - .expect("localhost should be allowed for TSI"); - validate_openshell_endpoint("http://[::1]:8080") - .expect("ipv6 loopback should be allowed for TSI"); - } - - #[test] - fn validate_openshell_endpoint_rejects_unspecified_hosts() { - let err = validate_openshell_endpoint("http://0.0.0.0:8080") - .expect_err("unspecified endpoint should fail"); - assert!(err.contains("not reachable from sandbox VMs")); - } - - #[test] - fn validate_openshell_endpoint_accepts_host_gateway() { - validate_openshell_endpoint("http://host.containers.internal:8080") - .expect("guest-reachable host alias should be accepted"); - validate_openshell_endpoint("http://192.168.127.1:8080") - .expect("gateway IP should be accepted"); - validate_openshell_endpoint(&format!("http://{OPENSHELL_HOST_GATEWAY_ALIAS}:8080")) - .expect("openshell host alias should be accepted"); - validate_openshell_endpoint("https://gateway.internal:8443") - .expect("dns endpoint should be accepted"); - } - - #[test] - fn host_control_endpoint_rewrites_guest_host_aliases() { - for host in HOST_LOOPBACK_ALIASES { - assert_eq!( - host_control_openshell_endpoint(&format!("https://{host}:8443/control")) - .expect("guest alias should be rewritten"), - ( - "https://127.0.0.1:8443/control".to_string(), - Some((*host).to_string()), - ), - "host alias {host}" - ); - } - } - - #[test] - fn host_control_endpoint_preserves_remote_gateway() { - assert_eq!( - host_control_openshell_endpoint("https://gateway.internal:8443") - .expect("remote gateway should be preserved"), - ("https://gateway.internal:8443".to_string(), None) - ); - } - - #[test] - fn relative_state_dir_is_resolved_from_the_working_directory() { - let working_dir = std::env::current_dir().expect("working directory"); - assert_eq!( - absolute_state_dir(Path::new("target/driver-state")).expect("resolve state dir"), - working_dir.join("target/driver-state") - ); - - let absolute = working_dir.join("existing-absolute-state"); - assert_eq!( - absolute_state_dir(&absolute).expect("preserve absolute state dir"), - absolute - ); - } - - #[test] - fn supervisor_otlp_environment_carries_only_configured_signals() { - use openshell_core::sandbox_env::{ - GATEWAY_NAME, OTLP_AGENT_ENDPOINT, OTLP_AGENT_PROTOCOL, OTLP_ENDPOINT, - OTLP_OCSF_ENDPOINT, OTLP_OCSF_PROTOCOL, OTLP_PROTOCOL, OtlpExport, OtlpProtocol, - }; - let export = |endpoint: &str, protocol| { - Some(OtlpExport { - endpoint: endpoint.to_string(), - protocol, - }) - }; - - let mut config = VmDriverConfig::default(); - assert!(supervisor_otlp_environment(&config).is_empty()); - - config.supervisor_otlp.traces = export("http://127.0.0.1:4317", OtlpProtocol::Grpc); - let environment = supervisor_otlp_environment(&config); - assert_eq!( - environment[0], - (OTLP_ENDPOINT, "http://127.0.0.1:4317".to_string()) - ); - assert!(environment.iter().all(|(name, _)| *name != OTLP_PROTOCOL)); - - config.supervisor_otlp.traces = export("http://127.0.0.1:4318", OtlpProtocol::HttpProtobuf); - assert_eq!( - supervisor_otlp_environment(&config)[1], - (OTLP_PROTOCOL, "http/protobuf".to_string()) - ); - - config.supervisor_otlp.traces = None; - config.supervisor_otlp.ocsf = export("http://siem:4317", OtlpProtocol::Grpc); - assert_eq!( - supervisor_otlp_environment(&config), - [(OTLP_OCSF_ENDPOINT, "http://siem:4317".to_string()),] - ); - - config.supervisor_otlp.ocsf = export("http://siem:4318", OtlpProtocol::HttpProtobuf); - assert_eq!( - supervisor_otlp_environment(&config), - [ - (OTLP_OCSF_ENDPOINT, "http://siem:4318".to_string()), - (OTLP_OCSF_PROTOCOL, "http/protobuf".to_string()), - ] - ); - - config.supervisor_otlp.ocsf = None; - config.supervisor_otlp.agent = export("http://agents:4317", OtlpProtocol::Grpc); - assert_eq!( - supervisor_otlp_environment(&config), - [(OTLP_AGENT_ENDPOINT, "http://agents:4317".to_string())] - ); - - config.supervisor_otlp.agent = export("http://agents:4318", OtlpProtocol::HttpProtobuf); - assert_eq!( - supervisor_otlp_environment(&config), - [ - (OTLP_AGENT_ENDPOINT, "http://agents:4318".to_string()), - (OTLP_AGENT_PROTOCOL, "http/protobuf".to_string()), - ] - ); - - config.supervisor_gateway_name = Some("prod-west".to_string()); - assert_eq!( - supervisor_otlp_environment(&config).last(), - Some(&(GATEWAY_NAME, "prod-west".to_string())) - ); - } - - #[test] - fn host_control_environment_contains_only_explicit_values() { - let mut command = Command::new("openshell-sandbox"); - command.env("UNTRUSTED_PARENT_VALUE", "must-not-leak"); - isolate_host_control_environment(&mut command); - command.env("DRIVER_OWNED_VALUE", "kept"); - - let environment = command.as_std().get_envs().collect::>(); - assert_eq!(environment.len(), 1); - assert_eq!(environment[0].0, "DRIVER_OWNED_VALUE"); - assert_eq!( - environment[0].1.and_then(std::ffi::OsStr::to_str), - Some("kept") - ); - } - - #[test] - fn prepared_image_cache_identity_includes_rootfs_layout_and_openshell_version() { - let image = "sha256:local-image"; - let image_hash = compute_bytes_sha256_hex(image.as_bytes()); - let image_account = prepared_image_cache_identity(image, &VmDriverConfig::default()); - assert_eq!( - image_account, - format!( - "sandbox-prepared-rootfs-ext4-umoci-v4:openshell-{}:image-account:{image_hash}", - openshell_core::VERSION - ) - ); - - let identities = [ - VmDriverConfig { - sandbox_uid: Some(1000), - sandbox_gid: Some(1000), - ..Default::default() - }, - VmDriverConfig { - sandbox_uid: Some(2000), - sandbox_gid: Some(3000), - ..Default::default() - }, - VmDriverConfig { - sandbox_uid: Some(2000), - ..Default::default() - }, - VmDriverConfig { - sandbox_gid: Some(3000), - ..Default::default() - }, - ] - .map(|config| prepared_image_cache_identity(image, &config)); - - assert!(identities.iter().all(|identity| identity != &image_account)); - for (index, identity) in identities.iter().enumerate() { - assert!( - identities[index + 1..] - .iter() - .all(|other| other != identity), - "owner contracts must use distinct cache keys" - ); - } - } - - #[test] - fn bootstrap_image_cache_identity_includes_rootfs_layout_version_and_guest_runtime() { - let identity = bootstrap_image_cache_identity("sha256:bootstrap-image"); - assert!(identity.starts_with(&format!( - "sandbox-bootstrap-rootfs-ext4-v6:openshell-{}:guest-", - openshell_core::VERSION - ))); - assert!(identity.ends_with(&compute_bytes_sha256_hex(b"sha256:bootstrap-image"))); - assert!(identity.contains(&sandbox_guest_runtime_identity())); - } - - #[test] - fn stage_guest_image_payload_copies_registry_oci_layout() { - let base = unique_temp_dir(); - let staging_dir = base.join("staging"); - let layout_dir = base.join("layout"); - let blob_dir = layout_dir.join("blobs").join("sha256"); - fs::create_dir_all(&blob_dir).unwrap(); - fs::write( - layout_dir.join("oci-layout"), - r#"{"imageLayoutVersion":"1.0.0"}"#, - ) - .unwrap(); - fs::write(layout_dir.join("index.json"), "{}").unwrap(); - fs::write(blob_dir.join("abc"), "blob").unwrap(); - - stage_guest_image_payload( - &staging_dir, - &GuestImagePayload { - image_ref: "ghcr.io/example/app:latest".to_string(), - image_identity: prepared_image_cache_identity( - "sha256:abc", - &VmDriverConfig::default(), - ), - source: GuestImagePayloadSource::RegistryOciLayout { layout_dir }, - }, - ) - .unwrap(); - - let image_dir = staging_dir.join("config").join(GUEST_IMAGE_CONFIG_DIR); - assert_eq!( - fs::read_to_string(image_dir.join("source")).unwrap(), - "oci-layout" - ); - assert_eq!( - fs::read_to_string(image_dir.join("ref")).unwrap(), - "ghcr.io/example/app:latest" - ); - assert_eq!( - fs::read_to_string( - image_dir - .join(GUEST_IMAGE_OCI_LAYOUT_DIR) - .join("blobs") - .join("sha256") - .join("abc") - ) - .unwrap(), - "blob" - ); - - let _ = std::fs::remove_dir_all(base); - } - - #[test] - fn registry_layer_download_concurrency_is_bounded() { - assert_eq!( - registry_layer_download_concurrency_value(None), - DEFAULT_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY - ); - assert_eq!( - registry_layer_download_concurrency_value(Some("0")), - DEFAULT_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY - ); - assert_eq!(registry_layer_download_concurrency_value(Some("8")), 8); - assert_eq!( - registry_layer_download_concurrency_value(Some("999")), - MAX_REGISTRY_LAYER_DOWNLOAD_CONCURRENCY - ); - } - - #[tokio::test] - async fn remove_registry_layer_staging_preserves_merged_rootfs() { - let base = unique_temp_dir(); - let layers_dir = base.join("layers"); - let rootfs_dir = base.join("rootfs"); - fs::create_dir_all(&layers_dir).unwrap(); - fs::create_dir_all(&rootfs_dir).unwrap(); - fs::write(layers_dir.join("layer.blob"), b"compressed layer").unwrap(); - fs::write(rootfs_dir.join("merged.txt"), b"merged rootfs").unwrap(); - - remove_registry_layer_staging(&base) - .await - .expect("remove layer staging"); - - assert!(!layers_dir.exists()); - assert_eq!( - fs::read(rootfs_dir.join("merged.txt")).unwrap(), - b"merged rootfs" - ); - - let _ = fs::remove_dir_all(base); - } - - #[test] - fn sanitize_image_identity_rewrites_path_separators() { - assert_eq!( - sanitize_image_identity("sha256:abc/def@ghi"), - "sha256-abc-def-ghi" - ); - } - - #[test] - fn vsock_cid_monotonically_increases() { - let cid1 = allocate_vsock_cid(); - let cid2 = allocate_vsock_cid(); - assert!(cid2 > cid1); - } - - fn unique_temp_dir() -> PathBuf { - static COUNTER: AtomicU64 = AtomicU64::new(0); - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let suffix = COUNTER.fetch_add(1, Ordering::Relaxed); - std::env::temp_dir().join(format!( - "openshell-vm-driver-test-{}-{nanos}-{suffix}", - std::process::id() - )) - } - - fn spawn_exited_child() -> Child { - Command::new("sh") - .arg("-c") - .arg("exit 0") - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn() - .unwrap() - } - - /// Delay SIGTERM handling so premature liveness EOF wins the race. - #[tokio::test] - async fn stop_signals_supervisor_before_closing_its_liveness_pipe() { - let dir = unique_temp_dir(); - fs::create_dir_all(&dir).unwrap(); - let driver_log = dir.join("driver.log"); - let subscriber = tracing_subscriber::fmt() - .with_max_level(tracing::Level::WARN) - .without_time() - .with_ansi(false) - .with_writer(Arc::new(fs::File::create(&driver_log).unwrap())) - .finish(); - let _tracing = tracing::subscriber::set_default(subscriber); - let events = dir.join("events"); - let (read_end, write_end) = nix::unistd::pipe().unwrap(); - for fd in [&read_end, &write_end] { - nix::fcntl::fcntl( - fd.as_raw_fd(), - nix::fcntl::FcntlArg::F_SETFD(nix::fcntl::FdFlag::FD_CLOEXEC), - ) - .unwrap(); - } - let read_fd = read_end.as_raw_fd(); - let mut command = Command::new("sh"); - command - .arg("-c") - .arg( - r#"events=$1 -(cat <&3 >/dev/null; echo eof >>"$events") & -trap 'sleep 0.2; echo term >>"$events"; exit 143' TERM -echo ready >>"$events" -while :; do sleep 0.05; done"#, - ) - .arg("supervisor") - .arg(&events) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()); - // SAFETY: only async-signal-safe `dup2` runs between fork and exec. - unsafe { - command.pre_exec(move || { - if libc::dup2(read_fd, 3) < 0 { - return Err(std::io::Error::last_os_error()); - } - Ok(()) - }); - } - let supervisor = command.spawn().unwrap(); - drop(read_end); - - let ready = async { - while !fs::read_to_string(&events).is_ok_and(|log| log.contains("ready")) { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }; - tokio::time::timeout(Duration::from_secs(5), ready) - .await - .expect("stand-in supervisor installs its SIGTERM handler"); - - let mut process = VmProcess { - child: spawn_exited_child(), - supervisor, - supervisor_liveness: Some(fs::File::from(write_end)), - deleting: false, - }; - terminate_sandbox_processes(&mut process).await.unwrap(); - - let log = fs::read_to_string(&events).unwrap(); - let first_event = log.lines().find(|line| *line != "ready"); - assert_eq!( - first_event, - Some("term"), - "SIGTERM must reach the supervisor before its liveness pipe closes; events: {log:?}" - ); - assert!( - fs::read_to_string(&driver_log).unwrap().is_empty(), - "an orderly supervisor shutdown must not warn about lost writes" - ); - fs::remove_dir_all(&dir).ok(); - } - - /// A supervisor that ignores SIGTERM is killed once its grace expires, and - /// only then is its liveness pipe closed. - #[tokio::test] - async fn stop_kills_a_supervisor_that_ignores_sigterm_after_the_grace() { - let dir = unique_temp_dir(); - fs::create_dir_all(&dir).unwrap(); - let driver_log = dir.join("driver.log"); - let subscriber = tracing_subscriber::fmt() - .with_max_level(tracing::Level::WARN) - .without_time() - .with_ansi(false) - .with_writer(Arc::new(fs::File::create(&driver_log).unwrap())) - .finish(); - let _tracing = tracing::subscriber::set_default(subscriber); - let events = dir.join("events"); - let (read_end, write_end) = nix::unistd::pipe().unwrap(); - for fd in [&read_end, &write_end] { - nix::fcntl::fcntl( - fd.as_raw_fd(), - nix::fcntl::FcntlArg::F_SETFD(nix::fcntl::FdFlag::FD_CLOEXEC), - ) - .unwrap(); - } - let read_fd = read_end.as_raw_fd(); - let mut command = Command::new("sh"); - command - .arg("-c") - .arg( - r#"events=$1 -(cat <&3 >/dev/null; echo eof >>"$events") & -trap '' TERM -echo ready >>"$events" -while :; do sleep 0.05; done"#, - ) - .arg("supervisor") - .arg(&events) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()); - // SAFETY: only async-signal-safe `dup2` runs between fork and exec. - unsafe { - command.pre_exec(move || { - if libc::dup2(read_fd, 3) < 0 { - return Err(std::io::Error::last_os_error()); - } - Ok(()) - }); - } - let supervisor = command.spawn().unwrap(); - drop(read_end); - let ready = async { - while !fs::read_to_string(&events).is_ok_and(|log| log.contains("ready")) { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }; - tokio::time::timeout(Duration::from_secs(5), ready) - .await - .expect("stand-in supervisor starts"); - - let mut process = VmProcess { - child: spawn_exited_child(), - supervisor, - supervisor_liveness: Some(fs::File::from(write_end)), - deleting: false, - }; - let grace = Duration::from_millis(300); - let started = tokio::time::Instant::now(); - terminate_sandbox_processes_within(&mut process, grace) - .await - .unwrap(); - let elapsed = started.elapsed(); - - assert!( - elapsed >= grace, - "the supervisor must get its full grace before the kill: {elapsed:?}" - ); - assert!( - process.supervisor.try_wait().unwrap().is_some(), - "the supervisor is gone once the grace has expired" - ); - assert!(process.supervisor_liveness.is_none()); - // The liveness pipe closes only after the supervisor has been dealt with. - let closed = async { - while !fs::read_to_string(&events).is_ok_and(|log| log.contains("eof")) { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }; - tokio::time::timeout(Duration::from_secs(5), closed) - .await - .expect("the liveness pipe is closed after the stop"); - let driver_log = fs::read_to_string(&driver_log).unwrap(); - assert!( - driver_log.contains("WARN") - && driver_log.contains("guest filesystem flush was not confirmed"), - "a forced supervisor shutdown must warn that recent writes may be lost: {driver_log:?}" - ); - fs::remove_dir_all(&dir).ok(); - } - - async fn insert_test_record( - driver: &VmDriver, - sandbox_id: &str, - state_dir: PathBuf, - child: Child, - ) { - let sandbox = Sandbox { - id: sandbox_id.to_string(), - name: sandbox_id.to_string(), - ..Default::default() - }; - let process = Arc::new(Mutex::new(VmProcess { - child, - supervisor: spawn_exited_child(), - supervisor_liveness: None, - deleting: false, - })); - - let mut registry = driver.registry.lock().await; - registry.insert( - sandbox_id.to_string(), - SandboxRecord { - snapshot: sandbox, - state_dir, - process: Some(process), - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - } - - use crate::lifecycle::{ - BackendFeature, LaunchPlan, LifecycleError, LifecycleExtension, LifecycleExtensionRegistry, - LifecycleResult, - }; - use crate::runtime::VmBackend; - - /// Driver whose rootfs tar staging root is an isolated temp directory. - fn rootfs_tar_test_driver(staging_root: &Path, max_bytes: Option) -> VmDriver { - let (events, _) = broadcast::channel(WATCH_BUFFER); - let (socket_root, socket_root_fd) = test_socket_root(); - VmDriver { - config: VmDriverConfig { - rootfs_tar_staging_dir: Some(staging_root.to_path_buf()), - rootfs_tar_max_bytes: max_bytes, - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - } - } - - /// `/req-/` with `contents`, the shape the - /// gateway allocates for one create request. - fn staged_rootfs_tar(staging_root: &Path, request: &str, contents: &[u8]) -> PathBuf { - let request_dir = staging_root.join(format!("req-{request}")); - std::fs::create_dir_all(&request_dir).expect("create request dir"); - let archive = request_dir.join("rootfs.tar"); - std::fs::write(&archive, contents).expect("write archive"); - archive - } - - #[tokio::test] - async fn validate_rootfs_tar_path_accepts_staged_archive() { - let root = unique_temp_dir(); - std::fs::create_dir_all(&root).expect("create staging root"); - let archive = staged_rootfs_tar(&root, "a", b"payload"); - let driver = rootfs_tar_test_driver(&root, None); - - let resolved = driver - .validate_rootfs_tar_path(&archive) - .await - .expect("a correctly staged archive is accepted"); - - assert_eq!( - resolved, - archive.canonicalize().expect("canonicalize archive") - ); - let _ = std::fs::remove_dir_all(&root); - } - - /// The core of the fix: a caller-named host path must never reach - /// privileged driver I/O, even if the caller is authenticated. - #[tokio::test] - async fn validate_rootfs_tar_path_rejects_arbitrary_host_paths() { - let root = unique_temp_dir(); - std::fs::create_dir_all(&root).expect("create staging root"); - let driver = rootfs_tar_test_driver(&root, None); - - for candidate in ["/etc/passwd", "/dev/zero"] { - let path = Path::new(candidate); - if !path.exists() { - continue; - } - let Err(err) = driver.validate_rootfs_tar_path(path).await else { - panic!("{candidate} must be rejected"); - }; - assert_eq!( - err.code(), - Code::PermissionDenied, - "{candidate} should be denied, got: {err}" - ); - } - let _ = std::fs::remove_dir_all(&root); - } - - #[tokio::test] - async fn validate_rootfs_tar_path_rejects_symlink_escape() { - let root = unique_temp_dir(); - let request_dir = root.join("req-a"); - std::fs::create_dir_all(&request_dir).expect("create request dir"); - let target = unique_temp_dir(); - std::fs::create_dir_all(&target).expect("create escape target dir"); - let secret = target.join("secret.tar"); - std::fs::write(&secret, b"not yours").expect("write escape target"); - let link = request_dir.join("rootfs.tar"); - std::os::unix::fs::symlink(&secret, &link).expect("create symlink"); - let driver = rootfs_tar_test_driver(&root, None); - - let err = driver - .validate_rootfs_tar_path(&link) - .await - .expect_err("a symlink out of the staging root must be rejected"); - - assert_eq!(err.code(), Code::PermissionDenied, "{err}"); - let _ = std::fs::remove_dir_all(&root); - let _ = std::fs::remove_dir_all(&target); - } - - #[tokio::test] - async fn validate_rootfs_tar_path_rejects_wrong_depth() { - let root = unique_temp_dir(); - std::fs::create_dir_all(&root).expect("create staging root"); - let shallow = root.join("rootfs.tar"); - std::fs::write(&shallow, b"payload").expect("write shallow archive"); - let deep_dir = root.join("req-a").join("nested"); - std::fs::create_dir_all(&deep_dir).expect("create deep dir"); - let deep = deep_dir.join("rootfs.tar"); - std::fs::write(&deep, b"payload").expect("write deep archive"); - let driver = rootfs_tar_test_driver(&root, None); - - for path in [&shallow, &deep] { - let err = driver - .validate_rootfs_tar_path(path) - .await - .expect_err("only request-directory depth is accepted"); - assert_eq!(err.code(), Code::PermissionDenied, "{err}"); - } - let _ = std::fs::remove_dir_all(&root); - } - - #[tokio::test] - async fn validate_rootfs_tar_path_rejects_directory() { - let root = unique_temp_dir(); - let request_dir = root.join("req-a"); - let not_a_file = request_dir.join("rootfs.tar"); - std::fs::create_dir_all(¬_a_file).expect("create directory in archive position"); - let driver = rootfs_tar_test_driver(&root, None); - - let err = driver - .validate_rootfs_tar_path(¬_a_file) - .await - .expect_err("a directory is not a rootfs tar"); - - assert_eq!(err.code(), Code::InvalidArgument, "{err}"); - let _ = std::fs::remove_dir_all(&root); - } - - #[tokio::test] - async fn validate_rootfs_tar_path_enforces_max_bytes() { - let root = unique_temp_dir(); - std::fs::create_dir_all(&root).expect("create staging root"); - let archive = staged_rootfs_tar(&root, "a", &[0_u8; 64]); - let driver = rootfs_tar_test_driver(&root, Some(16)); - - let err = driver - .validate_rootfs_tar_path(&archive) - .await - .expect_err("an oversized archive must be rejected"); - - assert_eq!(err.code(), Code::InvalidArgument, "{err}"); - let _ = std::fs::remove_dir_all(&root); - } - - /// Identity must follow the bytes and configured owner contract, not the - /// path. The gateway hands every request its own staging directory, so a - /// path-derived key would miss the cache on every single create. - #[test] - fn rootfs_tar_cache_identity_tracks_contents_and_owner_contract() { - let config = VmDriverConfig::default(); - let same_a = rootfs_tar_cache_identity(&compute_bytes_sha256_hex(b"rootfs-bytes"), &config); - let same_b = rootfs_tar_cache_identity(&compute_bytes_sha256_hex(b"rootfs-bytes"), &config); - let different = - rootfs_tar_cache_identity(&compute_bytes_sha256_hex(b"other-bytes"), &config); - let configured_owner = rootfs_tar_cache_identity( - &compute_bytes_sha256_hex(b"rootfs-bytes"), - &VmDriverConfig { - sandbox_uid: Some(1234), - sandbox_gid: Some(5678), - ..VmDriverConfig::default() - }, - ); - - assert_eq!( - same_a, same_b, - "identical contents and owner contracts must share one prepared disk" - ); - assert_ne!( - same_a, different, - "different contents must not collide on one prepared disk" - ); - assert_ne!( - same_a, configured_owner, - "different owner contracts must not share a prepared disk" - ); - } - - /// The old key was `path + seconds-truncated mtime` run through a - /// punctuation sanitizer, so `/tmp/a/b.tar` and `/tmp/a-b.tar` collided and - /// a long path could blow past filesystem component limits. - #[test] - fn rootfs_tar_cache_identity_is_bounded_and_separator_safe() { - let long_path_digest = compute_bytes_sha256_hex(&vec![7_u8; 4096]); - let identity = rootfs_tar_cache_identity(&long_path_digest, &VmDriverConfig::default()); - let sanitized = sanitize_image_identity(&identity); - - assert!( - sanitized.len() < 255, - "cache directory component must stay within filesystem limits, got {}", - sanitized.len() - ); - assert_ne!( - rootfs_tar_cache_identity( - &compute_bytes_sha256_hex(b"/tmp/a/b.tar"), - &VmDriverConfig::default(), - ), - rootfs_tar_cache_identity( - &compute_bytes_sha256_hex(b"/tmp/a-b.tar"), - &VmDriverConfig::default(), - ), - "separator-colliding inputs must not share an identity" - ); - } - - const TEST_STAGING_LIMIT: u64 = 10 * 1024 * 1024; - - /// Build an uncompressed tar holding a single file. - pub(super) fn tar_bytes_with_file(name: &str, contents: &[u8]) -> Vec { - let mut builder = tar::Builder::new(Vec::new()); - append_test_tar_file(&mut builder, name, contents); - builder.into_inner().expect("finish tar") - } - - pub(super) fn append_test_tar_file( - builder: &mut tar::Builder>, - name: &str, - contents: &[u8], - ) { - let mut header = tar::Header::new_gnu(); - header.set_size(u64::try_from(contents.len()).expect("tar entry size fits u64")); - header.set_mode(0o644); - header.set_cksum(); - builder - .append_data(&mut header, name, contents) - .expect("append tar entry"); - } - - fn append_test_tar_symlink(builder: &mut tar::Builder>, name: &str, target: &Path) { - let mut header = tar::Header::new_gnu(); - header.set_entry_type(tar::EntryType::Symlink); - header.set_size(0); - header.set_mode(0o777); - header.set_link_name(target).expect("set symlink target"); - header.set_cksum(); - builder - .append_data(&mut header, name, std::io::empty()) - .expect("append symlink entry"); - } - - pub(super) fn gzip_bytes(bytes: &[u8]) -> Vec { - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - encoder.write_all(bytes).expect("gzip payload"); - encoder.finish().expect("finish gzip") - } - - #[test] - fn stage_rootfs_tar_archive_matches_source_digest() { - let base = unique_temp_dir(); - std::fs::create_dir_all(&base).expect("create base dir"); - let src = base.join("src.tar"); - let dst = base.join("dst.tar"); - let payload = vec![3_u8; 200 * 1024]; - std::fs::write(&src, &payload).expect("write source"); - - let copied = - stage_rootfs_tar_archive(&src, &dst, TEST_STAGING_LIMIT).expect("copy should succeed"); - - assert_eq!(copied, compute_file_sha256_hex(&src).expect("hash source")); - assert_eq!(copied, compute_bytes_sha256_hex(&payload)); - assert_eq!(std::fs::read(&dst).expect("read copy"), payload); - let _ = std::fs::remove_dir_all(&base); - } - - /// An archive rewritten between the hash pass and the copy pass yields a - /// different digest, which is what lets the caller reject it instead of - /// caching a disk under an identity that does not describe it. - #[test] - fn stage_rootfs_tar_archive_detects_content_change_between_passes() { - let base = unique_temp_dir(); - std::fs::create_dir_all(&base).expect("create base dir"); - let src = base.join("src.tar"); - std::fs::write(&src, b"original").expect("write source"); - let first = compute_file_sha256_hex(&src).expect("hash source"); - - std::fs::write(&src, b"replaced").expect("rewrite source"); - let second = stage_rootfs_tar_archive(&src, &base.join("dst.tar"), TEST_STAGING_LIMIT) - .expect("copy"); - - assert_ne!( - first, second, - "a mid-staging rewrite must produce a different digest" - ); - let _ = std::fs::remove_dir_all(&base); - } - - /// `--from` accepts `.tar.gz`/`.tgz`, and the guest extracts the staged - /// file as a plain tar, so staging has to decompress on the way in. - #[test] - fn stage_rootfs_tar_archive_decompresses_gzip_sources() { - let base = unique_temp_dir(); - std::fs::create_dir_all(&base).expect("create base dir"); - let tar = tar_bytes_with_file("etc/marker.txt", b"rootfs-tar-gzip\n"); - let gzipped = gzip_bytes(&tar); - let src = base.join("src.tar.gz"); - let dst = base.join("source-rootfs.tar"); - std::fs::write(&src, &gzipped).expect("write source"); - - let digest = - stage_rootfs_tar_archive(&src, &dst, TEST_STAGING_LIMIT).expect("stage gzip archive"); - - assert_eq!( - digest, - compute_bytes_sha256_hex(&gzipped), - "the digest must cover the whole compressed source" - ); - assert_eq!( - std::fs::read(&dst).expect("read staged archive"), - tar, - "the staged archive must be an uncompressed tar" - ); - - let extracted = base.join("extracted"); - extract_rootfs_archive_to(&dst, &extracted).expect("extract staged archive"); - assert_eq!( - std::fs::read_to_string(extracted.join("etc/marker.txt")).expect("read marker"), - "rootfs-tar-gzip\n" - ); - let _ = std::fs::remove_dir_all(&base); - } - - /// The configured limit bounds what the driver writes, not just what it - /// accepts, so a highly compressible archive cannot fill the host disk. - #[test] - fn stage_rootfs_tar_archive_rejects_oversized_expansion() { - let base = unique_temp_dir(); - std::fs::create_dir_all(&base).expect("create base dir"); - let src = base.join("bomb.tar.gz"); - std::fs::write(&src, gzip_bytes(&vec![0_u8; 4 * 1024 * 1024])).expect("write source"); - - let err = stage_rootfs_tar_archive(&src, &base.join("dst.tar"), 64 * 1024) - .expect_err("expansion beyond the limit must be rejected"); - - assert!(err.contains("65536"), "unexpected error: {err}"); - let _ = std::fs::remove_dir_all(&base); - } - - fn test_driver_with_extensions(extensions: LifecycleExtensionRegistry) -> VmDriver { - let (events, _) = broadcast::channel(WATCH_BUFFER); - let (socket_root, socket_root_fd) = test_socket_root(); - VmDriver { - config: VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - vcpus: 2, - mem_mib: 2048, - gpu_vcpus: 8, - gpu_mem_mib: 16384, - ..Default::default() - }, - socket_root, - socket_root_fd, - launcher_bin: PathBuf::from("openshell-driver-vm"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events, - gpu_inventory: None, - lifecycle_extensions: Arc::new(extensions), - } - } - - fn test_driver_with_proxy(https_proxy: &str) -> VmDriver { - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.upstream_proxy.https_proxy = Some(https_proxy.to_string()); - driver - } - - #[derive(Debug)] - struct QemuRequiringExtension { - name: String, - } - - #[tonic::async_trait] - impl LifecycleExtension for QemuRequiringExtension { - fn name(&self) -> &str { - &self.name - } - - async fn configure_launch( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - plan.require_backend(VmBackend::Qemu); - plan.require_backend_feature(BackendFeature::PciPassthrough); - Ok(()) - } - - async fn before_launch( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - if plan.backend != VmBackend::Qemu { - return Err(LifecycleError::new( - "qemu-requiring extension demands QEMU backend", - )); - } - plan.env.push("EXT_DECLARED_QEMU=1".to_string()); - Ok(()) - } - } - - #[derive(Debug)] - struct AlwaysFailsExtension; - - #[tonic::async_trait] - impl LifecycleExtension for AlwaysFailsExtension { - fn name(&self) -> &'static str { - "always-fails" - } - - async fn before_launch( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - _plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - Err(LifecycleError::resource_exhausted("pool empty")) - } - } - - #[test] - fn empty_registry_keeps_non_gpu_sandbox_on_libkrun() { - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - - let plan = driver - .build_vm_launch_plan("sandbox-x", false, false, None) - .expect("plan should build"); - - assert_eq!(plan.backend, VmBackend::Libkrun); - assert_eq!(plan.vcpus, 2); - assert_eq!(plan.mem_mib, 2048); - assert!(plan.vsock_cid.is_none()); - assert!(plan.gpu_bdf.is_none()); - assert!(plan.env.is_empty()); - } - - #[test] - fn empty_registry_has_no_extension_descriptors() { - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - assert!(driver.lifecycle_extensions.descriptors().is_empty()); - } - - #[test] - fn gpu_sandbox_uses_qemu_backend_and_gpu_sizing() { - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - - let plan = driver - .build_vm_launch_plan("sandbox-gpu", true, true, Some("0000:01:00.0".to_string())) - .expect("gpu plan should build"); - - assert_eq!(plan.backend, VmBackend::Qemu); - assert_eq!(plan.vcpus, 8); - assert_eq!(plan.mem_mib, 16384); - assert_eq!(plan.gpu_bdf.as_deref(), Some("0000:01:00.0")); - assert!(plan.vsock_cid.is_some()); - } - - #[test] - fn launch_plan_rejects_external_kernel_on_unsupported_backend() { - let mut plan = LaunchPlan { - backend: VmBackend::Libkrun, - vcpus: 2, - mem_mib: 2048, - required_backends: Vec::new(), - required_backend_features: Vec::new(), - kernel_profile: None, - kernel_image: Some(PathBuf::from("/tmp/openshell-test-kernel")), - gpu_bdf: None, - vsock_cid: None, - guest_init_dropins: Vec::new(), - env: Vec::new(), - }; - - let err = VmDriver::validate_launch_plan_backend(false, &plan) - .expect_err("external kernels require a compatible backend"); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("external kernel images")); - - let base = unique_temp_dir(); - std::fs::create_dir_all(&base).unwrap(); - let kernel = base.join("vmlinux"); - std::fs::write(&kernel, b"kernel").unwrap(); - plan.backend = VmBackend::Qemu; - plan.kernel_image = Some(kernel); - VmDriver::validate_launch_plan_backend(true, &plan).expect("existing kernel is accepted"); - let _ = std::fs::remove_dir_all(base); - } - - #[test] - fn backend_feature_requirements_select_qemu_launch_plan() { - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - let mut plan = driver - .build_vm_launch_plan("sandbox-vfio", false, false, None) - .expect("base plan should build"); - plan.require_backend_feature(BackendFeature::PciPassthrough); - - driver - .resolve_launch_plan_backend("sandbox-vfio", false, None, &mut plan) - .expect("backend feature should resolve"); - - assert_eq!(plan.backend, VmBackend::Qemu); - assert!(plan.vsock_cid.is_some()); - } - - #[test] - fn explicit_backend_requirement_selects_qemu_launch_plan() { - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - let mut plan = driver - .build_vm_launch_plan("sandbox-qemu", false, false, None) - .expect("base plan should build"); - plan.require_backend(VmBackend::Qemu); - - driver - .resolve_launch_plan_backend("sandbox-qemu", false, None, &mut plan) - .expect("backend requirement should resolve"); - - assert_eq!(plan.backend, VmBackend::Qemu); - assert!(plan.vsock_cid.is_some()); - } - - #[test] - fn guest_init_dropin_feature_does_not_force_qemu() { - let driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - let mut plan = driver - .build_vm_launch_plan("sandbox-init", false, false, None) - .expect("base plan should build"); - plan.require_backend_feature(BackendFeature::GuestInitDropins); - - driver - .resolve_launch_plan_backend("sandbox-init", false, None, &mut plan) - .expect("guest init feature should resolve"); - - assert_eq!(plan.backend, VmBackend::Libkrun); - } - - #[test] - fn guest_init_dropin_validation_rejects_unsafe_or_duplicate_names() { - validate_guest_init_dropins(&[GuestInitDropin::new("50-vfio.sh", b"true\n".to_vec())]) - .expect("safe drop-in name is accepted"); - - let err = validate_guest_init_dropins(&[GuestInitDropin::new( - "../50-vfio.sh", - b"true\n".to_vec(), - )]) - .expect_err("path traversal is rejected"); - assert!(err.contains("must contain only ASCII")); - - let err = validate_guest_init_dropins(&[ - GuestInitDropin::new("50-vfio.sh", b"true\n".to_vec()), - GuestInitDropin::new("50-vfio.sh", b"true\n".to_vec()), - ]) - .expect_err("duplicate drop-ins are rejected"); - assert!(err.contains("duplicate")); - } - - #[test] - fn guest_init_dropin_manifest_lists_only_injected_names_sorted() { - let manifest = render_guest_init_dropin_manifest(&[ - GuestInitDropin::new("50-vfio.sh", b"true\n".to_vec()), - GuestInitDropin::new("10-nemo.sh", b"true\n".to_vec()), - ]); - assert_eq!( - String::from_utf8(manifest).unwrap(), - "10-nemo.sh\n50-vfio.sh\n" - ); - } - - #[test] - fn guest_init_dropin_manifest_is_empty_when_no_dropins() { - // An empty manifest is the fail-closed signal that nothing under - // init.d should run. - assert!(render_guest_init_dropin_manifest(&[]).is_empty()); - } - - #[tokio::test] - async fn extension_can_validate_backend_in_before_launch() { - let extension = Arc::new(QemuRequiringExtension { - name: "validate".to_string(), - }); - let extensions = LifecycleExtensionRegistry::with(vec![extension.clone()]); - let sandbox = Sandbox { - id: "sandbox-validate".to_string(), - name: "sandbox-validate".to_string(), - ..Default::default() - }; - - let mut libkrun_plan = LaunchPlan { - backend: VmBackend::Libkrun, - vcpus: 2, - mem_mib: 2048, - required_backends: Vec::new(), - required_backend_features: Vec::new(), - kernel_profile: None, - kernel_image: None, - gpu_bdf: None, - vsock_cid: None, - guest_init_dropins: Vec::new(), - env: Vec::new(), - }; - let err = extensions - .before_launch(&sandbox, Path::new("/tmp/state"), &mut libkrun_plan) - .await - .expect_err("backend mismatch should fail validation"); - assert!(err.message().contains("demands QEMU")); - - let mut qemu_plan = LaunchPlan { - backend: VmBackend::Qemu, - vcpus: 2, - mem_mib: 2048, - required_backends: Vec::new(), - required_backend_features: Vec::new(), - kernel_profile: None, - kernel_image: None, - gpu_bdf: None, - vsock_cid: Some(7), - guest_init_dropins: Vec::new(), - env: Vec::new(), - }; - extensions - .before_launch(&sandbox, Path::new("/tmp/state"), &mut qemu_plan) - .await - .expect("QEMU backend should satisfy the extension"); - assert!(qemu_plan.env.contains(&"EXT_DECLARED_QEMU=1".to_string())); - } - - #[tokio::test] - async fn lifecycle_error_resource_exhausted_propagates() { - let extensions = LifecycleExtensionRegistry::with(vec![Arc::new(AlwaysFailsExtension)]); - let sandbox = Sandbox { - id: "sandbox-resource".to_string(), - name: "sandbox-resource".to_string(), - ..Default::default() - }; - let mut plan = LaunchPlan { - backend: VmBackend::Qemu, - vcpus: 2, - mem_mib: 2048, - required_backends: Vec::new(), - required_backend_features: Vec::new(), - kernel_profile: None, - kernel_image: None, - gpu_bdf: None, - vsock_cid: Some(7), - guest_init_dropins: Vec::new(), - env: Vec::new(), - }; - let err = extensions - .before_launch(&sandbox, Path::new("/tmp/state"), &mut plan) - .await - .expect_err("scripted pool exhaustion should surface"); - assert!(err.is_resource_exhausted()); - assert_eq!(err.message(), "pool empty"); - } - - /// A driver config carrying only corporate proxy settings. - fn proxy_config( - https_proxy: Option<&str>, - auth_file: Option<&str>, - ca_bundle: Option<&str>, - ) -> VmDriverConfig { - VmDriverConfig { - grpc_endpoint: "http://127.0.0.1:8080".to_string(), - upstream_proxy: UpstreamProxyConfig { - https_proxy: https_proxy.map(ToString::to_string), - proxy_auth_file: auth_file.map(PathBuf::from), - proxy_auth_allow_insecure: auth_file.map(|_| true), - ..UpstreamProxyConfig::default() - }, - proxy_ca_bundle: ca_bundle.map(PathBuf::from), - ..Default::default() - } - } - - #[test] - fn driver_config_debug_redacts_the_proxy_url_and_credential_path() { - // `Debug` can be emitted before validation runs, and an unvalidated - // proxy URL may still carry inline `user:pass@` credentials. - let rendered = format!( - "{:?}", - proxy_config( - Some("http://user:secret@proxy.corp.test:3128"), - Some("/etc/openshell/secrets/proxy-auth"), - None, - ) - ); - assert!( - !rendered.contains("secret") && !rendered.contains("proxy.corp.test"), - "the proxy URL must be logged as presence only: {rendered}" - ); - assert!( - !rendered.contains("/etc/openshell/secrets/proxy-auth"), - "the credential path must be logged as presence only: {rendered}" - ); - assert!( - rendered.contains("upstream_proxy_configured: true") - && rendered.contains("proxy_auth_file_configured: true"), - "presence of each must still be visible for debugging: {rendered}" - ); - } - - #[test] - fn ipv6_egress_settings_parse_validate_and_render_supervisor_args() { - let mut value = serde_json::to_value(proxy_config(None, None, None)).unwrap(); - value["policy_dns_ipv6_egress"] = "enabled".into(); - value["nat64_prefixes"] = serde_json::json!(["2001:db8:64::/96"]); - let config: VmDriverConfig = - serde_json::from_value(value).expect("VM driver config parses flattened keys"); - config.validate_runtime_security_config().unwrap(); - assert_eq!( - config.ipv6_egress.supervisor_args(), - [ - "--policy-dns-ipv6-egress", - "enabled", - "--nat64-prefix", - "2001:db8:64::/96" - ] - ); - let invalid = VmDriverConfig { - ipv6_egress: openshell_core::SupervisorIpv6EgressConfig { - nat64_prefixes: vec!["2001:db8::/33".to_string()], - ..Default::default() - }, - ..proxy_config(None, None, None) - }; - assert!(invalid.validate_runtime_security_config().is_err()); - } - - #[test] - fn upstream_proxy_args_are_empty_without_a_configured_proxy() { - assert!( - upstream_proxy_cli_args(&VmDriverConfig::default()) - .unwrap() - .is_empty() - ); - } - - #[test] - fn upstream_proxy_args_pass_host_paths_to_host_control() { - let config = proxy_config( - Some("http://proxy.corp.test:3128"), - Some("/etc/openshell/secrets/proxy-auth"), - Some("/etc/openshell/tls/corp-ca.pem"), - ); - let args = upstream_proxy_cli_args(&config).unwrap(); - - // Control runs on the gateway host and receives the operator-owned - // paths directly; neither path is copied into the guest. - let auth = args - .iter() - .position(|arg| arg == "--upstream-proxy-auth-file") - .map(|i| args[i + 1].as_str()); - assert_eq!(auth, Some("/etc/openshell/secrets/proxy-auth")); - let ca = args - .iter() - .position(|arg| arg == "--upstream-proxy-ca-bundle") - .map(|i| args[i + 1].as_str()); - assert_eq!(ca, Some("/etc/openshell/tls/corp-ca.pem")); - } - - #[test] - fn upstream_proxy_args_pass_only_explicit_opt_ins() { - let mut config = proxy_config(Some("https://proxy.corp.test:3130"), None, None); - config.upstream_proxy.no_proxy = Some("10.0.0.0/8,.svc.cluster.local".to_string()); - let args = upstream_proxy_cli_args(&config).unwrap(); - assert_eq!( - args, - vec![ - "--upstream-proxy".to_string(), - "https://proxy.corp.test:3130".to_string(), - "--upstream-no-proxy".to_string(), - "10.0.0.0/8,.svc.cluster.local".to_string(), - ] - ); - - // `Some(false)` must not be passed as the presence flag it is on the - // supervisor side. - config.upstream_proxy.proxy_connect_by_hostname = Some(false); - assert!( - !upstream_proxy_cli_args(&config) - .unwrap() - .iter() - .any(|arg| arg == "--upstream-proxy-connect-by-hostname") - ); - config.upstream_proxy.proxy_connect_by_hostname = Some(true); - assert!( - upstream_proxy_cli_args(&config) - .unwrap() - .iter() - .any(|arg| arg == "--upstream-proxy-connect-by-hostname") - ); - } - - #[test] - fn upstream_proxy_args_route_vm_host_aliases_to_host_loopback() { - for alias in HOST_LOOPBACK_ALIASES { - let config = proxy_config(Some(&format!("http://{alias}:3128")), None, None); - let args = upstream_proxy_cli_args(&config).unwrap(); - assert_eq!( - args, - vec![ - "--upstream-proxy".to_string(), - format!("http://{alias}:3128"), - "--upstream-proxy-dial-ip".to_string(), - "127.0.0.1".to_string(), - ], - "host alias {alias} must dial host loopback without changing its TLS identity" - ); - } - } - - #[test] - fn proxy_config_validation_rejects_settings_without_a_proxy_url() { - let config = VmDriverConfig { - upstream_proxy: UpstreamProxyConfig { - no_proxy: Some("10.0.0.0/8".to_string()), - ..UpstreamProxyConfig::default() - }, - ..Default::default() - }; - let err = config - .validate_runtime_security_config() - .expect_err("a bypass list without a proxy would hide a fail-open state"); - assert!(err.contains("no_proxy"), "{err}"); - - let config = proxy_config(Some("http://proxy.corp.test:3128"), None, None); - config - .validate_runtime_security_config() - .expect("a lone proxy URL is a complete configuration"); - - let config = VmDriverConfig { - proxy_ca_bundle: Some(PathBuf::from("/etc/openshell/tls/corp-ca.pem")), - ..Default::default() - }; - let err = config - .validate_runtime_security_config() - .expect_err("a CA bundle without a proxy URL must fail closed"); - assert!(err.contains("proxy_ca_bundle"), "{err}"); - } - - #[test] - fn proxy_config_validation_requires_the_cleartext_acknowledgement() { - let mut config = proxy_config( - Some("http://proxy.corp.test:3128"), - Some("/etc/openshell/secrets/proxy-auth"), - None, - ); - config.upstream_proxy.proxy_auth_allow_insecure = None; - let err = config - .validate_runtime_security_config() - .expect_err("Basic auth to an http:// proxy is cleartext on the wire"); - assert!(err.contains("proxy_auth_allow_insecure"), "{err}"); - } - - #[test] - fn qemu_launch_plan_uses_vsock_only_with_host_proxy() { - let driver = test_driver_with_proxy("http://127.0.0.1:8080"); - let mut plan = driver - .build_vm_launch_plan("sandbox-proxy-vsock", true, true, None) - .expect("gpu plan should build"); - driver - .resolve_launch_plan_backend("sandbox-proxy-vsock", true, None, &mut plan) - .expect("host control can reach a host-loopback proxy"); - assert!(plan.vsock_cid.is_some()); - } - - #[test] - fn guest_environment_carries_no_corporate_proxy_settings() { - // The egress boundary is argv-only: `build_guest_environment` merges - // user-supplied environment, so anything it emitted here would be - // attacker-influenced. - let config = proxy_config( - Some("http://proxy.corp.test:3128"), - Some("/etc/openshell/secrets/proxy-auth"), - None, - ); - let sandbox = Sandbox { - id: "sb-proxy".to_string(), - name: "proxy".to_string(), - spec: Some(SandboxSpec { - environment: [ - ( - "HTTPS_PROXY".to_string(), - "http://attacker:3128".to_string(), - ), - ("NO_PROXY".to_string(), "*".to_string()), - ] - .into_iter() - .collect(), - ..Default::default() - }), - ..Default::default() - }; - - let env = build_guest_environment(&sandbox, &config); - assert!( - !env.iter().any(|entry| entry.starts_with("--upstream")), - "driver environment must never carry supervisor arguments: {env:?}" - ); - // A sandbox may still set the conventional variables for its own - // workload, but the supervisor ignores them on this path -- what - // matters is that the driver never derives the boundary from them. - assert!( - !env.iter() - .any(|entry| entry.contains("proxy.corp.test") || entry.contains("proxy-auth")), - "operator proxy settings must not reach the guest environment: {env:?}" - ); - } - - #[test] - fn sandbox_driver_config_cannot_carry_proxy_settings() { - // The upstream proxy is host network infrastructure, not a per-sandbox - // setting: the caller-supplied envelope must reject it outright - // rather than silently ignoring it. - for key in [ - "https_proxy", - "no_proxy", - "proxy_auth_file", - "proxy_auth_allow_insecure", - "proxy_connect_by_hostname", - ] { - let template = SandboxTemplate { - driver_config: Some(Struct { - fields: std::iter::once(( - key.to_string(), - Value { - kind: Some(Kind::StringValue("http://attacker:3128".to_string())), - }, - )) - .collect(), - }), - ..Default::default() - }; - assert!( - VmSandboxDriverConfig::from_template(&template).is_err(), - "template.driver_config.vm must reject '{key}'" - ); - } - } - - #[test] - fn capabilities_report_static_resource_support() { - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - let resources = driver.capabilities().resource_capabilities.unwrap(); - assert!(!resources.cpu.unwrap().limit_supported); - assert!(!resources.memory.unwrap().limit_supported); - let gpu = resources.gpu.unwrap(); - assert!(!gpu.default_selection_supported); - assert!(!gpu.count_selection_supported); - - driver.config.gpu_enabled = true; - let gpu = driver - .capabilities() - .resource_capabilities - .unwrap() - .gpu - .unwrap(); - assert!(gpu.default_selection_supported); - assert!(gpu.count_selection_supported); - } - - /// Register a stopped, process-free record whose id, name, and workspace are - /// set independently. - /// - /// The other test helpers reuse one string for both id and name, so a test - /// built on them cannot express the cross-workspace name collision that - /// lifecycle resolution has to tolerate. - async fn insert_named_record( - driver: &VmDriver, - id: &str, - name: &str, - workspace: &str, - ) -> PathBuf { - let state_dir = sandbox_state_dir(&driver.config.state_dir, id).unwrap(); - create_private_dir_all(&state_dir).await.unwrap(); - driver.registry.lock().await.insert( - id.to_string(), - SandboxRecord { - snapshot: Sandbox { - id: id.to_string(), - name: name.to_string(), - workspace: workspace.to_string(), - ..Default::default() - }, - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - state_dir - } - - fn resolution_test_driver(state_dir: &Path) -> VmDriver { - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = state_dir.to_path_buf(); - driver - } - - #[tokio::test] - async fn stop_targets_the_requested_id_when_two_workspaces_share_a_name() { - let temp = tempfile::tempdir().unwrap(); - let driver = resolution_test_driver(temp.path()); - let alpha = insert_named_record(&driver, "vm-alpha", "demo", "alpha").await; - let beta = insert_named_record(&driver, "vm-beta", "demo", "beta").await; - - driver - .stop_sandbox("vm-beta", "demo") - .await - .expect("stop by id should be accepted"); - - assert!( - beta.join(SANDBOX_STOPPED_FILE).exists(), - "the requested sandbox should have been stopped" - ); - assert!( - !alpha.join(SANDBOX_STOPPED_FILE).exists(), - "the same-named sandbox in another workspace must be untouched" - ); - } - - #[tokio::test] - async fn delete_targets_the_requested_id_when_two_workspaces_share_a_name() { - let temp = tempfile::tempdir().unwrap(); - let driver = resolution_test_driver(temp.path()); - let alpha = insert_named_record(&driver, "vm-alpha", "demo", "alpha").await; - insert_named_record(&driver, "vm-beta", "demo", "beta").await; - - let response = driver - .delete_sandbox("vm-beta", "demo") - .await - .expect("delete by id should be accepted"); - - assert!(response.deleted); - let registry = driver.registry.lock().await; - assert!(!registry.contains_key("vm-beta")); - assert!( - registry.contains_key("vm-alpha"), - "the same-named sandbox in another workspace must survive" - ); - assert!(alpha.exists(), "the surviving sandbox must keep its state"); - } - - #[tokio::test] - async fn a_repeated_delete_does_not_fall_back_to_a_same_named_sandbox() { - let temp = tempfile::tempdir().unwrap(); - let driver = resolution_test_driver(temp.path()); - let alpha = insert_named_record(&driver, "vm-alpha", "demo", "alpha").await; - insert_named_record(&driver, "vm-beta", "demo", "beta").await; - - let first = driver - .delete_sandbox("vm-beta", "demo") - .await - .expect("the first delete should be accepted"); - assert!(first.deleted); - - // Delete is idempotent, so a retry carrying the same id and name is - // ordinary caller behavior. The id is gone from the registry by now, and - // resolving it by name instead would destroy the sandbox in `alpha`. - let second = driver - .delete_sandbox("vm-beta", "demo") - .await - .expect("a repeated delete should be accepted"); - - assert!( - !second.deleted, - "a repeated delete must report that nothing was removed" - ); - assert!( - driver.registry.lock().await.contains_key("vm-alpha"), - "a repeated delete must not remove a same-named sandbox in another workspace" - ); - assert!(alpha.exists(), "the surviving sandbox must keep its state"); - } - - #[tokio::test] - async fn stop_and_start_reject_an_absent_id_that_shares_a_name() { - let temp = tempfile::tempdir().unwrap(); - let driver = resolution_test_driver(temp.path()); - let alpha = insert_named_record(&driver, "vm-alpha", "demo", "alpha").await; - - let stop_error = driver - .stop_sandbox("vm-absent", "demo") - .await - .expect_err("a supplied id that is not registered must not resolve by name"); - assert_eq!(stop_error.code(), Code::NotFound); - - let (start_authentication, _) = test_launch_authentication("absent"); - let start_error = driver - .start_sandbox( - "vm-absent", - "demo", - "g0000000000000001", - start_authentication, - ) - .await - .expect_err("a supplied id that is not registered must not resolve by name"); - assert_eq!(start_error.code(), Code::NotFound); - - assert!( - !alpha.join(SANDBOX_STOPPED_FILE).exists(), - "the same-named sandbox must not have been touched" - ); - } - - #[tokio::test] - async fn a_name_only_request_matching_two_sandboxes_is_rejected() { - let temp = tempfile::tempdir().unwrap(); - let driver = resolution_test_driver(temp.path()); - let alpha = insert_named_record(&driver, "vm-alpha", "demo", "alpha").await; - let beta = insert_named_record(&driver, "vm-beta", "demo", "beta").await; - - // Without an id the driver has nothing to disambiguate with: the request - // carries no workspace, and picking by iteration order would stop or - // delete an arbitrary one of the two. - for error in [ - driver.stop_sandbox("", "demo").await.unwrap_err(), - driver - .start_sandbox( - "", - "demo", - "g0000000000000001", - test_launch_authentication("ambiguous").0, - ) - .await - .unwrap_err(), - driver.delete_sandbox("", "demo").await.unwrap_err(), - ] { - assert_eq!(error.code(), Code::FailedPrecondition); - assert!(error.message().contains("matched more than one sandbox")); - } - - let registry = driver.registry.lock().await; - assert!(registry.contains_key("vm-alpha")); - assert!(registry.contains_key("vm-beta")); - assert!(!alpha.join(SANDBOX_STOPPED_FILE).exists()); - assert!(!beta.join(SANDBOX_STOPPED_FILE).exists()); - } - - #[tokio::test] - async fn a_name_only_request_still_resolves_a_unique_name() { - let temp = tempfile::tempdir().unwrap(); - let driver = resolution_test_driver(temp.path()); - let alpha = insert_named_record(&driver, "vm-alpha", "demo", "alpha").await; - insert_named_record(&driver, "vm-beta", "other", "beta").await; - - driver - .stop_sandbox("", "demo") - .await - .expect("an unambiguous name-only stop should still resolve"); - - assert!(alpha.join(SANDBOX_STOPPED_FILE).exists()); - } - - // ── VM mount config tests ────────────────────────────────────────── - - fn mount_test_config(enable_bind_mounts: bool) -> VmDriverConfig { - let mut config = VmDriverConfig { - enable_bind_mounts, - ..VmDriverConfig::default() - }; - config.resource_admission.enabled = false; - config - } - - #[test] - fn vm_mount_validation_rejects_when_resource_admission_enabled() { - let dir = std::env::temp_dir(); - let mounts = vec![VmMountConfig { - mount_type: None, - source: dir.display().to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let mut config = mount_test_config(true); - config.resource_admission.enabled = true; - let err = validate_vm_driver_mounts(&mounts, &config, false).unwrap_err(); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("resource admission")); - } - - #[test] - fn vm_mount_config_deserializes_with_default_readonly() { - let json = serde_json::json!({ - "mounts": [{"source": "/host/data", "target": "/sandbox/data"}] - }); - let config: VmSandboxDriverConfig = serde_json::from_value(json).unwrap(); - assert_eq!(config.mounts.len(), 1); - assert_eq!(config.mounts[0].source, "/host/data"); - assert_eq!(config.mounts[0].target, "/sandbox/data"); - assert!(config.mounts[0].read_only); - } - - #[test] - fn vm_mount_config_accepts_docker_style_bind_type() { - let json = serde_json::json!({ - "mounts": [{"type": "bind", "source": "/host/data", "target": "/sandbox/data"}] - }); - let config: VmSandboxDriverConfig = serde_json::from_value(json).unwrap(); - assert!(matches!( - config.mounts[0].mount_type, - Some(VmMountType::Bind) - )); - assert!(config.mounts[0].read_only); - } - - #[test] - fn vm_mount_config_rejects_non_bind_types() { - for mount_type in ["volume", "tmpfs", "image"] { - let json = serde_json::json!({ - "mounts": [{"type": mount_type, "source": "x", "target": "/sandbox/data"}] - }); - let err = serde_json::from_value::(json).unwrap_err(); - assert!( - err.to_string().contains("expected `bind`"), - "{mount_type}: {err}" - ); - } - } - - #[test] - fn vm_mount_config_deserializes_explicit_readwrite() { - let json = serde_json::json!({ - "mounts": [{"source": "/host/data", "target": "/sandbox/data", "read_only": false}] - }); - let config: VmSandboxDriverConfig = serde_json::from_value(json).unwrap(); - assert!(!config.mounts[0].read_only); - } - - #[test] - fn vm_mount_validation_requires_enable_bind_mounts() { - let dir = std::env::temp_dir(); - let mounts = vec![VmMountConfig { - mount_type: None, - source: dir.display().to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let err = validate_vm_driver_mounts(&mounts, &mount_test_config(false), false).unwrap_err(); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("enable_bind_mounts")); - } - - #[test] - fn vm_mount_validation_allows_when_enabled() { - let dir = std::env::temp_dir(); - let mounts = vec![VmMountConfig { - mount_type: None, - source: dir.display().to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - assert!(validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).is_ok()); - } - - #[test] - fn vm_mount_validation_rejects_relative_source() { - let mounts = vec![VmMountConfig { - mount_type: None, - source: "relative/path".to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let err = validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); - } - - #[test] - fn vm_mount_validation_rejects_control_chars_in_source() { - // The launcher receives mounts as tab-separated arguments. - for source in ["/srv/data\tvfs9\trw", "/srv/data\n/etc"] { - let mounts = vec![VmMountConfig { - mount_type: None, - source: source.to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let err = - validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("control characters")); - } - } - - #[test] - fn vm_mount_validation_rejects_reserved_openshell_target() { - let dir = std::env::temp_dir(); - let mounts = vec![VmMountConfig { - mount_type: None, - source: dir.display().to_string(), - target: "/opt/openshell/data".to_string(), - read_only: true, - }]; - let err = validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); - } - - #[test] - fn vm_mount_validation_rejects_vm_internal_paths() { - let dir = std::env::temp_dir(); - for reserved in VM_RESERVED_GUEST_PATHS { - let mounts = vec![VmMountConfig { - mount_type: None, - source: dir.display().to_string(), - target: reserved.to_string(), - read_only: true, - }]; - let err = - validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).unwrap_err(); - assert_eq!( - err.code(), - Code::InvalidArgument, - "expected rejection for target {reserved}" - ); - assert!( - err.message().contains("VM-internal path"), - "expected VM-internal path message for {reserved}, got: {}", - err.message() - ); - } - } - - #[test] - fn vm_mount_validation_rejects_duplicate_targets() { - let dir = std::env::temp_dir(); - let mounts = vec![ - VmMountConfig { - mount_type: None, - source: dir.display().to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }, - VmMountConfig { - mount_type: None, - source: dir.display().to_string(), - target: "/sandbox/data".to_string(), - read_only: false, - }, - ]; - let err = validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("duplicate")); - } - - #[tokio::test] - async fn vm_mount_validation_defers_missing_source_to_provisioning() { - let mounts = vec![VmMountConfig { - mount_type: None, - source: "/nonexistent/openshell-vm-mount-source".to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - assert!(validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).is_ok()); - let err = validate_vm_mount_sources(&mounts).await.unwrap_err(); - assert_eq!(err.code(), Code::FailedPrecondition); - } - - #[test] - fn vm_mount_validation_rejects_nested_targets() { - let dir = std::env::temp_dir().display().to_string(); - for (first, second) in [ - ("/sandbox/a", "/sandbox/a/b"), - ("/sandbox/a/b", "/sandbox/a"), - ] { - let mounts = vec![ - VmMountConfig { - mount_type: None, - source: dir.clone(), - target: first.to_string(), - read_only: true, - }, - VmMountConfig { - mount_type: None, - source: dir.clone(), - target: second.to_string(), - read_only: true, - }, - ]; - let err = - validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("overlaps"), "{first} vs {second}"); - } - } - - #[test] - fn vm_mount_validation_allows_sibling_targets() { - let dir = std::env::temp_dir().display().to_string(); - let mounts = vec![ - VmMountConfig { - mount_type: None, - source: dir.clone(), - target: "/sandbox/a".to_string(), - read_only: true, - }, - VmMountConfig { - mount_type: None, - source: dir, - target: "/sandbox/ab".to_string(), - read_only: true, - }, - ]; - assert!(validate_vm_driver_mounts(&mounts, &mount_test_config(true), false).is_ok()); - } - - #[test] - fn vm_mount_validation_empty_passes() { - assert!(validate_vm_driver_mounts(&[], &mount_test_config(false), false).is_ok()); - } - - #[test] - fn vm_mount_validation_rejects_qemu_backend() { - let dir = std::env::temp_dir(); - let mounts = vec![VmMountConfig { - mount_type: None, - source: dir.display().to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let err = validate_vm_driver_mounts(&mounts, &mount_test_config(true), true).unwrap_err(); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("QEMU")); - } - - #[test] - fn vm_mount_validation_rejects_too_many_mounts() { - let dir = std::env::temp_dir().display().to_string(); - let mounts = |count: usize| -> Vec { - (0..count) - .map(|i| VmMountConfig { - mount_type: None, - source: dir.clone(), - target: format!("/sandbox/data{i}"), - read_only: true, - }) - .collect() - }; - let config = mount_test_config(true); - assert!(validate_vm_driver_mounts(&mounts(VM_MAX_BIND_MOUNTS), &config, false).is_ok()); - let err = - validate_vm_driver_mounts(&mounts(VM_MAX_BIND_MOUNTS + 1), &config, false).unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("at most"), "{}", err.message()); - } - - #[cfg(unix)] - #[tokio::test] - async fn vm_mount_validation_rejects_unreadable_source() { - use std::os::unix::fs::PermissionsExt; - - if rustix::process::geteuid().is_root() { - return; // root bypasses directory permissions - } - let source = tempfile::tempdir().unwrap(); - fs::set_permissions(source.path(), fs::Permissions::from_mode(0o000)).unwrap(); - let mounts = vec![VmMountConfig { - mount_type: None, - source: source.path().display().to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let result = validate_vm_mount_sources(&mounts).await; - // Restore access before asserting so the temp dir can always be removed. - fs::set_permissions(source.path(), fs::Permissions::from_mode(0o700)).unwrap(); - let err = result.unwrap_err(); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("cannot access"), "{}", err.message()); - } - - #[cfg(unix)] - #[tokio::test] - async fn vm_mount_validation_rejects_symlink_source() { - let parent = tempfile::tempdir().unwrap(); - let real = parent.path().join("real"); - let link = parent.path().join("link"); - fs::create_dir(&real).unwrap(); - std::os::unix::fs::symlink(&real, &link).unwrap(); - // A trailing slash would make the stat resolve the link. - for suffix in ["", "/"] { - let mounts = vec![VmMountConfig { - mount_type: None, - source: format!("{}{suffix}", link.display()), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let err = validate_vm_mount_sources(&mounts).await.unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("symbolic link"), "{}", err.message()); - } - } - - #[tokio::test] - async fn vm_mount_validation_rejects_file_source() { - let file = tempfile::NamedTempFile::new().unwrap(); - let mounts = vec![VmMountConfig { - mount_type: None, - source: file.path().display().to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let err = validate_vm_mount_sources(&mounts).await.unwrap_err(); - assert_eq!(err.code(), Code::InvalidArgument); - assert!(err.message().contains("must be a directory")); - } - - #[tokio::test] - async fn vm_mount_validation_reports_inaccessible_source() { - // A path below a regular file fails stat with something other than - // NotFound, even as root. - let file = tempfile::NamedTempFile::new().unwrap(); - let mounts = vec![VmMountConfig { - mount_type: None, - source: file.path().join("child").display().to_string(), - target: "/sandbox/data".to_string(), - read_only: true, - }]; - let err = validate_vm_mount_sources(&mounts).await.unwrap_err(); - assert_eq!(err.code(), Code::FailedPrecondition); - assert!(err.message().contains("cannot access"), "{}", err.message()); - } - - #[tokio::test] - async fn provisioning_checks_mount_sources_before_resolving_images() { - let directory = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = directory.path().to_path_buf(); - let sandbox = Sandbox { - id: "sb-mount-source".to_string(), - name: "mount-source".to_string(), - spec: Some(SandboxSpec { - launch_authentication: test_launch_authentication("mount-source").0, - template: Some(SandboxTemplate { - driver_config: Some(mounts_driver_config( - "/nonexistent/openshell-vm-mount-source", - "/sandbox/data", - )), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - let state_dir = directory.path().join("sandbox"); - driver.registry.lock().await.insert( - sandbox.id.clone(), - SandboxRecord { - snapshot: sandbox.clone(), - state_dir: state_dir.clone(), - process: None, - provisioning_task: None, - preparation: None, - gpu_bdf: None, - deleting: false, - }, - ); - let mut events = driver.events.subscribe(); - let error = driver - .provision_sandbox_inner( - sandbox, - "invalid image reference".to_string(), - state_dir, - None, - OverlayPreparation::Fresh, - ) - .await - .unwrap_err(); - assert!( - error.message().contains("does not exist"), - "{}", - error.message() - ); - assert!(matches!( - events.try_recv(), - Err(broadcast::error::TryRecvError::Empty) - )); - } - - /// Runs `prepare_virtiofs_target` from the guest init script against a - /// host directory standing in for the guest root. - #[cfg(unix)] - fn run_prepare_virtiofs_target(root: &Path, target: &str) -> std::process::Output { - let script = include_str!("../scripts/openshell-vm-sandbox-init.sh"); - let start = script - .find("prepare_virtiofs_target() {") - .expect("init script defines prepare_virtiofs_target"); - let end = start + script[start..].find("\n}\n").expect("function end") + 3; - let program = format!( - "set -euo pipefail\nts() {{ echo \"$@\"; }}\n{}\nprepare_virtiofs_target \"$1\" \"$(id -u):$(id -g)\"\n", - &script[start..end] - ); - std::process::Command::new("bash") - .args(["-c", &program, "test", target]) - .env("ROOT_PREFIX", root) - .output() - .unwrap() - } - - #[cfg(unix)] - #[test] - fn vm_init_prepare_virtiofs_target_creates_missing_directories() { - let root = tempfile::tempdir().unwrap(); - fs::create_dir(root.path().join("sandbox")).unwrap(); - let output = run_prepare_virtiofs_target(root.path(), "/sandbox/a/b"); - assert!(output.status.success(), "{output:?}"); - let expected = root.path().join("sandbox/a/b"); - assert!(expected.is_dir()); - assert_eq!( - String::from_utf8_lossy(&output.stdout).trim(), - expected.display().to_string() - ); - } - - #[cfg(unix)] - #[test] - fn vm_init_prepare_virtiofs_target_refuses_symlinks() { - let root = tempfile::tempdir().unwrap(); - let elsewhere = tempfile::tempdir().unwrap(); - fs::create_dir(root.path().join("sandbox")).unwrap(); - std::os::unix::fs::symlink(elsewhere.path(), root.path().join("sandbox/link")).unwrap(); - let output = run_prepare_virtiofs_target(root.path(), "/sandbox/link/x"); - assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr).contains("traverses symlink")); - assert!(!elsewhere.path().join("x").exists()); - } - - #[cfg(unix)] - #[test] - fn vm_init_prepare_virtiofs_target_refuses_non_directory() { - let root = tempfile::tempdir().unwrap(); - fs::create_dir(root.path().join("sandbox")).unwrap(); - fs::write(root.path().join("sandbox/file"), b"").unwrap(); - let output = run_prepare_virtiofs_target(root.path(), "/sandbox/file/x"); - assert!(!output.status.success()); - assert!(String::from_utf8_lossy(&output.stderr).contains("is not a directory")); - } - - fn mounts_driver_config(source: &str, target: &str) -> Struct { - let string = |s: &str| Value { - kind: Some(Kind::StringValue(s.to_string())), - }; - let mount = Struct { - fields: [ - ("source".to_string(), string(source)), - ("target".to_string(), string(target)), - ] - .into_iter() - .collect(), - }; - Struct { - fields: std::iter::once(( - "mounts".to_string(), - Value { - kind: Some(Kind::ListValue(prost_types::ListValue { - values: vec![Value { - kind: Some(Kind::StructValue(mount)), - }], - })), - }, - )) - .collect(), - } - } - - #[tokio::test] - async fn recovery_denied_when_bind_mounts_are_revoked() { - let directory = tempfile::tempdir().unwrap(); - let source = tempfile::tempdir().unwrap(); - let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); - driver.config.state_dir = directory.path().to_path_buf(); - driver.config.default_image = "invalid image reference".to_string(); - driver.config.allow_driver_config = true; - driver.config.resource_admission.enabled = false; - driver.config.enable_bind_mounts = true; - let sandbox = Sandbox { - id: "sb-mount-restore".to_string(), - name: "mount-restore".to_string(), - spec: Some(SandboxSpec { - launch_authentication: test_launch_authentication("mount-restore").0, - template: Some(SandboxTemplate { - driver_config: Some(mounts_driver_config( - &source.path().display().to_string(), - "/sandbox/data", - )), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - }; - decode_launch_authentication(&sandbox.spec.as_ref().unwrap().launch_authentication) - .expect("credentials are valid, so only the mount gate can deny recovery"); - driver - .validate_sandbox(&sandbox) - .expect("mounts are admitted while enabled"); - - driver.config.enable_bind_mounts = false; - let err = driver.validate_sandbox(&sandbox).unwrap_err(); - assert!( - err.message().contains("enable_bind_mounts"), - "{}", - err.message() - ); - let state_dir = sandbox_state_dir(directory.path(), &sandbox.id).unwrap(); - create_private_dir_all(&state_dir).await.unwrap(); - write_sandbox_request(&state_dir, &sandbox).await.unwrap(); - let accepted = driver - .restore_persisted_sandbox(sandbox, state_dir, true, &tracing::Span::current()) - .await; - assert!(!accepted, "revoked bind mounts must deny restoration"); - assert!(driver.registry.lock().await.is_empty()); - } - - #[test] - fn vm_mount_manifest_renders_tab_separated_entries() { - let mounts = [ - VmMountConfig { - mount_type: None, - source: "/host/a".to_string(), - target: "/sandbox/a".to_string(), - read_only: true, - }, - VmMountConfig { - mount_type: None, - source: "/host/b".to_string(), - target: "/sandbox/b".to_string(), - read_only: false, - }, - ]; - assert_eq!( - render_mount_manifest(&mounts), - "osfs0\t/sandbox/a\tro\nosfs1\t/sandbox/b\trw\n" - ); - } -} diff --git a/crates/openshell-driver-vm/src/embedded_runtime.rs b/crates/openshell-driver-vm/src/embedded_runtime.rs deleted file mode 100644 index 4b75bd4ba8..0000000000 --- a/crates/openshell-driver-vm/src/embedded_runtime.rs +++ /dev/null @@ -1,167 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Embedded libkrun runtime resources for the VM driver. - -use std::fs; -use std::path::{Path, PathBuf}; - -#[cfg(all(target_os = "macos", target_arch = "aarch64"))] -mod resources { - pub const LIBKRUN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrun.dylib.zst")); - pub const LIBKRUNFW: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrunfw.5.dylib.zst")); - pub const LIBKRUN_NAME: &str = "libkrun.dylib"; - pub const LIBKRUNFW_NAME: &str = "libkrunfw.5.dylib"; -} - -#[cfg(all(target_os = "linux", target_arch = "aarch64"))] -mod resources { - pub const LIBKRUN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrun.so.zst")); - pub const LIBKRUNFW: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrunfw.so.5.zst")); - pub const LIBKRUN_NAME: &str = "libkrun.so"; - pub const LIBKRUNFW_NAME: &str = "libkrunfw.so.5"; -} - -#[cfg(all(target_os = "linux", target_arch = "x86_64"))] -mod resources { - pub const LIBKRUN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrun.so.zst")); - pub const LIBKRUNFW: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrunfw.so.5.zst")); - pub const LIBKRUN_NAME: &str = "libkrun.so"; - pub const LIBKRUNFW_NAME: &str = "libkrunfw.so.5"; -} - -#[cfg(not(any( - all(target_os = "macos", target_arch = "aarch64"), - all(target_os = "linux", target_arch = "aarch64"), - all(target_os = "linux", target_arch = "x86_64"), -)))] -mod resources { - pub const LIBKRUN: &[u8] = &[]; - pub const LIBKRUNFW: &[u8] = &[]; - pub const LIBKRUN_NAME: &str = "libkrun"; - pub const LIBKRUNFW_NAME: &str = "libkrunfw"; -} - -const VERSION: &str = env!("CARGO_PKG_VERSION"); - -pub fn ensure_runtime_extracted() -> Result { - if resources::LIBKRUN.is_empty() { - return Err( - "VM runtime not embedded for this platform. Supported: macOS ARM64, Linux ARM64, Linux x86_64" - .to_string(), - ); - } - - let cache_dir = runtime_cache_dir()?; - let version_marker = cache_dir.join(".version"); - let cache_key = runtime_cache_key(); - - if version_marker.exists() - && let Ok(cached_key) = fs::read_to_string(&version_marker) - && cached_key.trim() == cache_key - && validate_runtime_dir(&cache_dir).is_ok() - { - return Ok(cache_dir); - } - - cleanup_old_versions(&cache_dir)?; - - if cache_dir.exists() { - fs::remove_dir_all(&cache_dir) - .map_err(|e| format!("remove old runtime cache {}: {e}", cache_dir.display()))?; - } - fs::create_dir_all(&cache_dir) - .map_err(|e| format!("create runtime cache {}: {e}", cache_dir.display()))?; - - extract_resource(resources::LIBKRUN, &cache_dir.join(resources::LIBKRUN_NAME))?; - extract_resource( - resources::LIBKRUNFW, - &cache_dir.join(resources::LIBKRUNFW_NAME), - )?; - - #[cfg(target_os = "macos")] - { - let unversioned = cache_dir.join("libkrunfw.dylib"); - if !unversioned.exists() { - std::os::unix::fs::symlink(resources::LIBKRUNFW_NAME, &unversioned) - .map_err(|e| format!("symlink {}: {e}", unversioned.display()))?; - } - } - - fs::write(&version_marker, cache_key) - .map_err(|e| format!("write runtime marker {}: {e}", version_marker.display()))?; - - Ok(cache_dir) -} - -pub fn validate_runtime_dir(dir: &Path) -> Result<(), String> { - let libkrun = dir.join(resources::LIBKRUN_NAME); - let libkrunfw = dir.join(resources::LIBKRUNFW_NAME); - for path in [&libkrun, &libkrunfw] { - if !path.is_file() { - return Err(format!("missing runtime file: {}", path.display())); - } - let size = fs::metadata(path).map_or(0, |m| m.len()); - if size == 0 { - return Err(format!("runtime file is empty (stub): {}", path.display())); - } - } - - Ok(()) -} - -fn runtime_cache_key() -> String { - let mut fp: u64 = 0; - for (index, chunk) in [resources::LIBKRUN, resources::LIBKRUNFW] - .into_iter() - .enumerate() - { - let sample = &chunk[..chunk.len().min(64)]; - let mut word: u64 = 0; - for (offset, byte) in sample.iter().enumerate() { - word ^= u64::from(*byte) << ((offset % 8) * 8); - } - let index_u32 = u32::try_from(index).unwrap_or(u32::MAX); - fp ^= word.rotate_left(index_u32 * 13 + 7); - fp ^= (chunk.len() as u64).rotate_left(index_u32 * 17 + 3); - } - format!("{VERSION}-{fp:016x}") -} - -fn runtime_cache_dir() -> Result { - let base = - openshell_core::paths::xdg_data_dir().map_err(|e| format!("resolve XDG data dir: {e}"))?; - Ok(base.join("openshell").join("vm-runtime").join(VERSION)) -} - -fn runtime_cache_base() -> Result { - let base = - openshell_core::paths::xdg_data_dir().map_err(|e| format!("resolve XDG data dir: {e}"))?; - Ok(base.join("openshell").join("vm-runtime")) -} - -fn cleanup_old_versions(current_dir: &Path) -> Result<(), String> { - let base = runtime_cache_base()?; - if !base.exists() { - return Ok(()); - } - - let entries = fs::read_dir(&base).map_err(|e| format!("read {}: {e}", base.display()))?; - for entry in entries.filter_map(Result::ok) { - let path = entry.path(); - if path.is_dir() && !current_dir.starts_with(&path) && path != current_dir { - let _ = fs::remove_dir_all(&path); - } - } - Ok(()) -} - -fn extract_resource(compressed: &[u8], dest: &Path) -> Result<(), String> { - if compressed.is_empty() { - return Err(format!("embedded resource is empty: {}", dest.display())); - } - - let decompressed = - zstd::decode_all(compressed).map_err(|e| format!("decompress {}: {e}", dest.display()))?; - fs::write(dest, decompressed).map_err(|e| format!("write {}: {e}", dest.display())) -} diff --git a/crates/openshell-driver-vm/src/extensions/mod.rs b/crates/openshell-driver-vm/src/extensions/mod.rs deleted file mode 100644 index 86d3464697..0000000000 --- a/crates/openshell-driver-vm/src/extensions/mod.rs +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Concrete implementations of [`crate::lifecycle::LifecycleExtension`]. -//! -//! The framework itself — the trait, registry, launch plan, descriptor, -//! and backend-feature resolver — lives in [`crate::lifecycle`]. This -//! module is the conventional home for concrete extensions that -//! implement the trait. -//! -//! # Conventions for a new extension -//! -//! - Each extension lives in its own submodule: -//! `crates/openshell-driver-vm/src/extensions//mod.rs`. -//! - The submodule exposes a single public type -//! `Extension` (e.g. `VfioPassthroughExtension`) that -//! implements [`crate::lifecycle::LifecycleExtension`]. -//! - Helpers (pool allocators, guest env builders, on-disk state -//! layouts) live alongside the extension in private modules within -//! the same directory. -//! - The extension's [`crate::lifecycle::LifecycleExtension::name`] -//! must match `` (kebab-case ASCII). The driver creates -//! per-extension state at -//! `/extensions//` for hooks to use. -//! - Re-export the extension type from this `mod.rs` so callers can -//! write `use openshell_driver_vm::extensions::VfioPassthroughExtension;`. -//! -//! New extension types are wired into a running driver by registering -//! them with [`crate::lifecycle::LifecycleExtensionRegistry`] and passing -//! the registry to [`crate::VmDriver::new_with_extensions`]. diff --git a/crates/openshell-driver-vm/src/ffi.rs b/crates/openshell-driver-vm/src/ffi.rs deleted file mode 100644 index db1deb619c..0000000000 --- a/crates/openshell-driver-vm/src/ffi.rs +++ /dev/null @@ -1,214 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Minimal runtime-loaded bindings for the libkrun C API used by the VM driver. - -#![allow(unsafe_code)] - -use std::ffi::{CStr, CString}; -use std::path::{Path, PathBuf}; -use std::sync::OnceLock; - -use libc::c_char; -use libloading::Library; - -use crate::runtime::validate_runtime_dir; - -pub const KRUN_LOG_TARGET_DEFAULT: i32 = -1; -pub const KRUN_LOG_LEVEL_OFF: u32 = 0; -pub const KRUN_LOG_LEVEL_ERROR: u32 = 1; -pub const KRUN_LOG_LEVEL_WARN: u32 = 2; -pub const KRUN_LOG_LEVEL_INFO: u32 = 3; -pub const KRUN_LOG_LEVEL_DEBUG: u32 = 4; -pub const KRUN_LOG_LEVEL_TRACE: u32 = 5; -pub const KRUN_LOG_STYLE_AUTO: u32 = 0; -pub const KRUN_LOG_OPTION_NO_ENV: u32 = 1; - -type KrunInitLog = - unsafe extern "C" fn(target_fd: i32, level: u32, style: u32, options: u32) -> i32; -type KrunCreateCtx = unsafe extern "C" fn() -> i32; -type KrunFreeCtx = unsafe extern "C" fn(ctx_id: u32) -> i32; -type KrunSetVmConfig = unsafe extern "C" fn(ctx_id: u32, num_vcpus: u8, ram_mib: u32) -> i32; -type KrunAddDisk = unsafe extern "C" fn( - ctx_id: u32, - block_id: *const c_char, - disk_path: *const c_char, - read_only: bool, -) -> i32; -type KrunSetRootDiskRemount = unsafe extern "C" fn( - ctx_id: u32, - device: *const c_char, - fstype: *const c_char, - options: *const c_char, -) -> i32; -type KrunSetWorkdir = unsafe extern "C" fn(ctx_id: u32, workdir_path: *const c_char) -> i32; -type KrunSetExec = unsafe extern "C" fn( - ctx_id: u32, - exec_path: *const c_char, - argv: *const *const c_char, - envp: *const *const c_char, -) -> i32; -type KrunSetConsoleOutput = unsafe extern "C" fn(ctx_id: u32, filepath: *const c_char) -> i32; -type KrunStartEnter = unsafe extern "C" fn(ctx_id: u32) -> i32; -type KrunDisableImplicitVsock = unsafe extern "C" fn(ctx_id: u32) -> i32; -type KrunAddVsock = unsafe extern "C" fn(ctx_id: u32, tsi_features: u32) -> i32; -type KrunAddVsockPort2 = - unsafe extern "C" fn(ctx_id: u32, port: u32, filepath: *const c_char, listen: bool) -> i32; -type KrunAddVirtiofs4 = unsafe extern "C" fn( - ctx_id: u32, - tag: *const c_char, - path: *const c_char, - shm_size: u64, - read_only: bool, - semantics: u32, -) -> i32; - -// Field names mirror the libkrun C API symbol names (`krun_*`); preserving -// the prefix keeps the FFI binding 1:1 with the upstream library. -#[allow(clippy::struct_field_names)] -pub struct LibKrun { - pub krun_init_log: KrunInitLog, - pub krun_create_ctx: KrunCreateCtx, - pub krun_free_ctx: KrunFreeCtx, - pub krun_set_vm_config: KrunSetVmConfig, - pub krun_add_disk: KrunAddDisk, - pub krun_set_root_disk_remount: KrunSetRootDiskRemount, - pub krun_set_workdir: KrunSetWorkdir, - pub krun_set_exec: KrunSetExec, - pub krun_set_console_output: KrunSetConsoleOutput, - pub krun_start_enter: KrunStartEnter, - pub krun_disable_implicit_vsock: KrunDisableImplicitVsock, - pub krun_add_vsock: KrunAddVsock, - pub krun_add_vsock_port2: KrunAddVsockPort2, - /// Load error kept so runtimes without virtiofs still boot sandboxes - /// that request no bind mounts, and mount requests report why. - pub krun_add_virtiofs4: Result, -} - -static LIBKRUN: OnceLock = OnceLock::new(); - -pub fn libkrun(runtime_dir: &Path) -> Result<&'static LibKrun, String> { - if let Some(lib) = LIBKRUN.get() { - return Ok(lib); - } - - validate_runtime_dir(runtime_dir)?; - let loaded = LibKrun::load(runtime_dir)?; - let _ = LIBKRUN.set(loaded); - Ok(LIBKRUN.get().expect("libkrun should be initialized")) -} - -pub fn required_runtime_lib_name() -> &'static str { - #[cfg(target_os = "macos")] - { - "libkrun.dylib" - } - #[cfg(not(target_os = "macos"))] - { - "libkrun.so" - } -} - -impl LibKrun { - fn load(runtime_dir: &Path) -> Result { - let libkrun_path = runtime_dir.join(required_runtime_lib_name()); - preload_runtime_support_libraries(runtime_dir)?; - - let library = Box::leak(Box::new(unsafe { - Library::new(&libkrun_path) - .map_err(|e| format!("load libkrun from {}: {e}", libkrun_path.display()))? - })); - - Ok(Self { - krun_init_log: load_symbol(library, b"krun_init_log\0", &libkrun_path)?, - krun_create_ctx: load_symbol(library, b"krun_create_ctx\0", &libkrun_path)?, - krun_free_ctx: load_symbol(library, b"krun_free_ctx\0", &libkrun_path)?, - krun_set_vm_config: load_symbol(library, b"krun_set_vm_config\0", &libkrun_path)?, - krun_add_disk: load_symbol(library, b"krun_add_disk\0", &libkrun_path)?, - krun_set_root_disk_remount: load_symbol( - library, - b"krun_set_root_disk_remount\0", - &libkrun_path, - )?, - krun_set_workdir: load_symbol(library, b"krun_set_workdir\0", &libkrun_path)?, - krun_set_exec: load_symbol(library, b"krun_set_exec\0", &libkrun_path)?, - krun_set_console_output: load_symbol( - library, - b"krun_set_console_output\0", - &libkrun_path, - )?, - krun_start_enter: load_symbol(library, b"krun_start_enter\0", &libkrun_path)?, - krun_disable_implicit_vsock: load_symbol( - library, - b"krun_disable_implicit_vsock\0", - &libkrun_path, - )?, - krun_add_vsock: load_symbol(library, b"krun_add_vsock\0", &libkrun_path)?, - krun_add_vsock_port2: load_symbol(library, b"krun_add_vsock_port2\0", &libkrun_path)?, - krun_add_virtiofs4: load_symbol(library, b"krun_add_virtiofs4\0", &libkrun_path), - }) - } -} - -fn preload_runtime_support_libraries(runtime_dir: &Path) -> Result, String> { - let entries = std::fs::read_dir(runtime_dir) - .map_err(|e| format!("read {}: {e}", runtime_dir.display()))?; - - let mut support_libs: Vec = entries - .filter_map(Result::ok) - .map(|entry| entry.path()) - .filter(|path| { - path.file_name() - .and_then(|name| name.to_str()) - .is_some_and(|name| { - #[cfg(target_os = "macos")] - { - name.starts_with("libkrunfw") - && Path::new(name) - .extension() - .is_some_and(|ext| ext.eq_ignore_ascii_case("dylib")) - } - #[cfg(not(target_os = "macos"))] - { - name.starts_with("libkrunfw") && name.contains(".so") - } - }) - }) - .collect(); - - support_libs.sort(); - for path in &support_libs { - let path_cstr = CString::new(path.to_string_lossy().as_bytes()) - .map_err(|e| format!("invalid support library path {}: {e}", path.display()))?; - let handle = - unsafe { libc::dlopen(path_cstr.as_ptr(), libc::RTLD_NOW | libc::RTLD_GLOBAL) }; - if handle.is_null() { - let error = unsafe { - let err = libc::dlerror(); - if err.is_null() { - "unknown dlopen error".to_string() - } else { - CStr::from_ptr(err).to_string_lossy().into_owned() - } - }; - return Err(format!( - "preload runtime support library {}: {error}", - path.display() - )); - } - } - - Ok(support_libs) -} - -fn load_symbol(library: &'static Library, name: &[u8], path: &Path) -> Result { - unsafe { - library.get::(name).map(|symbol| *symbol).map_err(|e| { - format!( - "load symbol {} from {}: {e}", - String::from_utf8_lossy(name).trim_end_matches('\0'), - path.display() - ) - }) - } -} diff --git a/crates/openshell-driver-vm/src/gpu.rs b/crates/openshell-driver-vm/src/gpu.rs deleted file mode 100644 index e7b0233fdf..0000000000 --- a/crates/openshell-driver-vm/src/gpu.rs +++ /dev/null @@ -1,173 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use openshell_vfio::{ - GpuBindGuard, GpuBindState, GpuBinding, GpuInfo, SysfsRoot, prepare_gpu_for_passthrough, - probe_host_nvidia_vfio_readiness, reconcile_stale_bindings, validate_bdf, -}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU32, Ordering}; - -/// Tracks available GPUs and their assignment to sandboxes. -pub struct GpuInventory { - slots: Vec, - sysfs: SysfsRoot, - state_path: PathBuf, -} - -struct GpuSlot { - info: GpuInfo, - assigned_to: Option, - bind_guard: Option, -} - -impl GpuInventory { - pub fn new(sysfs: SysfsRoot, state_dir: &Path) -> Self { - let state_path = state_dir.join("gpu-bindings.json"); - - let restored = reconcile_stale_bindings(&sysfs, &state_path); - for bdf in &restored { - tracing::info!(bdf = %bdf, "restored stale GPU binding from previous crash"); - } - - let gpus = probe_host_nvidia_vfio_readiness(&sysfs); - let slots = gpus - .into_iter() - .map(|info| GpuSlot { - info, - assigned_to: None, - bind_guard: None, - }) - .collect(); - - Self { - slots, - sysfs, - state_path, - } - } - - pub fn gpu_count(&self) -> u32 { - u32::try_from(self.slots.len()).unwrap_or(u32::MAX) - } - - pub fn available_count(&self) -> u32 { - u32::try_from( - self.slots - .iter() - .filter(|s| s.assigned_to.is_none()) - .count(), - ) - .unwrap_or(u32::MAX) - } - - /// Assign a GPU to a sandbox. Returns the assignment details including BDF. - pub fn assign(&mut self, sandbox_id: &str, gpu_device: &str) -> Result { - let slot_idx = if gpu_device.is_empty() { - self.slots - .iter() - .position(|s| s.assigned_to.is_none()) - .ok_or_else(|| "all GPUs are currently assigned to other sandboxes".to_string())? - } else if let Ok(idx) = gpu_device.parse::() { - if idx >= self.slots.len() { - return Err(format!( - "GPU index {idx} out of range (have {} GPUs)", - self.slots.len() - )); - } - if self.slots[idx].assigned_to.is_some() { - return Err(format!( - "GPU at index {idx} ({}) is already assigned to another sandbox", - self.slots[idx].info.bdf - )); - } - idx - } else { - validate_bdf(gpu_device).map_err(|e| e.to_string())?; - let idx = self - .slots - .iter() - .position(|s| s.info.bdf == gpu_device) - .ok_or_else(|| format!("GPU {gpu_device} not found in inventory"))?; - if self.slots[idx].assigned_to.is_some() { - return Err(format!( - "GPU {gpu_device} is already assigned to another sandbox" - )); - } - idx - }; - - let bdf = self.slots[slot_idx].info.bdf.clone(); - let guard = prepare_gpu_for_passthrough(&self.sysfs, &bdf) - .map_err(|e| format!("failed to prepare GPU {bdf} for passthrough: {e}"))?; - - self.slots[slot_idx].assigned_to = Some(sandbox_id.to_string()); - self.slots[slot_idx].bind_guard = Some(guard); - self.persist_state(); - - Ok(GpuAssignment { - bdf, - name: self.slots[slot_idx].info.name.clone(), - iommu_group: self.slots[slot_idx].info.iommu_group, - }) - } - - /// Release a GPU assignment. The `GpuBindGuard` is dropped, restoring the GPU. - pub fn release(&mut self, sandbox_id: &str) { - if let Some(slot) = self - .slots - .iter_mut() - .find(|s| s.assigned_to.as_deref() == Some(sandbox_id)) - { - let bdf = slot.info.bdf.clone(); - slot.assigned_to = None; - slot.bind_guard.take(); - self.persist_state(); - tracing::info!(bdf = %bdf, sandbox_id = %sandbox_id, "released GPU assignment"); - } - } - - fn persist_state(&self) { - let bindings: Vec = self - .slots - .iter() - .filter_map(|s| { - s.assigned_to.as_ref().map(|id| GpuBinding { - bdf: s.info.bdf.clone(), - sandbox_id: id.clone(), - bound_at_ms: std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX)), - }) - }) - .collect(); - let state = GpuBindState { bindings }; - if let Err(err) = state.save(&self.state_path) { - tracing::warn!(error = %err, "failed to persist GPU bind state"); - } - } -} - -pub struct GpuAssignment { - pub bdf: String, - pub name: String, - pub iommu_group: u32, -} - -static NEXT_VSOCK_CID: AtomicU32 = AtomicU32::new(3); - -pub fn allocate_vsock_cid() -> u32 { - NEXT_VSOCK_CID.fetch_add(1, Ordering::Relaxed) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn vsock_cid_increments() { - let cid1 = allocate_vsock_cid(); - let cid2 = allocate_vsock_cid(); - assert_eq!(cid2, cid1 + 1); - } -} diff --git a/crates/openshell-driver-vm/src/isolation/mod.rs b/crates/openshell-driver-vm/src/isolation/mod.rs deleted file mode 100644 index f52456b50e..0000000000 --- a/crates/openshell-driver-vm/src/isolation/mod.rs +++ /dev/null @@ -1,248 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! VM provisioning for the shared authenticated boundary protocol. -//! -//! This module deliberately contains no lifecycle, process, network, or wire -//! implementation. The driver chooses the host transport and binds immutable -//! VM claims; `openshell-isolation-interface` and `openshell-sandbox` provide -//! the common control and boundary behavior. - -use openshell_isolation_interface::contract::{ - BackendError, ProvisioningEvidence, ResolvedWorkloadIdentity, -}; -use openshell_sandbox_backend::GPU_RESOURCE_CLAIM; -use openshell_sandbox_backend::boundary_protocol::{ - BoundaryConfig, BoundaryListener, GatewayVerificationKey, SandboxRuntimeDescriptor, - SandboxTlsClientConfig, SandboxTlsServerConfig, SandboxTransport, -}; -use serde::Serialize; -use std::collections::{BTreeMap, HashMap}; - -#[derive(Serialize)] -struct VmOuterFenceEvidence<'a> { - generation: &'a str, - network_device_count: u32, -} - -impl VmOuterFenceEvidence<'_> { - fn project(&self) -> Result { - if self.generation.is_empty() || self.network_device_count != 0 { - return Err(BackendError::Descriptor( - "VM provisioning evidence is incomplete".to_string(), - )); - } - let encoded = serde_json::to_vec(self).map_err(|error| { - BackendError::Descriptor(format!("encode VM outer fence evidence: {error}")) - })?; - let projection = - ProvisioningEvidence::from_enforcement_evidence(self.generation, &encoded)?; - projection.validate(self.generation)?; - Ok(projection) - } -} - -/// Driver-owned inputs that bind one VM generation to one supervisor boundary. -pub struct VmBoundarySpec { - pub boundary_id: String, - pub generation: String, - pub session_id: openshell_core::SandboxSessionId, - pub session_rotation: openshell_core::jwt::SessionRotation, - pub auth_epoch: openshell_core::jwt::CredentialEpoch, - pub gateway_id: String, - pub verification_keys: Vec, - pub image_identity: String, - pub transport: SandboxTransport, - pub supervisor_tls: SandboxTlsClientConfig, - pub sandbox_tls: SandboxTlsServerConfig, - pub control_port: u32, - pub agent_uid: u32, - pub agent_gid: u32, - pub child_env: HashMap, - pub gpu_requested: bool, -} - -/// The protected guest config and matching host descriptor for one VM. -pub struct VmBoundaryProvisioning { - pub boundary_config: BoundaryConfig, - pub runtime_descriptor: SandboxRuntimeDescriptor, -} - -impl VmBoundarySpec { - /// Produce both sides of the common protocol from one set of immutable - /// driver inputs so their identity claims cannot drift. - pub fn provision(self) -> Result { - let workload_identity = ResolvedWorkloadIdentity::new( - self.agent_uid, - self.agent_gid, - Vec::new(), - "vm-config".to_string(), - self.image_identity.clone(), - )?; - let mut resource_claims = BTreeMap::from([ - ("vm.generation".to_string(), self.generation.clone()), - ("vm.image_identity".to_string(), self.image_identity), - ]); - if self.gpu_requested { - resource_claims.insert(GPU_RESOURCE_CLAIM.to_string(), "true".to_string()); - } - let provisioning_evidence = VmOuterFenceEvidence { - generation: &self.generation, - network_device_count: 0, - } - .project()?; - Ok(VmBoundaryProvisioning { - boundary_config: BoundaryConfig { - boundary_id: self.boundary_id.clone(), - generation: self.generation.clone(), - session_id: self.session_id, - session_rotation: self.session_rotation, - auth_epoch: self.auth_epoch, - gateway_id: self.gateway_id, - verification_keys: self.verification_keys, - listener: match &self.transport { - SandboxTransport::RuntimeInitiatedVsock { port, .. } => { - BoundaryListener::RuntimeInitiatedVsock { - host_port: *port, - tls: self.sandbox_tls, - } - } - SandboxTransport::RuntimeInitiatedUnix { .. } => { - BoundaryListener::RuntimeInitiatedVsock { - host_port: self.control_port, - tls: self.sandbox_tls, - } - } - _ => BoundaryListener::Vsock { - control_port: self.control_port, - tls: self.sandbox_tls, - }, - }, - resource_claims: resource_claims.clone(), - resource_claim_files: BTreeMap::new(), - workload_identity: workload_identity.clone(), - provisioning_evidence: provisioning_evidence.clone(), - child_env: self.child_env, - }, - runtime_descriptor: SandboxRuntimeDescriptor { - boundary_id: self.boundary_id, - generation: self.generation, - session_id: self.session_id, - workload_identity, - transport: self.transport, - tls: self.supervisor_tls, - // The host-side control process is the network broker, so - // reserved host aliases terminate at its loopback address - // after crossing the authenticated boundary channel. - host_gateway_ip: Some(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)), - resource_claims, - provisioning_evidence, - }, - }) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use openshell_sandbox_backend::boundary_protocol::{ - SandboxTlsClientConfig, SandboxTlsServerConfig, SandboxTransport, - generate_sandbox_tls_material, - }; - - #[test] - fn outer_fence_projection_rejects_each_missing_native_fact() { - assert!( - VmOuterFenceEvidence { - generation: "", - network_device_count: 0, - } - .project() - .is_err() - ); - assert!( - VmOuterFenceEvidence { - generation: "generation-1", - network_device_count: 1, - } - .project() - .is_err() - ); - } - - #[test] - fn provisioning_binds_identical_resource_claims() { - for gpu_requested in [false, true] { - assert_provisioning_claims(gpu_requested); - } - } - - fn assert_provisioning_claims(gpu_requested: bool) { - let session_id = openshell_core::SandboxSessionId::new(); - let material = generate_sandbox_tls_material(session_id).unwrap(); - let provisioned = VmBoundarySpec { - boundary_id: "sandbox-1".to_string(), - generation: "generation-1".to_string(), - session_id, - session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), - auth_epoch: openshell_core::jwt::CredentialEpoch::new(1).unwrap(), - gateway_id: "gateway-1".to_string(), - verification_keys: vec![GatewayVerificationKey { - key_id: "key-1".to_string(), - public_key_pem: "public-key".to_string(), - }], - image_identity: "sha256:image".to_string(), - transport: SandboxTransport::Vsock { - guest_cid: 42, - port: 5500, - }, - supervisor_tls: SandboxTlsClientConfig { - server_name: material.server_name, - trust_anchor_pem: material.trust_anchor_pem, - }, - sandbox_tls: SandboxTlsServerConfig { - certificate_chain_path: "/.openshell/state/sandbox.crt".into(), - private_key_path: "/.openshell/state/sandbox.key".into(), - }, - control_port: 5500, - agent_uid: 1000, - agent_gid: 1000, - child_env: HashMap::new(), - gpu_requested, - } - .provision() - .unwrap(); - - assert_eq!( - provisioned.boundary_config.resource_claims, - provisioned.runtime_descriptor.resource_claims - ); - assert_eq!( - provisioned - .runtime_descriptor - .resource_claims - .get(GPU_RESOURCE_CLAIM) - .map(String::as_str), - gpu_requested.then_some("true") - ); - assert_eq!( - provisioned.runtime_descriptor.resource_claims["vm.generation"], - "generation-1" - ); - assert_eq!( - provisioned.runtime_descriptor.host_gateway_ip, - Some(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)) - ); - assert_eq!( - provisioned.boundary_config.provisioning_evidence, - provisioned.runtime_descriptor.provisioning_evidence - ); - assert!( - provisioned - .runtime_descriptor - .provisioning_evidence - .validate("generation-1") - .is_ok() - ); - } -} diff --git a/crates/openshell-driver-vm/src/layer_applier.rs b/crates/openshell-driver-vm/src/layer_applier.rs deleted file mode 100644 index 42c21afbf6..0000000000 --- a/crates/openshell-driver-vm/src/layer_applier.rs +++ /dev/null @@ -1,913 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Applies extracted OCI layers to a VM root filesystem. - -use std::collections::VecDeque; -use std::ffi::OsString; -use std::fs; -use std::io::{self, Read, Write as _}; -#[cfg(unix)] -use std::os::unix::ffi::OsStrExt as _; -#[cfg(unix)] -use std::os::unix::fs::PermissionsExt; -use std::path::{Component, Path, PathBuf}; - -const MIN_ENTRY_BYTES: u64 = 4096; - -/// Both limits span every layer of one bootstrap build. Tar headers and padding -/// consume decoded bytes. Sparse holes and copies of hard links consume output -/// bytes even when there is little or no corresponding data in the tar. -pub struct BootstrapExtractionBudget { - limit: u64, - decoded_left: u64, - output_left: u64, -} - -impl BootstrapExtractionBudget { - pub fn new(limit: u64) -> Self { - Self { - limit, - decoded_left: limit, - output_left: limit, - } - } - - fn exceeded(&self, kind: &str) -> io::Error { - io::Error::other(format!( - "bootstrap extraction limit of {} bytes exceeded for {kind}", - self.limit - )) - } - - fn reserve_entry(&mut self, bytes: u64) -> io::Result<()> { - self.output_left = self - .output_left - .checked_sub(bytes.max(MIN_ENTRY_BYTES)) - .ok_or_else(|| self.exceeded("filesystem output"))?; - Ok(()) - } - - pub fn unpack_tar(&mut self, reader: impl Read, dest: &Path) -> io::Result<()> { - fs::create_dir_all(dest)?; - let dest = dest.canonicalize()?; - let mut input = reader.take(self.decoded_left); - let unpack = self.unpack_entries(&mut tar::Archive::new(&mut input), &dest); - if unpack.is_ok() { - // The tar parser stops at the first end marker. Account for padding, - // trailing data and concatenated compression frames through EOF. - io::copy(&mut input, &mut io::sink())?; - } - self.decoded_left = input.limit(); - if self.decoded_left == 0 && input.into_inner().read(&mut [0])? != 0 { - return Err(self.exceeded("decoded layer tars")); - } - unpack - } - - fn unpack_entries( - &mut self, - archive: &mut tar::Archive, - dest: &Path, - ) -> io::Result<()> { - // Match Archive::unpack: validate each path with unpack_in and apply - // directory modes after descendants, deepest first. - let mut directories = Vec::new(); - for entry in archive.entries()? { - let mut entry = entry?; - let kind = entry.header().entry_type(); - if kind.is_pax_global_extensions() - || kind.is_pax_local_extensions() - || kind.is_gnu_longname() - || kind.is_gnu_longlink() - { - continue; - } - // unpack_in can create every parent of a member, even if the tar - // has no entries for those directories. Reserve before it writes. - for _ in entry - .path()? - .components() - .filter(|c| matches!(c, Component::Normal(_))) - .skip(1) - { - self.reserve_entry(0)?; - } - let bytes = if kind.is_symlink() { - entry - .link_name_bytes() - .map_or(0, |target| target.len() as u64) - } else if kind.is_dir() { - 0 - } else { - // tar resolves PAX size overrides and GNU sparse extents here. - entry.size() - }; - self.reserve_entry(bytes)?; - if kind.is_dir() { - directories.push(entry); - } else { - entry.unpack_in(dest)?; - } - } - directories.sort_by(|a, b| b.path_bytes().cmp(&a.path_bytes())); - for mut directory in directories { - directory.unpack_in(dest)?; - } - Ok(()) - } - - pub fn apply_layer(&mut self, layer_root: &Path, rootfs: &Path) -> Result<(), String> { - LayerApplier::new(rootfs)?.apply(layer_root, self) - } -} - -/// Owns all filesystem mutations performed while merging an extracted OCI -/// layer into a rootfs. -/// -/// Keeping the mutation boundary here makes the distinction between symlinks -/// supplied by the current layer and directory symlinks retained from lower -/// layers explicit. The latter are followed only through a -/// [`DirectoryMergePlan::FollowLowerLayerSymlink`] decision. -struct LayerApplier { - rootfs: PathBuf, - #[cfg(unix)] - root_dir: rustix::fd::OwnedFd, -} - -#[cfg(not(unix))] -#[derive(Debug)] -enum DirectoryMergePlan { - CreateDirectory { path: PathBuf }, - MergeDirectory { path: PathBuf }, - FollowLowerLayerSymlink { target: PathBuf }, - ReplaceLowerLayerEntry { path: PathBuf }, -} - -#[cfg(not(unix))] -impl DirectoryMergePlan { - fn path(&self) -> &Path { - match self { - Self::CreateDirectory { path } - | Self::MergeDirectory { path } - | Self::ReplaceLowerLayerEntry { path } => path, - Self::FollowLowerLayerSymlink { target, .. } => target, - } - } - - fn applies_directory_metadata(&self) -> bool { - !matches!(self, Self::FollowLowerLayerSymlink { .. }) - } -} - -#[cfg(unix)] -struct ResolvedDirectory { - fd: rustix::fd::OwnedFd, - components: Vec, -} - -#[cfg(unix)] -enum DirectoryMergePlan { - CreateDirectory, - MergeDirectory(ResolvedDirectory), - FollowLowerLayerSymlink(ResolvedDirectory), - ReplaceLowerLayerEntry, -} - -impl LayerApplier { - fn new(rootfs: &Path) -> Result { - fs::create_dir_all(rootfs).map_err(|err| format!("create {}: {err}", rootfs.display()))?; - let rootfs = fs::canonicalize(rootfs) - .map_err(|err| format!("canonicalize rootfs {}: {err}", rootfs.display()))?; - #[cfg(unix)] - let root_dir = rustix::fs::open( - &rootfs, - rustix::fs::OFlags::RDONLY - | rustix::fs::OFlags::DIRECTORY - | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC, - rustix::fs::Mode::empty(), - ) - .map_err(|err| format!("open rootfs {}: {err}", rootfs.display()))?; - Ok(Self { - rootfs, - #[cfg(unix)] - root_dir, - }) - } - - fn apply( - &self, - layer_root: &Path, - budget: &mut BootstrapExtractionBudget, - ) -> Result<(), String> { - #[cfg(unix)] - { - let root = ResolvedDirectory { - fd: self.open_root_dir()?, - components: Vec::new(), - }; - self.merge_directory(layer_root, &root, budget) - } - #[cfg(not(unix))] - { - self.merge_directory(layer_root, &self.rootfs, budget) - } - } - - #[cfg(not(unix))] - fn merge_directory( - &self, - source_dir: &Path, - target_dir: &Path, - budget: &mut BootstrapExtractionBudget, - ) -> Result<(), String> { - fs::create_dir_all(target_dir) - .map_err(|err| format!("create {}: {err}", target_dir.display()))?; - - let mut entries = fs::read_dir(source_dir) - .map_err(|err| format!("read {}: {err}", source_dir.display()))? - .collect::, _>>() - .map_err(|err| format!("read {}: {err}", source_dir.display()))?; - entries.sort_by_key(fs::DirEntry::file_name); - - if entries - .iter() - .any(|entry| entry.file_name().to_string_lossy() == ".wh..wh..opq") - { - self.clear_directory_contents(target_dir)?; - } - - for entry in entries { - let file_name = entry.file_name(); - let name = file_name.to_string_lossy(); - if name == ".wh..wh..opq" { - continue; - } - if let Some(hidden_name) = name.strip_prefix(".wh.") { - self.remove_path_if_exists(&target_dir.join(hidden_name))?; - continue; - } - - let source_path = entry.path(); - let dest_path = target_dir.join(&file_name); - let metadata = fs::symlink_metadata(&source_path) - .map_err(|err| format!("stat {}: {err}", source_path.display()))?; - let file_type = metadata.file_type(); - let bytes = if file_type.is_dir() { - 0 - } else { - metadata.len() - }; - budget.reserve_entry(bytes).map_err(|err| err.to_string())?; - - if file_type.is_dir() { - let plan = self.plan_directory_merge(&dest_path)?; - if matches!(plan, DirectoryMergePlan::ReplaceLowerLayerEntry { .. }) { - self.remove_path_if_exists(plan.path())?; - } - fs::create_dir_all(plan.path()) - .map_err(|err| format!("create {}: {err}", plan.path().display()))?; - self.merge_directory(&source_path, plan.path(), budget)?; - if plan.applies_directory_metadata() { - fs::set_permissions(plan.path(), metadata.permissions()) - .map_err(|err| format!("chmod {}: {err}", plan.path().display()))?; - } - } else if file_type.is_file() { - self.remove_path_if_exists(&dest_path)?; - if let Some(parent) = dest_path.parent() { - fs::create_dir_all(parent) - .map_err(|err| format!("create {}: {err}", parent.display()))?; - } - fs::copy(&source_path, &dest_path).map_err(|err| { - format!( - "copy {} to {}: {err}", - source_path.display(), - dest_path.display() - ) - })?; - fs::set_permissions(&dest_path, metadata.permissions()) - .map_err(|err| format!("chmod {}: {err}", dest_path.display()))?; - } else if file_type.is_symlink() { - self.copy_symlink(&source_path, &dest_path)?; - } else { - return Err(format!( - "unsupported layer entry type at {}", - source_path.display() - )); - } - } - - Ok(()) - } - - #[cfg(unix)] - fn merge_directory( - &self, - source_dir: &Path, - target_dir: &ResolvedDirectory, - budget: &mut BootstrapExtractionBudget, - ) -> Result<(), String> { - let mut entries = fs::read_dir(source_dir) - .map_err(|err| format!("read {}: {err}", source_dir.display()))? - .collect::, _>>() - .map_err(|err| format!("read {}: {err}", source_dir.display()))?; - entries.sort_by_key(fs::DirEntry::file_name); - - if entries - .iter() - .any(|entry| entry.file_name().to_string_lossy() == ".wh..wh..opq") - { - self.clear_directory_contents(target_dir)?; - } - - for entry in entries { - let file_name = entry.file_name(); - let name = file_name.to_string_lossy(); - if name == ".wh..wh..opq" { - continue; - } - if let Some(hidden_name) = name.strip_prefix(".wh.") { - self.remove_entry(target_dir, std::ffi::OsStr::new(hidden_name))?; - continue; - } - - let source_path = entry.path(); - let metadata = fs::symlink_metadata(&source_path) - .map_err(|err| format!("stat {}: {err}", source_path.display()))?; - let file_type = metadata.file_type(); - let bytes = if file_type.is_dir() { - 0 - } else { - metadata.len() - }; - budget.reserve_entry(bytes).map_err(|err| err.to_string())?; - - if file_type.is_dir() { - let plan = self.plan_directory_merge(target_dir, &file_name)?; - let apply_metadata = - !matches!(plan, DirectoryMergePlan::FollowLowerLayerSymlink(_)); - let child = match plan { - DirectoryMergePlan::CreateDirectory => { - self.create_child_directory(target_dir, &file_name)? - } - DirectoryMergePlan::MergeDirectory(directory) - | DirectoryMergePlan::FollowLowerLayerSymlink(directory) => directory, - DirectoryMergePlan::ReplaceLowerLayerEntry => { - self.remove_entry(target_dir, &file_name)?; - self.create_child_directory(target_dir, &file_name)? - } - }; - self.merge_directory(&source_path, &child, budget)?; - if apply_metadata { - rustix::fs::fchmod(&child.fd, Self::mode_from_metadata(&metadata)).map_err( - |err| format!("chmod {}: {err}", self.directory_path(&child).display()), - )?; - } - } else if file_type.is_file() { - self.copy_file(&source_path, target_dir, &file_name, &metadata)?; - } else if file_type.is_symlink() { - self.copy_symlink(&source_path, target_dir, &file_name)?; - } else { - return Err(format!( - "unsupported layer entry type at {}", - source_path.display() - )); - } - } - - Ok(()) - } - - #[cfg(unix)] - fn plan_directory_merge( - &self, - parent: &ResolvedDirectory, - name: &std::ffi::OsStr, - ) -> Result { - let entry_path = self.entry_path(parent, name); - let stat = match rustix::fs::statat(&parent.fd, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) - { - Ok(stat) => stat, - Err(rustix::io::Errno::NOENT) => return Ok(DirectoryMergePlan::CreateDirectory), - Err(err) => return Err(format!("stat {}: {err}", entry_path.display())), - }; - let file_type = rustix::fs::FileType::from_raw_mode(stat.st_mode); - if file_type.is_dir() { - return self - .open_child_directory(parent, name) - .map(DirectoryMergePlan::MergeDirectory); - } - if file_type.is_symlink() { - let mut components = parent.components.clone(); - components.push(name.to_os_string()); - if let Some(directory) = self.resolve_directory(&components)? { - return Ok(DirectoryMergePlan::FollowLowerLayerSymlink(directory)); - } - } - Ok(DirectoryMergePlan::ReplaceLowerLayerEntry) - } - - #[cfg(unix)] - fn open_root_dir(&self) -> Result { - rustix::fs::openat( - &self.root_dir, - ".", - Self::directory_open_flags(), - rustix::fs::Mode::empty(), - ) - .map_err(|err| format!("open rootfs {}: {err}", self.rootfs.display())) - } - - #[cfg(unix)] - fn open_child_directory( - &self, - parent: &ResolvedDirectory, - name: &std::ffi::OsStr, - ) -> Result { - let path = self.entry_path(parent, name); - let fd = rustix::fs::openat( - &parent.fd, - name, - Self::directory_open_flags(), - rustix::fs::Mode::empty(), - ) - .map_err(|err| format!("open directory {}: {err}", path.display()))?; - let mut components = parent.components.clone(); - components.push(name.to_os_string()); - Ok(ResolvedDirectory { fd, components }) - } - - #[cfg(unix)] - fn create_child_directory( - &self, - parent: &ResolvedDirectory, - name: &std::ffi::OsStr, - ) -> Result { - let path = self.entry_path(parent, name); - rustix::fs::mkdirat(&parent.fd, name, rustix::fs::Mode::from_raw_mode(0o700)) - .map_err(|err| format!("create {}: {err}", path.display()))?; - self.open_child_directory(parent, name) - } - - #[cfg(unix)] - fn resolve_directory( - &self, - components: &[OsString], - ) -> Result, String> { - const MAX_SYMLINKS: usize = 40; - - let requested = components - .iter() - .fold(self.rootfs.clone(), |path, component| path.join(component)); - let mut pending = components - .iter() - .cloned() - .map(RootfsPathComponent::Normal) - .collect::>(); - let mut resolved = Vec::::new(); - let mut stack = vec![self.open_root_dir()?]; - let mut symlinks = 0_usize; - - while let Some(component) = pending.pop_front() { - match component { - RootfsPathComponent::Parent => { - if resolved.pop().is_none() { - return Err(format!( - "layer destination {} escapes rootfs {}", - requested.display(), - self.rootfs.display() - )); - } - stack.pop(); - } - RootfsPathComponent::Normal(name) => { - let parent = stack.last().expect("root directory handle remains"); - let candidate = resolved - .iter() - .fold(self.rootfs.clone(), |path, component| path.join(component)) - .join(&name); - let stat = match rustix::fs::statat( - parent, - &name, - rustix::fs::AtFlags::SYMLINK_NOFOLLOW, - ) { - Ok(stat) => stat, - Err(rustix::io::Errno::NOENT | rustix::io::Errno::NOTDIR) => { - return Ok(None); - } - Err(err) => return Err(format!("stat {}: {err}", candidate.display())), - }; - let file_type = rustix::fs::FileType::from_raw_mode(stat.st_mode); - if file_type.is_symlink() { - symlinks += 1; - if symlinks > MAX_SYMLINKS { - return Err(format!( - "too many symlinks while resolving layer destination {}", - requested.display() - )); - } - let target = rustix::fs::readlinkat(parent, &name, Vec::new()) - .map_err(|err| format!("readlink {}: {err}", candidate.display()))?; - let target = Path::new(std::ffi::OsStr::from_bytes(target.to_bytes())); - if target.is_absolute() { - return Err(format!( - "absolute symlink {} -> {} cannot be traversed while applying a layer", - candidate.display(), - target.display() - )); - } - let mut target_components = rootfs_path_components(target)?; - target_components.append(&mut pending); - pending = target_components; - } else if file_type.is_dir() { - let fd = rustix::fs::openat( - parent, - &name, - Self::directory_open_flags(), - rustix::fs::Mode::empty(), - ) - .map_err(|err| format!("open directory {}: {err}", candidate.display()))?; - resolved.push(name); - stack.push(fd); - } else { - return Ok(None); - } - } - } - } - - let fd = stack.pop().expect("resolved directory handle remains"); - Ok(Some(ResolvedDirectory { - fd, - components: resolved, - })) - } - - #[cfg(unix)] - fn copy_file( - &self, - source_path: &Path, - parent: &ResolvedDirectory, - name: &std::ffi::OsStr, - metadata: &fs::Metadata, - ) -> Result<(), String> { - self.remove_entry(parent, name)?; - let path = self.entry_path(parent, name); - let mut source = fs::File::open(source_path) - .map_err(|err| format!("open {}: {err}", source_path.display()))?; - let fd = rustix::fs::openat( - &parent.fd, - name, - rustix::fs::OFlags::WRONLY - | rustix::fs::OFlags::CREATE - | rustix::fs::OFlags::EXCL - | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC, - rustix::fs::Mode::from_raw_mode(0o600), - ) - .map_err(|err| format!("create {}: {err}", path.display()))?; - let mut destination = fs::File::from(fd); - io::copy(&mut source, &mut destination).map_err(|err| { - format!( - "copy {} to {}: {err}", - source_path.display(), - path.display() - ) - })?; - destination - .flush() - .map_err(|err| format!("flush {}: {err}", path.display()))?; - rustix::fs::fchmod(&destination, Self::mode_from_metadata(metadata)) - .map_err(|err| format!("chmod {}: {err}", path.display())) - } - - #[cfg(unix)] - fn clear_directory_contents(&self, directory: &ResolvedDirectory) -> Result<(), String> { - let mut stream = rustix::fs::Dir::read_from(&directory.fd) - .map_err(|err| format!("read {}: {err}", self.directory_path(directory).display()))?; - let mut names = Vec::new(); - for entry in &mut stream { - let entry = entry.map_err(|err| { - format!("read {}: {err}", self.directory_path(directory).display()) - })?; - let name = entry.file_name().to_bytes(); - if name != b"." && name != b".." { - names.push(std::ffi::OsStr::from_bytes(name).to_os_string()); - } - } - for name in names { - self.remove_entry(directory, &name)?; - } - Ok(()) - } - - #[cfg(unix)] - fn remove_entry( - &self, - parent: &ResolvedDirectory, - name: &std::ffi::OsStr, - ) -> Result<(), String> { - let path = self.entry_path(parent, name); - let stat = match rustix::fs::statat(&parent.fd, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) - { - Ok(stat) => stat, - Err(rustix::io::Errno::NOENT) => return Ok(()), - Err(err) => return Err(format!("stat {}: {err}", path.display())), - }; - if rustix::fs::FileType::from_raw_mode(stat.st_mode).is_dir() { - let directory = self.open_child_directory(parent, name)?; - self.clear_directory_contents(&directory)?; - rustix::fs::unlinkat(&parent.fd, name, rustix::fs::AtFlags::REMOVEDIR) - .map_err(|err| format!("remove {}: {err}", path.display())) - } else { - rustix::fs::unlinkat(&parent.fd, name, rustix::fs::AtFlags::empty()) - .map_err(|err| format!("remove {}: {err}", path.display())) - } - } - - #[cfg(unix)] - fn copy_symlink( - &self, - source_path: &Path, - parent: &ResolvedDirectory, - name: &std::ffi::OsStr, - ) -> Result<(), String> { - let target = fs::read_link(source_path) - .map_err(|err| format!("readlink {}: {err}", source_path.display()))?; - self.remove_entry(parent, name)?; - let path = self.entry_path(parent, name); - rustix::fs::symlinkat(&target, &parent.fd, name) - .map_err(|err| format!("symlink {} to {}: {err}", target.display(), path.display())) - } - - #[cfg(unix)] - fn directory_open_flags() -> rustix::fs::OFlags { - rustix::fs::OFlags::RDONLY - | rustix::fs::OFlags::DIRECTORY - | rustix::fs::OFlags::NOFOLLOW - | rustix::fs::OFlags::CLOEXEC - } - - #[cfg(unix)] - fn mode_from_metadata(metadata: &fs::Metadata) -> rustix::fs::Mode { - let raw = metadata.permissions().mode(); - let mut mode = rustix::fs::Mode::empty(); - for (bit, flag) in [ - (0o4000, rustix::fs::Mode::SUID), - (0o2000, rustix::fs::Mode::SGID), - (0o1000, rustix::fs::Mode::SVTX), - (0o0400, rustix::fs::Mode::RUSR), - (0o0200, rustix::fs::Mode::WUSR), - (0o0100, rustix::fs::Mode::XUSR), - (0o0040, rustix::fs::Mode::RGRP), - (0o0020, rustix::fs::Mode::WGRP), - (0o0010, rustix::fs::Mode::XGRP), - (0o0004, rustix::fs::Mode::ROTH), - (0o0002, rustix::fs::Mode::WOTH), - (0o0001, rustix::fs::Mode::XOTH), - ] { - if raw & bit != 0 { - mode |= flag; - } - } - mode - } - - #[cfg(unix)] - fn directory_path(&self, directory: &ResolvedDirectory) -> PathBuf { - directory - .components - .iter() - .fold(self.rootfs.clone(), |path, component| path.join(component)) - } - - #[cfg(unix)] - fn entry_path(&self, parent: &ResolvedDirectory, name: &std::ffi::OsStr) -> PathBuf { - self.directory_path(parent).join(name) - } - - #[cfg(not(unix))] - fn plan_directory_merge(&self, path: &Path) -> Result { - self.ensure_rootfs_destination(path)?; - let metadata = match fs::symlink_metadata(path) { - Ok(metadata) => metadata, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - return Ok(DirectoryMergePlan::CreateDirectory { - path: path.to_path_buf(), - }); - } - Err(err) => return Err(format!("stat {}: {err}", path.display())), - }; - if metadata.file_type().is_dir() { - return Ok(DirectoryMergePlan::MergeDirectory { - path: path.to_path_buf(), - }); - } - if metadata.file_type().is_symlink() { - let target = self.resolve_path_beneath_rootfs(path)?; - match fs::metadata(&target) { - Ok(metadata) if metadata.file_type().is_dir() => { - return Ok(DirectoryMergePlan::FollowLowerLayerSymlink { target }); - } - Ok(_) => {} - Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} - Err(err) => return Err(format!("stat {}: {err}", target.display())), - } - } - Ok(DirectoryMergePlan::ReplaceLowerLayerEntry { - path: path.to_path_buf(), - }) - } - - #[cfg(not(unix))] - fn clear_directory_contents(&self, dir: &Path) -> Result<(), String> { - if !dir.exists() { - return Ok(()); - } - for entry in fs::read_dir(dir).map_err(|err| format!("read {}: {err}", dir.display()))? { - let entry = entry.map_err(|err| format!("read {}: {err}", dir.display()))?; - self.remove_path_if_exists(&entry.path())?; - } - Ok(()) - } - - #[cfg(not(unix))] - fn remove_path_if_exists(&self, path: &Path) -> Result<(), String> { - self.ensure_rootfs_destination(path)?; - let Ok(metadata) = fs::symlink_metadata(path) else { - return Ok(()); - }; - if metadata.file_type().is_dir() { - fs::remove_dir_all(path).map_err(|err| format!("remove {}: {err}", path.display())) - } else { - fs::remove_file(path).map_err(|err| format!("remove {}: {err}", path.display())) - } - } - - #[cfg(not(unix))] - fn ensure_rootfs_destination(&self, path: &Path) -> Result<(), String> { - path.strip_prefix(&self.rootfs).map(|_| ()).map_err(|_| { - format!( - "layer destination {} is outside rootfs {}", - path.display(), - self.rootfs.display() - ) - }) - } - - #[cfg(not(unix))] - fn resolve_path_beneath_rootfs(&self, path: &Path) -> Result { - const MAX_SYMLINKS: usize = 40; - - // A symlink from an earlier OCI layer has container path semantics, - // not ambient access to the host filesystem. Resolve it component by - // component without following it, and reject targets that leave the - // private image staging root before a later layer performs any - // filesystem operation. - let relative = path.strip_prefix(&self.rootfs).map_err(|_| { - format!( - "layer destination {} is outside rootfs {}", - path.display(), - self.rootfs.display() - ) - })?; - let mut pending = rootfs_path_components(relative)?; - let mut resolved = Vec::::new(); - let mut symlinks = 0_usize; - - while let Some(component) = pending.pop_front() { - match component { - RootfsPathComponent::Parent => { - if resolved.pop().is_none() { - return Err(format!( - "layer destination {} escapes rootfs {}", - path.display(), - self.rootfs.display() - )); - } - } - RootfsPathComponent::Normal(name) => { - let candidate = resolved - .iter() - .fold(self.rootfs.clone(), |path, component| path.join(component)) - .join(&name); - match fs::symlink_metadata(&candidate) { - Ok(metadata) if metadata.file_type().is_symlink() => { - symlinks += 1; - if symlinks > MAX_SYMLINKS { - return Err(format!( - "too many symlinks while resolving layer destination {}", - path.display() - )); - } - let target = fs::read_link(&candidate).map_err(|err| { - format!("readlink {}: {err}", candidate.display()) - })?; - if target.is_absolute() { - return Err(format!( - "absolute symlink {} -> {} cannot be traversed while applying a layer", - candidate.display(), - target.display() - )); - } - let mut target_components = rootfs_path_components(&target)?; - target_components.append(&mut pending); - pending = target_components; - } - Ok(_) => resolved.push(name), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => { - resolved.push(name); - } - Err(err) => return Err(format!("stat {}: {err}", candidate.display())), - } - } - } - } - - Ok(resolved - .into_iter() - .fold(self.rootfs.clone(), |path, component| path.join(component))) - } - - #[cfg(not(unix))] - fn copy_symlink(&self, _source_path: &Path, _dest_path: &Path) -> Result<(), String> { - Err("symlink layers are only supported on Unix hosts".to_string()) - } -} - -#[derive(Debug)] -enum RootfsPathComponent { - Parent, - Normal(OsString), -} - -fn rootfs_path_components(path: &Path) -> Result, String> { - path.components() - .filter_map(|component| match component { - Component::CurDir => None, - Component::ParentDir => Some(Ok(RootfsPathComponent::Parent)), - Component::Normal(name) => Some(Ok(RootfsPathComponent::Normal(name.to_os_string()))), - Component::RootDir | Component::Prefix(_) => Some(Err(format!( - "absolute symlink target {} cannot be traversed while applying a layer", - path.display() - ))), - }) - .collect() -} - -#[cfg(all(test, unix))] -mod tests { - use super::{DirectoryMergePlan, LayerApplier, ResolvedDirectory}; - use std::ffi::OsStr; - use std::fs; - use tempfile::tempdir; - - #[test] - fn keeps_using_opened_directory_after_path_replacement() { - let base = tempdir().unwrap(); - let rootfs = base.path().join("rootfs"); - let upper = base.path().join("upper"); - let outside = base.path().join("outside"); - fs::create_dir_all(rootfs.join("pivot")).unwrap(); - fs::create_dir_all(&upper).unwrap(); - fs::create_dir_all(&outside).unwrap(); - fs::write(rootfs.join("pivot/victim"), "inside").unwrap(); - fs::write(outside.join("victim"), "outside").unwrap(); - fs::write(upper.join(".wh..wh..opq"), "").unwrap(); - fs::write(upper.join("payload"), "payload").unwrap(); - - let applier = LayerApplier::new(&rootfs).unwrap(); - let root = ResolvedDirectory { - fd: applier.open_root_dir().unwrap(), - components: Vec::new(), - }; - let DirectoryMergePlan::MergeDirectory(opened) = applier - .plan_directory_merge(&root, OsStr::new("pivot")) - .unwrap() - else { - panic!("expected an existing directory merge"); - }; - - fs::rename(rootfs.join("pivot"), rootfs.join("detached")).unwrap(); - std::os::unix::fs::symlink(&outside, rootfs.join("pivot")).unwrap(); - applier - .merge_directory( - &upper, - &opened, - &mut super::BootstrapExtractionBudget::new(4096), - ) - .unwrap(); - - assert_eq!( - fs::read_to_string(outside.join("victim")).unwrap(), - "outside" - ); - assert!(!outside.join("payload").exists()); - assert_eq!( - fs::read_to_string(rootfs.join("detached/payload")).unwrap(), - "payload" - ); - assert!(!rootfs.join("detached/victim").exists()); - } -} diff --git a/crates/openshell-driver-vm/src/lib.rs b/crates/openshell-driver-vm/src/lib.rs deleted file mode 100644 index 1913d5652b..0000000000 --- a/crates/openshell-driver-vm/src/lib.rs +++ /dev/null @@ -1,51 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -// `defaults-without-telemetry` is an alias for the default feature set minus -// `telemetry`, not a switch that turns telemetry off. Cargo cannot subtract a -// default feature, so adding it on top of the defaults would otherwise produce -// a telemetry-on build that reads as telemetry-free. Fail the build instead. -#[cfg(all(feature = "telemetry", feature = "defaults-without-telemetry"))] -compile_error!( - "features `telemetry` and `defaults-without-telemetry` are mutually exclusive; \ - build a telemetry-free VM driver with `--no-default-features --features defaults-without-telemetry`" -); - -#[cfg(feature = "compute-driver")] -pub mod driver; -#[cfg(feature = "compute-driver")] -mod embedded_runtime; -#[cfg(feature = "compute-driver")] -mod ffi; -#[cfg(feature = "compute-driver")] -pub mod gpu; -#[cfg(feature = "compute-driver")] -mod isolation; -#[cfg(feature = "compute-driver")] -mod layer_applier; -#[cfg(feature = "compute-driver")] -pub mod lifecycle; -#[cfg(feature = "compute-driver")] -pub mod otel_tracing; -#[cfg(feature = "compute-driver")] -pub mod procguard; -#[cfg(feature = "compute-driver")] -mod rootfs; -#[cfg(feature = "compute-driver")] -mod runtime; -#[cfg(feature = "compute-driver")] -pub mod settings; - -#[cfg(feature = "compute-driver")] -pub use driver::{VmDriver, VmDriverConfig}; -#[cfg(feature = "compute-driver")] -pub use lifecycle::{ - BackendFeature, ExtensionCapabilities, ExtensionDescriptor, GuestInitDropin, LaunchAbortReason, - LaunchPlan, LifecycleError, LifecycleExtension, LifecycleExtensionRegistry, LifecycleResult, - RestoreContext, -}; -#[cfg(feature = "compute-driver")] -pub use runtime::{ - VM_RUNTIME_DIR_ENV, VmBackend, VmLaunchConfig, VmMount, VsockPortMap, configured_runtime_dir, - run_vm, -}; diff --git a/crates/openshell-driver-vm/src/lifecycle.rs b/crates/openshell-driver-vm/src/lifecycle.rs deleted file mode 100644 index f92082d99e..0000000000 --- a/crates/openshell-driver-vm/src/lifecycle.rs +++ /dev/null @@ -1,1241 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use std::collections::HashSet; -use std::path::{Path, PathBuf}; -use std::sync::Arc; - -use openshell_core::proto::compute::v1::DriverSandbox as Sandbox; -use openshell_core::settings::parse_bool_like; - -use crate::runtime::VmBackend; - -/// Label-key prefix used to request a per-sandbox lifecycle extension. -/// -/// A sandbox opts into an [`ExtensionActivation::OnRequest`] extension when -/// its template carries a `{SANDBOX_EXTENSION_LABEL_PREFIX}{key}` label set -/// to an enabled value. The label is policy-controlled (stamped by the -/// gateway), so a guest cannot self-activate an extension. This contract -/// lives with the lifecycle framework that consumes it rather than in the -/// shared settings registry. -pub const SANDBOX_EXTENSION_LABEL_PREFIX: &str = "openshell.ai/extension."; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum LaunchAbortReason { - LauncherSpawnFailed, - BeforeLaunchHookFailed, - GuestPrepareFailed, - /// The VM helper process exited on its own *after* the launcher was - /// spawned (e.g. a guest crash or the hypervisor dying), rather than the - /// driver aborting during setup. The driver releases its own per-launch - /// allocations when this happens, so extensions are given the same - /// opportunity to release host resources they allocated in - /// [`LifecycleExtension::before_launch`]. - ProcessExited, - /// The gateway intentionally stopped the sandbox while retaining disk state. - Stopped, -} - -#[derive(Debug, Clone)] -pub struct LifecycleError { - message: String, - resource_exhausted: bool, -} - -impl LifecycleError { - pub fn new(message: impl Into) -> Self { - Self { - message: message.into(), - resource_exhausted: false, - } - } - - pub fn resource_exhausted(message: impl Into) -> Self { - Self { - message: message.into(), - resource_exhausted: true, - } - } - - #[must_use] - pub fn message(&self) -> &str { - &self.message - } - - #[must_use] - pub fn is_resource_exhausted(&self) -> bool { - self.resource_exhausted - } -} - -impl std::fmt::Display for LifecycleError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.message) - } -} - -impl std::error::Error for LifecycleError {} - -pub type LifecycleResult = Result; - -/// A capability an extension can require from the VM backend. -/// -/// Extensions declare features they need (e.g. PCI passthrough or an -/// external kernel image) and the VM driver resolves a concrete -/// [`VmBackend`] that can satisfy them. The mapping from feature to -/// backend lives in [`BackendFeature::requires_qemu`] for now; once a -/// third backend exists this should evolve into a per-backend capability -/// table that the resolver intersects against feature requirements. -/// -/// # Current limitations -/// -/// Until the non-GPU QEMU launch path (PCI device transport / VFIO root -/// port wiring) lands, the driver still rejects launches where the -/// resolved backend is QEMU but the sandbox has no GPU. As a result, -/// declaring [`Self::PciPassthrough`] or [`Self::ExternalKernelImage`] on -/// a non-GPU sandbox is accepted by [`LifecycleExtensionRegistry::validate`] -/// at registration time but will fail provisioning with a -/// `FailedPrecondition` status. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum BackendFeature { - /// Extension supplies its own kernel image via - /// [`LaunchPlan::kernel_image`]. Currently QEMU-only. - ExternalKernelImage, - /// Extension contributes guest init drop-ins via - /// [`LaunchPlan::guest_init_dropins`]. Supported by all backends. - GuestInitDropins, - /// Extension needs PCI device passthrough on the guest. Currently - /// QEMU-only and currently rejected for non-GPU sandboxes pending the - /// non-GPU QEMU launch path landing. - PciPassthrough, -} - -impl BackendFeature { - #[must_use] - pub fn as_str(self) -> &'static str { - match self { - Self::ExternalKernelImage => "external-kernel-image", - Self::GuestInitDropins => "guest-init-dropins", - Self::PciPassthrough => "pci-passthrough", - } - } - - /// Returns true when satisfying this feature requires the QEMU backend - /// today. This is the simplest possible resolver and is expected to be - /// replaced with a per-backend capability table once a third backend - /// exists. - #[must_use] - pub fn requires_qemu(self) -> bool { - matches!(self, Self::ExternalKernelImage | Self::PciPassthrough) - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Default)] -pub struct ExtensionCapabilities { - pub kernel_profiles: Vec, - pub guest_init_dropins: Vec, - pub launch_features: Vec, - pub host_resources: Vec, -} - -/// A registration-time description of what a lifecycle extension provides -/// and requires. -/// -/// `required_backends` and `required_backend_features` are merged into the -/// launch plan unconditionally for every sandbox. An extension that wants -/// conditional behavior (e.g. only contribute requirements when the -/// sandbox spec asks for it) should leave the descriptor fields empty and -/// call [`LaunchPlan::require_backend`] / -/// [`LaunchPlan::require_backend_feature`] inside -/// [`LifecycleExtension::configure_launch`] instead. -/// -/// Whether the descriptor requirements are merged for *every* sandbox or -/// only for sandboxes that opted in is controlled by the extension's -/// [`LifecycleExtension::activation`]: a [`ExtensionActivation::Global`] -/// extension always participates, while an -/// [`ExtensionActivation::OnRequest`] extension only participates when the -/// sandbox carries the matching request label (see -/// [`ExtensionActivation`]). Within an active extension, the -/// "declare in the descriptor (merged) vs decide in the hook" knob still -/// applies for finer-grained, spec-dependent behavior. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ExtensionDescriptor { - pub name: String, - pub provides: ExtensionCapabilities, - pub required_backends: Vec, - pub required_backend_features: Vec, -} - -impl ExtensionDescriptor { - #[must_use] - pub fn new(name: impl Into) -> Self { - Self { - name: name.into(), - provides: ExtensionCapabilities::default(), - required_backends: Vec::new(), - required_backend_features: Vec::new(), - } - } -} - -/// A guest-side init drop-in injected into the sandbox's overlay disk. -/// -/// Drop-ins land at `/opt/openshell/init.d/{name}` inside the guest with -/// mode `0o755`. The guest's init script *executes* drop-ins in a child -/// shell in deterministic ASCII-sorted order; it does not source them. -/// Authors should: -/// -/// - Begin the file with a `#!/bin/bash` (or equivalent) shebang. -/// - Use the `00-`, `50-`, `99-` prefix convention to control ordering. -/// - Treat the parent shell as immutable: env vars set in a drop-in do not -/// propagate to the rest of init. -/// -/// `name` must consist of ASCII letters, digits, `.`, `-`, or `_` (no -/// path separators, no `.`/`..`); duplicates across a single launch plan -/// are rejected by the driver. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct GuestInitDropin { - pub name: String, - pub contents: Vec, -} - -impl GuestInitDropin { - #[must_use] - pub fn new(name: impl Into, contents: impl Into>) -> Self { - Self { - name: name.into(), - contents: contents.into(), - } - } -} - -#[derive(Debug, Clone)] -pub struct LaunchPlan { - pub backend: VmBackend, - pub vcpus: u8, - pub mem_mib: u32, - pub required_backends: Vec, - pub required_backend_features: Vec, - pub kernel_profile: Option, - pub kernel_image: Option, - pub gpu_bdf: Option, - pub vsock_cid: Option, - pub guest_init_dropins: Vec, - pub env: Vec, -} - -impl LaunchPlan { - pub fn require_backend(&mut self, backend: VmBackend) { - if !self.required_backends.contains(&backend) { - self.required_backends.push(backend); - } - } - - pub fn require_backend_feature(&mut self, feature: BackendFeature) { - if !self.required_backend_features.contains(&feature) { - self.required_backend_features.push(feature); - } - } - - pub fn require_backend_features(&mut self, features: impl IntoIterator) { - for feature in features { - self.require_backend_feature(feature); - } - } -} - -#[derive(Debug, Clone)] -pub struct RestoreContext { - pub sandbox: Sandbox, - pub state_dir: PathBuf, -} - -/// When a registered lifecycle extension participates in a sandbox's -/// lifecycle. -/// -/// This gates *every* hook (configure/launch/cleanup/restore) for the -/// extension, so an inactive extension is invisible to the sandbox: it -/// contributes no descriptor requirements, runs no host-side side effects, -/// and — crucially — its cleanup hooks are not invoked either (there is -/// nothing to clean up because nothing ran). -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ExtensionActivation { - /// The extension participates in every sandbox on this driver. This is - /// the default and matches the historical behavior where all registered - /// extensions ran unconditionally. - Global, - /// The extension participates only for sandboxes that explicitly - /// requested it via a `{SANDBOX_EXTENSION_LABEL_PREFIX}{key}` template - /// label set to an enabled value. The label is policy-controlled - /// (stamped by the gateway), so guests cannot self-activate an - /// extension. `key` must be a valid extension identifier (validated by - /// [`LifecycleExtensionRegistry::validate`]). - OnRequest { key: &'static str }, -} - -/// Lifecycle hooks an extension can implement to participate in VM sandbox -/// provisioning, launch failure, deletion, and post-restart reconciliation. -/// -/// # Hook ordering during a successful launch -/// -/// 1. [`configure_launch`](Self::configure_launch) — contribute backend -/// requirements (via [`LaunchPlan::require_backend`] / -/// [`LaunchPlan::require_backend_feature`]) and provisioning inputs -/// (kernel profile, guest init drop-ins, etc.). Called before the driver -/// has resolved the final backend. -/// 2. Driver resolves [`LaunchPlan::backend`] from declared requirements -/// and allocates backend-specific host resources such as a vsock CID. -/// 3. [`before_launch`](Self::before_launch) — perform host-side -/// side effects with the resolved plan in hand, optionally append -/// additional guest env via [`LaunchPlan::env`]. -/// 4. The driver spawns the VM launcher process. -/// -/// On launch failure or sandbox deletion, the driver invokes -/// [`after_launch_failed`](Self::after_launch_failed) or -/// [`after_delete`](Self::after_delete) in **reverse -/// registration order**, so cleanup mirrors setup. -#[tonic::async_trait] -pub trait LifecycleExtension: std::fmt::Debug + Send + Sync { - fn name(&self) -> &str; - - /// Declare when this extension participates in a sandbox's lifecycle. - /// - /// Defaults to [`ExtensionActivation::Global`] (runs for every sandbox). - /// Override and return [`ExtensionActivation::OnRequest`] for an opt-in - /// extension that should only run when the sandbox carries the matching - /// request label. - fn activation(&self) -> ExtensionActivation { - ExtensionActivation::Global - } - - fn descriptor(&self) -> ExtensionDescriptor { - ExtensionDescriptor::new(self.name()) - } - - /// Contribute backend requirements and provisioning inputs to the plan - /// before the driver picks a backend. - /// - /// Use this hook to: - /// - Declare backend requirements with - /// [`LaunchPlan::require_backend`] or - /// [`LaunchPlan::require_backend_feature`]. - /// - Set [`LaunchPlan::kernel_profile`] or - /// [`LaunchPlan::kernel_image`]. - /// - Append [`LaunchPlan::guest_init_dropins`] entries. - /// - /// At this point [`LaunchPlan::backend`] is the driver's tentative - /// choice and may still change during backend resolution. Do not perform - /// host-side side effects here — defer them to - /// [`before_launch`](Self::before_launch). - async fn configure_launch( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - _plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - Ok(()) - } - - /// Perform host-side preparation with the resolved launch plan. - /// - /// At this point [`LaunchPlan::backend`], - /// [`LaunchPlan::required_backends`], and - /// [`LaunchPlan::required_backend_features`] are finalized and any - /// backend-specific host resources have been - /// allocated. This hook is the right place to bind PCI devices, set - /// up filesystem state, or otherwise prepare the host. - /// - /// Implementations MAY append entries to [`LaunchPlan::env`] to - /// inject additional guest environment variables, and MAY return an - /// error to abort the launch. Implementations MUST NOT change - /// [`LaunchPlan::backend`], [`LaunchPlan::required_backends`], or - /// [`LaunchPlan::required_backend_features`]; those changes are - /// ignored by the driver once `before_launch` is reached. - /// - /// If this hook performs allocations that must be released on failure - /// or delete, implement - /// [`after_launch_failed`](Self::after_launch_failed) and - /// [`after_delete`](Self::after_delete) accordingly. - async fn before_launch( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - _plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - Ok(()) - } - - /// Release anything this extension allocated during - /// [`configure_launch`](Self::configure_launch) or - /// [`before_launch`](Self::before_launch). - /// - /// Invoked in reverse registration order with the reason in - /// [`LaunchAbortReason`]. This fires both when the launcher could not be - /// started / was aborted before it became healthy *and* when a - /// previously-running VM helper process exits on its own - /// ([`LaunchAbortReason::ProcessExited`]); in the latter case the driver - /// simultaneously releases its own per-launch allocations. - /// - /// Because [`LaunchAbortReason::ProcessExited`] cleanup runs while the - /// sandbox record still exists, this hook may later be followed by - /// [`after_delete`](Self::after_delete) for the same sandbox. - /// Implementations MUST therefore be idempotent: do best-effort cleanup, - /// treat already-released resources as success, and return [`Ok`] when - /// possible. Errors are logged but do not propagate. - /// - /// Invoked on every launcher failure, including failures that happen - /// during a persisted-sandbox restore (in that case - /// [`after_restore`](Self::after_restore) is *not* invoked). - async fn after_launch_failed( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - _reason: LaunchAbortReason, - ) -> LifecycleResult<()> { - Ok(()) - } - - /// Release per-sandbox resources after a sandbox has been deleted. - /// - /// Invoked in reverse registration order. Errors are logged but do not - /// propagate. - async fn after_delete(&self, _sandbox: &Sandbox, _state_dir: &Path) -> LifecycleResult<()> { - Ok(()) - } - - /// Inspect or reconcile persisted extension state before the driver - /// attempts to restore a sandbox after a process restart. - /// - /// Returning an error causes the driver to skip restoring this - /// sandbox; the persisted state is left on disk for operator - /// inspection. - async fn before_restore(&self, _sandbox: &RestoreContext) -> LifecycleResult<()> { - Ok(()) - } - - /// Notify the extension that a persisted sandbox has been - /// successfully restored and its launcher is running again. - /// - /// Only invoked when restore succeeds. If the restore fails partway - /// through, [`after_launch_failed`](Self::after_launch_failed) - /// runs instead. - async fn after_restore(&self, _sandbox: &RestoreContext) -> LifecycleResult<()> { - Ok(()) - } -} - -#[derive(Clone, Default)] -pub struct LifecycleExtensionRegistry { - extensions: Vec>, -} - -impl std::fmt::Debug for LifecycleExtensionRegistry { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("LifecycleExtensionRegistry") - .field( - "names", - &self - .extensions - .iter() - .map(|ext| ext.name()) - .collect::>(), - ) - .finish() - } -} - -impl LifecycleExtensionRegistry { - #[must_use] - pub fn new() -> Self { - Self::default() - } - - #[must_use] - pub fn with(extensions: Vec>) -> Self { - Self { extensions } - } - - pub fn push(&mut self, extension: Arc) { - self.extensions.push(extension); - } - - #[must_use] - pub fn is_empty(&self) -> bool { - self.extensions.is_empty() - } - - #[must_use] - pub fn len(&self) -> usize { - self.extensions.len() - } - - #[must_use] - pub fn names(&self) -> Vec { - self.extensions - .iter() - .map(|ext| ext.name().to_string()) - .collect() - } - - #[must_use] - pub fn descriptors(&self) -> Vec { - self.extensions.iter().map(|ext| ext.descriptor()).collect() - } - - /// Names of the extensions that are active for `sandbox`, in - /// registration order. - #[must_use] - pub fn active_names(&self, sandbox: &Sandbox) -> Vec { - self.active_for(sandbox) - .into_iter() - .map(|ext| ext.name().to_string()) - .collect() - } - - pub fn validate(&self) -> LifecycleResult<()> { - let mut names = HashSet::new(); - for ext in &self.extensions { - let descriptor = ext.descriptor(); - validate_extension_name(ext.name())?; - validate_extension_name(&descriptor.name)?; - if let ExtensionActivation::OnRequest { key } = ext.activation() { - validate_extension_identifier(key).map_err(|err| { - LifecycleError::new(format!( - "lifecycle extension '{}' has invalid activation key '{}': {err}", - ext.name(), - key - )) - })?; - } - if descriptor.name != ext.name() { - return Err(LifecycleError::new(format!( - "lifecycle extension '{}' descriptor name does not match '{}'", - ext.name(), - descriptor.name - ))); - } - validate_descriptor_strings(&descriptor)?; - if !names.insert(descriptor.name.clone()) { - return Err(LifecycleError::new(format!( - "duplicate lifecycle extension name: {}", - descriptor.name - ))); - } - } - Ok(()) - } - - /// Extensions active for `sandbox`, preserving registration order. - /// - /// [`ExtensionActivation::Global`] extensions are always included; - /// [`ExtensionActivation::OnRequest`] extensions are included only when - /// the sandbox carries the matching request label. - fn active_for<'a>(&'a self, sandbox: &Sandbox) -> Vec<&'a Arc> { - self.extensions - .iter() - .filter(|ext| match ext.activation() { - ExtensionActivation::Global => true, - ExtensionActivation::OnRequest { key } => sandbox_requested_extension(sandbox, key), - }) - .collect() - } - - #[tracing::instrument( - name = "vm.configure_launch", - skip_all, - fields( - otel.name = "vm.configure_launch", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox.id, - ) - )] - pub async fn configure_launch( - &self, - sandbox: &Sandbox, - state_dir: &Path, - plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - for ext in self.active_for(sandbox) { - let descriptor = ext.descriptor(); - for backend in descriptor.required_backends { - plan.require_backend(backend); - } - plan.require_backend_features(descriptor.required_backend_features); - // Snapshot fields where "last writer wins" could mask an - // extension conflict, so we can flag the conflict instead of - // silently dropping the earlier value. - let prev_kernel_profile = plan.kernel_profile.clone(); - let prev_kernel_image = plan.kernel_image.clone(); - ext.configure_launch(sandbox, state_dir, plan).await?; - warn_on_singleton_overwrite( - ext.name(), - "kernel_profile", - prev_kernel_profile.as_deref(), - plan.kernel_profile.as_deref(), - ); - warn_on_singleton_overwrite( - ext.name(), - "kernel_image", - prev_kernel_image - .as_deref() - .map(|p| p.display().to_string()), - plan.kernel_image - .as_deref() - .map(|p| p.display().to_string()), - ); - } - span_status.finish(Ok(())) - } - - #[tracing::instrument( - name = "vm.before_launch", - skip_all, - fields( - otel.name = "vm.before_launch", - otel.status_code = tracing::field::Empty, - sandbox.id = %sandbox.id, - ) - )] - pub async fn before_launch( - &self, - sandbox: &Sandbox, - state_dir: &Path, - plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - let span_status = openshell_otel::ErrorStatusGuard::current(); - for ext in self.active_for(sandbox) { - ext.before_launch(sandbox, state_dir, plan).await?; - } - span_status.finish(Ok(())) - } - - pub async fn after_launch_failed( - &self, - sandbox: &Sandbox, - state_dir: &Path, - reason: LaunchAbortReason, - ) { - for ext in self.active_for(sandbox).into_iter().rev() { - if let Err(err) = ext - .after_launch_failed(sandbox, state_dir, reason.clone()) - .await - { - tracing::warn!( - extension = ext.name(), - sandbox_id = %sandbox.id, - error = %err, - "vm driver: lifecycle extension after_launch_failed hook failed" - ); - } - } - } - - pub async fn after_delete(&self, sandbox: &Sandbox, state_dir: &Path) { - for ext in self.active_for(sandbox).into_iter().rev() { - if let Err(err) = ext.after_delete(sandbox, state_dir).await { - tracing::warn!( - extension = ext.name(), - sandbox_id = %sandbox.id, - error = %err, - "vm driver: lifecycle extension after_delete hook failed" - ); - } - } - } - - pub async fn before_restore(&self, sandbox: &RestoreContext) -> LifecycleResult<()> { - for ext in self.active_for(&sandbox.sandbox) { - ext.before_restore(sandbox).await?; - } - Ok(()) - } - - pub async fn after_restore(&self, sandbox: &RestoreContext) { - for ext in self.active_for(&sandbox.sandbox) { - if let Err(err) = ext.after_restore(sandbox).await { - tracing::warn!( - extension = ext.name(), - sandbox_id = %sandbox.sandbox.id, - error = %err, - "vm driver: lifecycle extension after_restore hook failed" - ); - } - } - } -} - -/// Returns true when `sandbox` opted into the extension identified by -/// `key` via a policy-stamped `{SANDBOX_EXTENSION_LABEL_PREFIX}{key}` -/// template label set to an enabled value. -fn sandbox_requested_extension(sandbox: &Sandbox, key: &str) -> bool { - let label_key = format!("{SANDBOX_EXTENSION_LABEL_PREFIX}{key}"); - sandbox - .spec - .as_ref() - .and_then(|spec| spec.template.as_ref()) - .and_then(|template| template.labels.get(&label_key)) - .is_some_and(|value| extension_label_enabled(value)) -} - -/// Interpret an extension request-label value. Accepts the explicit -/// `enabled`/`requested` spellings as well as the common bool-like values -/// understood by [`parse_bool_like`]; anything unrecognized is treated as -/// "not requested" so a malformed label fails closed. -fn extension_label_enabled(value: &str) -> bool { - let normalized = value.trim().to_ascii_lowercase(); - if matches!( - normalized.as_str(), - "enabled" | "enable" | "requested" | "request" - ) { - return true; - } - if matches!(normalized.as_str(), "disabled" | "disable") { - return false; - } - parse_bool_like(&normalized).unwrap_or(false) -} - -fn warn_on_singleton_overwrite( - extension_name: &str, - field: &str, - prev: Option, - next: Option, -) where - T: AsRef + std::fmt::Display + PartialEq, -{ - let (Some(prev), Some(next)) = (prev, next) else { - return; - }; - if prev == next { - return; - } - tracing::warn!( - extension = extension_name, - field, - previous = %prev, - next = %next, - "vm driver: lifecycle extension overwrote a singleton launch-plan field set by an earlier extension" - ); -} - -pub fn extension_state_dir( - sandbox_state_dir: &Path, - extension_name: &str, -) -> LifecycleResult { - validate_extension_name(extension_name)?; - Ok(sandbox_state_dir.join("extensions").join(extension_name)) -} - -fn validate_extension_name(name: &str) -> LifecycleResult<()> { - if name.is_empty() || name == "." || name == ".." { - return Err(LifecycleError::new( - "lifecycle extension name is empty or reserved", - )); - } - if !name - .chars() - .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.') - { - return Err(LifecycleError::new(format!( - "lifecycle extension name '{name}' must contain only ASCII letters, numbers, '.', '-', or '_'" - ))); - } - Ok(()) -} - -fn validate_descriptor_strings(descriptor: &ExtensionDescriptor) -> LifecycleResult<()> { - for value in descriptor - .provides - .kernel_profiles - .iter() - .chain(descriptor.provides.guest_init_dropins.iter()) - .chain(descriptor.provides.launch_features.iter()) - .chain(descriptor.provides.host_resources.iter()) - { - validate_extension_identifier(value).map_err(|err| { - LifecycleError::new(format!( - "lifecycle extension '{}' has invalid provided capability '{}': {err}", - descriptor.name, value - )) - })?; - } - Ok(()) -} - -fn validate_extension_identifier(value: &str) -> Result<(), &'static str> { - if value.is_empty() || value == "." || value == ".." { - return Err("identifier is empty or reserved"); - } - if !value - .chars() - .all(|ch| ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.') - { - return Err("identifier must contain only ASCII letters, numbers, '.', '-', or '_'"); - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - use std::path::PathBuf; - use std::sync::Mutex; - - use openshell_core::proto::compute::v1::{DriverSandboxSpec, DriverSandboxTemplate}; - - use super::*; - - #[derive(Debug)] - struct RecordingExtension { - name: String, - configure_should_fail: bool, - before_should_fail: bool, - activation: ExtensionActivation, - calls: Mutex>, - } - - impl RecordingExtension { - fn new(name: &str) -> Arc { - Arc::new(Self { - name: name.to_string(), - configure_should_fail: false, - before_should_fail: false, - activation: ExtensionActivation::Global, - calls: Mutex::new(Vec::new()), - }) - } - - fn on_request(name: &str, key: &'static str) -> Arc { - Arc::new(Self { - name: name.to_string(), - configure_should_fail: false, - before_should_fail: false, - activation: ExtensionActivation::OnRequest { key }, - calls: Mutex::new(Vec::new()), - }) - } - - fn failing(name: &str) -> Arc { - Arc::new(Self { - name: name.to_string(), - configure_should_fail: false, - before_should_fail: true, - activation: ExtensionActivation::Global, - calls: Mutex::new(Vec::new()), - }) - } - - fn configure_failing(name: &str) -> Arc { - Arc::new(Self { - name: name.to_string(), - configure_should_fail: true, - before_should_fail: false, - activation: ExtensionActivation::Global, - calls: Mutex::new(Vec::new()), - }) - } - - fn calls(&self) -> Vec { - self.calls.lock().unwrap().clone() - } - } - - #[tonic::async_trait] - impl LifecycleExtension for RecordingExtension { - fn name(&self) -> &str { - &self.name - } - - fn activation(&self) -> ExtensionActivation { - self.activation - } - - fn descriptor(&self) -> ExtensionDescriptor { - ExtensionDescriptor { - name: self.name.clone(), - provides: ExtensionCapabilities { - kernel_profiles: vec![format!("profile-{}", self.name)], - guest_init_dropins: vec![format!("50-{}.sh", self.name)], - launch_features: vec!["guest-init-dropins".to_string()], - host_resources: Vec::new(), - }, - required_backends: Vec::new(), - required_backend_features: vec![BackendFeature::GuestInitDropins], - } - } - - async fn configure_launch( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - self.calls - .lock() - .unwrap() - .push(format!("{}:configure_launch", self.name)); - if self.configure_should_fail { - return Err(LifecycleError::new(format!( - "{}: scripted configure_launch failure", - self.name - ))); - } - plan.kernel_profile = Some(format!("profile-{}", self.name)); - plan.guest_init_dropins.push(GuestInitDropin::new( - format!("50-{}.sh", self.name), - b"#!/bin/sh\n".to_vec(), - )); - Ok(()) - } - - async fn before_launch( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - plan: &mut LaunchPlan, - ) -> LifecycleResult<()> { - self.calls - .lock() - .unwrap() - .push(format!("{}:before_launch", self.name)); - if self.before_should_fail { - return Err(LifecycleError::new(format!( - "{}: scripted before_launch failure", - self.name - ))); - } - plan.env.push(format!("RECORDING_{}=1", self.name)); - Ok(()) - } - - async fn after_launch_failed( - &self, - _sandbox: &Sandbox, - _state_dir: &Path, - reason: LaunchAbortReason, - ) -> LifecycleResult<()> { - self.calls - .lock() - .unwrap() - .push(format!("{}:after_launch_failed:{:?}", self.name, reason)); - Ok(()) - } - - async fn after_delete(&self, _sandbox: &Sandbox, _state_dir: &Path) -> LifecycleResult<()> { - self.calls - .lock() - .unwrap() - .push(format!("{}:after_delete", self.name)); - Ok(()) - } - } - - fn sample_plan(backend: VmBackend) -> LaunchPlan { - LaunchPlan { - backend, - vcpus: 2, - mem_mib: 2048, - required_backends: Vec::new(), - required_backend_features: Vec::new(), - kernel_profile: None, - kernel_image: None, - gpu_bdf: None, - vsock_cid: None, - guest_init_dropins: Vec::new(), - env: Vec::new(), - } - } - - fn sample_sandbox() -> Sandbox { - Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - ..Default::default() - } - } - - fn sample_sandbox_with_extension(key: &str) -> Sandbox { - let label_key = format!("{SANDBOX_EXTENSION_LABEL_PREFIX}{key}"); - Sandbox { - id: "sandbox-123".to_string(), - name: "sandbox-123".to_string(), - spec: Some(DriverSandboxSpec { - template: Some(DriverSandboxTemplate { - labels: HashMap::from([(label_key, "enabled".to_string())]), - ..Default::default() - }), - ..Default::default() - }), - ..Default::default() - } - } - - fn as_extension(extension: &Arc) -> Arc - where - T: LifecycleExtension + 'static, - { - extension.clone() - } - - #[tokio::test] - async fn configure_launch_runs_each_extension_in_order() { - let ext_a = RecordingExtension::new("a"); - let ext_b = RecordingExtension::new("b"); - let registry = - LifecycleExtensionRegistry::with(vec![as_extension(&ext_a), as_extension(&ext_b)]); - let mut plan = sample_plan(VmBackend::Qemu); - let sandbox = sample_sandbox(); - - registry - .configure_launch(&sandbox, &PathBuf::from("/tmp/state"), &mut plan) - .await - .expect("configure_launch succeeds"); - - assert_eq!(plan.kernel_profile.as_deref(), Some("profile-b")); - assert_eq!( - plan.guest_init_dropins - .iter() - .map(|dropin| dropin.name.as_str()) - .collect::>(), - vec!["50-a.sh", "50-b.sh"] - ); - assert_eq!(ext_a.calls(), vec!["a:configure_launch"]); - assert_eq!(ext_b.calls(), vec!["b:configure_launch"]); - } - - #[tokio::test] - async fn configure_launch_short_circuits_on_first_failure() { - let ext_a = RecordingExtension::new("a"); - let ext_fail = RecordingExtension::configure_failing("boom"); - let ext_c = RecordingExtension::new("c"); - let registry = LifecycleExtensionRegistry::with(vec![ - as_extension(&ext_a), - as_extension(&ext_fail), - as_extension(&ext_c), - ]); - let mut plan = sample_plan(VmBackend::Libkrun); - let sandbox = sample_sandbox(); - - let err = registry - .configure_launch(&sandbox, &PathBuf::from("/tmp/state"), &mut plan) - .await - .expect_err("scripted failure should propagate"); - assert!(err.message().contains("scripted configure_launch failure")); - - assert_eq!(ext_a.calls(), vec!["a:configure_launch"]); - assert_eq!(ext_fail.calls(), vec!["boom:configure_launch"]); - assert!( - ext_c.calls().is_empty(), - "extensions after the failure must not be invoked" - ); - } - - #[tokio::test] - async fn on_request_extension_only_runs_when_label_is_enabled() { - let ext_global = RecordingExtension::new("global"); - let ext_requested = RecordingExtension::on_request("requested", "nemo-relay"); - let registry = LifecycleExtensionRegistry::with(vec![ - as_extension(&ext_global), - as_extension(&ext_requested), - ]); - let mut plan = sample_plan(VmBackend::Libkrun); - - registry - .configure_launch(&sample_sandbox(), &PathBuf::from("/tmp/state"), &mut plan) - .await - .expect("configure_launch succeeds"); - - assert_eq!(ext_global.calls(), vec!["global:configure_launch"]); - assert!( - ext_requested.calls().is_empty(), - "on-request extension must stay inactive without the request label" - ); - - let mut requested_plan = sample_plan(VmBackend::Libkrun); - registry - .configure_launch( - &sample_sandbox_with_extension("nemo-relay"), - &PathBuf::from("/tmp/state"), - &mut requested_plan, - ) - .await - .expect("configure_launch succeeds"); - - assert_eq!( - ext_requested.calls(), - vec!["requested:configure_launch"], - "on-request extension should run when the label is enabled" - ); - } - - #[tokio::test] - async fn active_names_reflects_request_label() { - let registry = LifecycleExtensionRegistry::with(vec![ - RecordingExtension::new("global"), - RecordingExtension::on_request("requested", "nemo-relay"), - ]); - - assert_eq!(registry.active_names(&sample_sandbox()), vec!["global"]); - assert_eq!( - registry.active_names(&sample_sandbox_with_extension("nemo-relay")), - vec!["global", "requested"] - ); - } - - #[test] - fn validate_rejects_invalid_on_request_key() { - let registry = LifecycleExtensionRegistry::with(vec![RecordingExtension::on_request( - "bad-key", - "../escape", - )]); - let err = registry - .validate() - .expect_err("invalid activation key should fail validation"); - assert!(err.message().contains("invalid activation key")); - } - - #[tokio::test] - async fn before_launch_runs_each_extension_in_order_and_collects_env() { - let ext_a = RecordingExtension::new("a"); - let ext_b = RecordingExtension::new("b"); - let registry = - LifecycleExtensionRegistry::with(vec![as_extension(&ext_a), as_extension(&ext_b)]); - let mut plan = sample_plan(VmBackend::Qemu); - let sandbox = sample_sandbox(); - - registry - .before_launch(&sandbox, &PathBuf::from("/tmp/state"), &mut plan) - .await - .expect("before_launch succeeds"); - - assert_eq!(plan.env, vec!["RECORDING_a=1", "RECORDING_b=1"]); - assert_eq!(ext_a.calls(), vec!["a:before_launch"]); - assert_eq!(ext_b.calls(), vec!["b:before_launch"]); - } - - #[tokio::test] - async fn before_launch_short_circuits_on_first_failure() { - let ext_a = RecordingExtension::new("a"); - let ext_fail = RecordingExtension::failing("boom"); - let ext_c = RecordingExtension::new("c"); - let registry = LifecycleExtensionRegistry::with(vec![ - as_extension(&ext_a), - as_extension(&ext_fail), - as_extension(&ext_c), - ]); - let mut plan = sample_plan(VmBackend::Libkrun); - let sandbox = sample_sandbox(); - - let err = registry - .before_launch(&sandbox, &PathBuf::from("/tmp/state"), &mut plan) - .await - .expect_err("scripted failure should propagate"); - assert!(err.message().contains("scripted before_launch failure")); - - assert_eq!(ext_a.calls(), vec!["a:before_launch"]); - assert_eq!(ext_fail.calls(), vec!["boom:before_launch"]); - assert!( - ext_c.calls().is_empty(), - "extensions after the failure must not be invoked" - ); - } - - #[tokio::test] - async fn after_launch_failed_runs_every_extension_in_reverse_order() { - let ext_a = RecordingExtension::new("a"); - let ext_b = RecordingExtension::new("b"); - let registry = - LifecycleExtensionRegistry::with(vec![as_extension(&ext_a), as_extension(&ext_b)]); - let sandbox = sample_sandbox(); - - registry - .after_launch_failed( - &sandbox, - &PathBuf::from("/tmp/state"), - LaunchAbortReason::LauncherSpawnFailed, - ) - .await; - - assert_eq!( - ext_a.calls(), - vec!["a:after_launch_failed:LauncherSpawnFailed"] - ); - assert_eq!( - ext_b.calls(), - vec!["b:after_launch_failed:LauncherSpawnFailed"] - ); - } - - #[tokio::test] - async fn after_delete_runs_every_extension() { - let ext_a = RecordingExtension::new("a"); - let ext_b = RecordingExtension::new("b"); - let registry = - LifecycleExtensionRegistry::with(vec![as_extension(&ext_a), as_extension(&ext_b)]); - let sandbox = sample_sandbox(); - - registry - .after_delete(&sandbox, &PathBuf::from("/tmp/state")) - .await; - - assert_eq!(ext_a.calls(), vec!["a:after_delete"]); - assert_eq!(ext_b.calls(), vec!["b:after_delete"]); - } - - #[test] - fn resource_exhausted_flag_round_trips() { - let err = LifecycleError::resource_exhausted("pool empty"); - assert!(err.is_resource_exhausted()); - assert_eq!(err.message(), "pool empty"); - - let plain = LifecycleError::new("internal"); - assert!(!plain.is_resource_exhausted()); - } - - #[test] - fn extension_state_dir_rejects_path_unsafe_names() { - let base = PathBuf::from("/tmp/sandbox"); - assert_eq!( - extension_state_dir(&base, "vfio").unwrap(), - base.join("extensions").join("vfio") - ); - assert!(extension_state_dir(&base, "../vfio").is_err()); - assert!(extension_state_dir(&base, "").is_err()); - } - - #[test] - fn validate_rejects_duplicate_extension_names() { - let registry = LifecycleExtensionRegistry::with(vec![ - RecordingExtension::new("dup"), - RecordingExtension::new("dup"), - ]); - let err = registry - .validate() - .expect_err("duplicate names should fail"); - assert!(err.message().contains("duplicate")); - } - - #[test] - fn descriptor_tracks_provided_capabilities_and_requirements() { - let ext = RecordingExtension::new("vfio"); - let registry = LifecycleExtensionRegistry::with(vec![ext]); - - let descriptors = registry.descriptors(); - assert_eq!(descriptors.len(), 1); - assert_eq!(descriptors[0].name, "vfio"); - assert!(descriptors[0].required_backends.is_empty()); - assert_eq!( - descriptors[0].required_backend_features, - vec![BackendFeature::GuestInitDropins] - ); - assert_eq!( - descriptors[0].provides.kernel_profiles, - vec!["profile-vfio".to_string()] - ); - assert_eq!( - descriptors[0].provides.guest_init_dropins, - vec!["50-vfio.sh".to_string()] - ); - } -} diff --git a/crates/openshell-driver-vm/src/listener.rs b/crates/openshell-driver-vm/src/listener.rs deleted file mode 100644 index 04283b7482..0000000000 --- a/crates/openshell-driver-vm/src/listener.rs +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! The driver's private Unix-socket listener: socket directory and socket -//! preparation, peer authorization by uid and expected gateway PID, and the -//! shutdown signal. - -use futures::Stream; -use std::io; -use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; -use std::path::Path; -use std::pin::Pin; -use std::task::{Context, Poll}; -use tokio::net::{UnixListener, UnixStream}; -use tracing::info; - -pub async fn shutdown_signal() { - let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) - .expect("install SIGTERM handler"); - tokio::select! { - result = tokio::signal::ctrl_c() => { - if let Err(error) = result { - tracing::warn!(%error, "failed to listen for Ctrl-C"); - } - } - _ = terminate.recv() => {} - } - info!("Shutdown signal received; stopping vm compute driver"); -} - -pub fn prepare_compute_driver_socket(socket_path: &Path) -> Result<(), String> { - let Some(parent) = socket_path.parent() else { - return Err(format!( - "vm compute driver socket path '{}' has no parent directory", - socket_path.display() - )); - }; - let expected_uid = current_euid(); - prepare_private_socket_dir(parent, expected_uid)?; - remove_stale_socket(socket_path, expected_uid) -} - -pub fn current_euid() -> u32 { - rustix::process::geteuid().as_raw() -} - -pub fn prepare_private_socket_dir(socket_dir: &Path, expected_uid: u32) -> Result<(), String> { - std::fs::create_dir_all(socket_dir) - .map_err(|err| format!("create socket dir {}: {err}", socket_dir.display()))?; - let metadata = std::fs::symlink_metadata(socket_dir) - .map_err(|err| format!("stat socket dir {}: {err}", socket_dir.display()))?; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - return Err(format!( - "socket dir {} is a symlink; refusing to use it", - socket_dir.display() - )); - } - if !file_type.is_dir() { - return Err(format!( - "socket dir {} is not a directory", - socket_dir.display() - )); - } - if metadata.uid() != expected_uid { - return Err(format!( - "socket dir {} is owned by uid {} but current euid is {}", - socket_dir.display(), - metadata.uid(), - expected_uid - )); - } - std::fs::set_permissions(socket_dir, std::fs::Permissions::from_mode(0o700)) - .map_err(|err| format!("chmod socket dir {}: {err}", socket_dir.display())) -} - -pub fn remove_stale_socket(socket_path: &Path, expected_uid: u32) -> Result<(), String> { - let metadata = match std::fs::symlink_metadata(socket_path) { - Ok(metadata) => metadata, - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(err) => return Err(format!("stat socket {}: {err}", socket_path.display())), - }; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - return Err(format!( - "socket {} is a symlink; refusing to remove it", - socket_path.display() - )); - } - if metadata.uid() != expected_uid { - return Err(format!( - "socket {} is owned by uid {} but current euid is {}", - socket_path.display(), - metadata.uid(), - expected_uid - )); - } - if !file_type.is_socket() { - return Err(format!( - "socket path {} exists but is not a Unix socket", - socket_path.display() - )); - } - std::fs::remove_file(socket_path) - .map_err(|err| format!("remove stale socket {}: {err}", socket_path.display())) -} - -pub fn restrict_socket_permissions(socket_path: &Path) -> Result<(), String> { - std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600)) - .map_err(|err| format!("chmod socket {}: {err}", socket_path.display())) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct PeerCredentials { - uid: u32, - pid: Option, -} - -pub fn peer_credentials(stream: &UnixStream) -> Result { - let credentials = stream - .peer_cred() - .map_err(|err| format!("read peer credentials: {err}"))?; - Ok(PeerCredentials { - uid: credentials.uid(), - pid: credentials.pid(), - }) -} - -pub fn authorize_peer_credentials( - peer: PeerCredentials, - driver_uid: u32, - gateway_pid: Option, -) -> Result<(), String> { - if peer.uid != driver_uid { - return Err(format!( - "peer uid {} does not match current euid {}", - peer.uid, driver_uid - )); - } - let Some(gateway_pid) = gateway_pid else { - return Ok(()); - }; - let Some(peer_process_id) = peer.pid.and_then(|pid| u32::try_from(pid).ok()) else { - return Err(format!( - "peer pid is unavailable; expected gateway pid {gateway_pid}" - )); - }; - if peer_process_id != gateway_pid { - return Err(format!( - "peer pid {peer_process_id} does not match expected gateway pid {gateway_pid}" - )); - } - Ok(()) -} - -pub struct AuthenticatedUnixIncoming { - listener: UnixListener, - expected_uid: u32, - expected_peer_pid: Option, -} - -impl AuthenticatedUnixIncoming { - pub fn new(listener: UnixListener, expected_peer_pid: Option) -> Self { - Self { - listener, - expected_uid: current_euid(), - expected_peer_pid, - } - } -} - -impl Stream for AuthenticatedUnixIncoming { - type Item = io::Result; - - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let this = self.get_mut(); - loop { - match this.listener.poll_accept(cx) { - Poll::Ready(Ok((stream, _addr))) => { - let authorized = peer_credentials(&stream).and_then(|peer| { - authorize_peer_credentials(peer, this.expected_uid, this.expected_peer_pid) - }); - match authorized { - Ok(()) => return Poll::Ready(Some(Ok(stream))), - Err(err) => { - tracing::warn!( - error = %err, - "rejected vm compute driver UDS client" - ); - } - } - } - Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err))), - Poll::Pending => return Poll::Pending, - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn peer_authorization_accepts_matching_uid_and_pid() { - authorize_peer_credentials( - PeerCredentials { - uid: 1000, - pid: Some(42), - }, - 1000, - Some(42), - ) - .unwrap(); - } - - #[test] - fn peer_authorization_rejects_wrong_pid() { - let err = authorize_peer_credentials( - PeerCredentials { - uid: 1000, - pid: Some(7), - }, - 1000, - Some(42), - ) - .expect_err("wrong pid should be rejected"); - assert!(err.contains("does not match expected gateway pid")); - } - - #[test] - fn peer_authorization_rejects_wrong_uid() { - let err = authorize_peer_credentials( - PeerCredentials { - uid: 1001, - pid: Some(42), - }, - 1000, - Some(42), - ) - .expect_err("wrong uid should be rejected"); - assert!(err.contains("does not match current euid")); - } - - #[test] - fn peer_authorization_rejects_missing_pid_when_expected() { - let err = authorize_peer_credentials( - PeerCredentials { - uid: 1000, - pid: None, - }, - 1000, - Some(42), - ) - .expect_err("missing pid should be rejected"); - assert!(err.contains("peer pid is unavailable")); - } - - #[test] - fn peer_authorization_accepts_matching_uid_without_expected_pid() { - authorize_peer_credentials( - PeerCredentials { - uid: 1000, - pid: None, - }, - 1000, - None, - ) - .unwrap(); - } -} diff --git a/crates/openshell-driver-vm/src/main.rs b/crates/openshell-driver-vm/src/main.rs deleted file mode 100644 index 407ad3e150..0000000000 --- a/crates/openshell-driver-vm/src/main.rs +++ /dev/null @@ -1,893 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use clap::Parser; -use miette::{IntoDiagnostic, Result}; -use openshell_core::VERSION; -use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; -use openshell_core::sandbox_env::SupervisorOtlpArgs; -#[cfg(target_os = "macos")] -use openshell_driver_vm::{VM_RUNTIME_DIR_ENV, configured_runtime_dir}; -use openshell_driver_vm::{ - VmBackend, VmDriver, VmDriverConfig, VmLaunchConfig, VmMount, VsockPortMap, procguard, run_vm, -}; -use std::net::SocketAddr; -use std::path::PathBuf; -use tokio::net::UnixListener; -use tracing::info; - -mod listener; -mod serve; -use listener::{ - AuthenticatedUnixIncoming, prepare_compute_driver_socket, restrict_socket_permissions, - shutdown_signal, -}; - -#[derive(Parser, Debug)] -#[command(name = "openshell-driver-vm")] -#[command(version = VERSION)] -#[allow(clippy::struct_excessive_bools)] -struct Args { - /// Operator-owned JSON policy; omitted means driver config disabled and labels required. - #[arg( - long, - env = "OPENSHELL_DRIVER_ADMISSION_CONFIG_JSON", - default_value = "{}" - )] - admission_config_json: openshell_core::resource_admission::DriverAdmissionConfig, - #[arg(long, hide = true, default_value_t = false)] - internal_run_vm: bool, - - #[arg(long, hide = true)] - internal_prepare_image: Option, - - #[arg(long = "vm-root-disk", hide = true, alias = "vm-rootfs")] - vm_root_disk: Option, - - #[arg(long = "vm-overlay-disk", hide = true)] - vm_overlay_disk: Option, - - #[arg(long = "vm-image-disk", hide = true)] - vm_image_disk: Option, - - #[arg(long = "vm-kernel-image", hide = true)] - vm_kernel_image: Option, - - #[arg(long, hide = true)] - vm_exec: Option, - - #[arg(long, hide = true, default_value = "/")] - vm_workdir: String, - - #[arg(long, hide = true)] - vm_env: Vec, - - #[arg(long, hide = true)] - vm_console_output: Option, - - #[arg(long, hide = true, default_value_t = 2)] - vm_vcpus: u8, - - #[arg(long, hide = true, default_value_t = 2048)] - vm_mem_mib: u32, - - #[arg(long, hide = true, default_value_t = 1)] - vm_krun_log_level: u32, - - #[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_BIND")] - bind_address: Option, - - #[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_SOCKET")] - bind_socket: Option, - - #[arg(long, hide = true)] - expected_peer_pid: Option, - - #[arg( - long, - env = "OPENSHELL_COMPUTE_DRIVER_ALLOW_UNAUTHENTICATED_TCP", - default_value_t = false - )] - allow_unauthenticated_tcp: bool, - - #[arg( - long, - env = "OPENSHELL_COMPUTE_DRIVER_ALLOW_SAME_UID_PEER", - default_value_t = false - )] - allow_same_uid_peer: bool, - - #[arg(long, env = "OPENSHELL_LOG_LEVEL", default_value = "info")] - log_level: String, - - #[command(flatten)] - otlp: SupervisorOtlpArgs, - - #[arg(long, env = "OPENSHELL_GATEWAY_NAME")] - gateway_name: Option, - - #[arg(long = "grpc-endpoint", env = "OPENSHELL_GRPC_ENDPOINT")] - grpc_endpoint: Option, - - #[arg(long, env = "OPENSHELL_SANDBOX_IMAGE", default_value = "")] - default_image: String, - - #[arg(long, env = "OPENSHELL_VM_BOOTSTRAP_IMAGE", default_value = "")] - bootstrap_image: String, - - #[arg(long, env = "OPENSHELL_VM_BOOTSTRAP_EXTRACTION_MAX_BYTES")] - bootstrap_extraction_max_bytes: Option, - - #[arg( - long, - env = "OPENSHELL_VM_DRIVER_STATE_DIR", - default_value = "target/openshell-vm-driver" - )] - state_dir: PathBuf, - - #[arg(long = "guest-tls-ca", env = "OPENSHELL_VM_TLS_CA")] - guest_tls_ca: Option, - - /// Deprecated; client certificates are rejected. - #[arg(long = "guest-tls-cert", env = "OPENSHELL_VM_TLS_CERT")] - guest_tls_cert: Option, - - /// Deprecated; client private keys are rejected. - #[arg(long = "guest-tls-key", env = "OPENSHELL_VM_TLS_KEY")] - guest_tls_key: Option, - - /// Gateway-owned normalized destination trust artifact. This hidden option - /// is supplied only by the in-process gateway VM factory. - #[arg(long, hide = true)] - additional_ca_bundle: Option, - - /// Expected SHA-256 generation of the gateway-owned destination trust - /// artifact. Supplied with the path so the child can authenticate its - /// one-time startup read without receiving CA bytes on argv or in env. - #[arg(long, hide = true)] - additional_ca_digest: Option, - - /// Expected certificate count in the gateway-normalized destination trust - /// artifact. - #[arg(long, hide = true)] - additional_ca_certificate_count: Option, - - /// Corporate forward proxy for supervisor TLS egress. - #[arg(long, env = "OPENSHELL_VM_UPSTREAM_PROXY")] - upstream_proxy: Option, - - #[arg(long, env = "OPENSHELL_VM_UPSTREAM_NO_PROXY")] - upstream_no_proxy: Option, - - /// Root-owned gateway-host file containing `user:pass` proxy credentials. - #[arg(long, env = "OPENSHELL_VM_UPSTREAM_PROXY_AUTH_FILE")] - upstream_proxy_auth_file: Option, - - /// Explicitly acknowledge cleartext Basic authentication to an http proxy. - #[arg( - long, - env = "OPENSHELL_VM_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE", - default_value_t = false - )] - upstream_proxy_auth_allow_insecure: bool, - - #[arg( - long, - env = "OPENSHELL_VM_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME", - default_value_t = false - )] - upstream_proxy_connect_by_hostname: bool, - - /// Gateway-host PEM CA bundle trusted for the corporate proxy and for - /// server certificates re-signed by a TLS-intercepting proxy. - #[arg(long, env = "OPENSHELL_VM_UPSTREAM_PROXY_CA_BUNDLE")] - upstream_proxy_ca_bundle: Option, - - /// AAAA handling for the host supervisors' mediated policy DNS: `auto`, - /// `enabled` or `disabled`. - #[arg(long, env = "OPENSHELL_VM_POLICY_DNS_IPV6_EGRESS")] - policy_dns_ipv6_egress: Option, - - /// NAT64 prefix (RFC 6052 CIDR) of the host network. Repeatable. - #[arg( - long = "nat64-prefix", - env = "OPENSHELL_VM_NAT64_PREFIXES", - value_delimiter = ',' - )] - nat64_prefixes: Vec, - - /// Guest-reachable SPIFFE Workload API endpoint (`tcp:IP:port`). - #[arg( - long = "provider-spiffe-workload-api-tcp-endpoint", - env = "OPENSHELL_PROVIDER_SPIFFE_WORKLOAD_API_TCP_ENDPOINT" - )] - provider_spiffe_workload_api_tcp_endpoint: Option, - - /// Explicit acknowledgement that the configured Workload API listener is exposed to VM guests. - #[arg( - long, - env = "OPENSHELL_PROVIDER_SPIFFE_ALLOW_GUEST_TCP", - default_value_t = false - )] - provider_spiffe_allow_guest_tcp: bool, - - #[arg(long, env = "OPENSHELL_VM_KRUN_LOG_LEVEL", default_value_t = 1)] - krun_log_level: u32, - - #[arg(long, env = "OPENSHELL_VM_DRIVER_VCPUS", default_value_t = 2)] - vcpus: u8, - - #[arg(long, env = "OPENSHELL_VM_DRIVER_MEM_MIB", default_value_t = 2048)] - mem_mib: u32, - - #[arg(long, env = "OPENSHELL_VM_OVERLAY_DISK_MIB", default_value_t = 4096)] - overlay_disk_mib: u64, - - #[arg(long, env = "OPENSHELL_VM_GPU")] - gpu: bool, - - #[arg(long, env = "OPENSHELL_VM_GPU_MEM_MIB", default_value_t = 8192)] - gpu_mem_mib: u32, - - #[arg(long, env = "OPENSHELL_VM_GPU_VCPUS", default_value_t = 4)] - gpu_vcpus: u8, - - #[arg(long, env = "OPENSHELL_VM_SANDBOX_UID")] - sandbox_uid: Option, - - #[arg(long, env = "OPENSHELL_VM_SANDBOX_GID")] - sandbox_gid: Option, - - // Corporate forward proxy for sandbox egress. Operator-owned: these reach - // the host supervisor on its argv, which the sandbox image and the - // user-supplied environment cannot influence. - #[arg(long, env = "OPENSHELL_VM_HTTPS_PROXY")] - https_proxy: Option, - - #[arg(long, env = "OPENSHELL_VM_NO_PROXY")] - no_proxy: Option, - - #[arg(long, env = "OPENSHELL_VM_PROXY_AUTH_FILE")] - proxy_auth_file: Option, - - // Value-taking rather than a presence flag so an explicit `false` in - // `[openshell.drivers.vm]` survives the gateway -> driver hop and still - // trips the "acknowledgement without a credential" check. - #[arg(long, env = "OPENSHELL_VM_PROXY_AUTH_ALLOW_INSECURE")] - proxy_auth_allow_insecure: Option, - - #[arg(long, env = "OPENSHELL_VM_PROXY_CONNECT_BY_HOSTNAME")] - proxy_connect_by_hostname: Option, - - #[arg(long, env = "OPENSHELL_VM_PROXY_CA_BUNDLE")] - proxy_ca_bundle: Option, - - #[arg(long, env = "OPENSHELL_VM_ENABLE_BIND_MOUNTS", default_value_t = false)] - enable_bind_mounts: bool, - - #[arg(long, env = "OPENSHELL_VM_ROOTFS_TAR_STAGING_DIR")] - rootfs_tar_staging_dir: Option, - - #[arg(long, env = "OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES")] - rootfs_tar_max_bytes: Option, - - #[arg(long, hide = true)] - vm_backend: Option, - - #[arg(long, hide = true)] - vm_gpu_bdf: Option, - - #[arg(long, hide = true)] - vm_vsock_cid: Option, - - #[arg(long, hide = true)] - vm_vsock_control_port: Option, - - #[arg(long, hide = true)] - vm_vsock_control_socket: Option, - - #[arg(long, hide = true)] - vm_vsock_runtime_initiated: bool, - - #[arg(long, hide = true)] - vm_mount: Vec, -} - -#[tokio::main] -async fn main() -> Result<()> { - if let Some(code) = serve::dispatch().await { - std::process::exit(code); - } - let args = Args::parse(); - if let Some(request) = args.internal_prepare_image { - openshell_driver_vm::driver::run_image_preparation_worker(&request) - .await - .map_err(|error| miette::miette!("{error}"))?; - return Ok(()); - } - if args.internal_run_vm { - // The VM launcher arms procguard after resolving its runtime so its - // libkrun worker cannot outlive the launcher. - maybe_reexec_internal_vm_with_runtime_env()?; - let config = build_vm_launch_config(&args).map_err(|err| miette::miette!("{err}"))?; - run_vm(&config).map_err(|err| miette::miette!("{err}"))?; - return Ok(()); - } - - let _tracing = openshell_otel::install_driver_tracing( - openshell_driver_vm::otel_tracing::TRACING, - openshell_otel::DriverTracingConfig { - endpoint: args.otlp.endpoint.as_deref(), - protocol: args.otlp.protocol.into(), - ca_file: args.otlp.ca_file.as_deref(), - cert_file: args.otlp.cert_file.as_deref(), - key_file: args.otlp.key_file.as_deref(), - gateway_name: args.gateway_name.as_deref(), - service_version: VERSION, - log_level: &args.log_level, - ansi: openshell_core::color::stdout_ansi(), - }, - ); - args.otlp.warn_deprecated(); - - let listen_mode = compute_driver_listen_mode(&args).map_err(|err| miette::miette!("{err}"))?; - - // Arm procguard so that if the gateway is killed (SIGKILL or crash) - // we also die. Without this the driver is reparented to init and - // keeps its per-sandbox VM launchers alive forever. Launchers have - // their own procguards (armed in `run_vm`) which cascade cleanup of - // the libkrun worker the moment this driver exits. - if let Err(err) = procguard::die_with_parent() { - tracing::warn!( - error = %err, - "procguard arm failed; gateway crashes may orphan this driver" - ); - } - - let supervisor_otlp = args.otlp.supervisor_otlp(); - let driver = VmDriver::new(VmDriverConfig { - allow_driver_config: args.admission_config_json.allow_driver_config, - resource_admission: args.admission_config_json.resource_admission.clone(), - grpc_endpoint: args - .grpc_endpoint - .ok_or_else(|| miette::miette!("OPENSHELL_GRPC_ENDPOINT is required"))?, - supervisor_otlp, - supervisor_gateway_name: args.gateway_name.clone(), - state_dir: args.state_dir.clone(), - launcher_bin: None, - default_image: args.default_image.clone(), - bootstrap_image: args.bootstrap_image.clone(), - bootstrap_extraction_max_bytes: args.bootstrap_extraction_max_bytes, - log_level: args.log_level.clone(), - krun_log_level: args.krun_log_level, - vcpus: args.vcpus, - mem_mib: args.mem_mib, - overlay_disk_mib: args.overlay_disk_mib, - guest_tls_ca: args.guest_tls_ca.clone(), - guest_tls_cert: args.guest_tls_cert.clone(), - guest_tls_key: args.guest_tls_key.clone(), - additional_ca_bundle: args.additional_ca_bundle.clone(), - additional_ca_digest: args.additional_ca_digest.clone(), - additional_ca_certificate_count: args.additional_ca_certificate_count, - additional_ca_snapshot: None, - upstream_proxy: openshell_core::UpstreamProxyConfig { - https_proxy: args.upstream_proxy.clone(), - no_proxy: args.upstream_no_proxy.clone(), - proxy_auth_file: args.upstream_proxy_auth_file.clone(), - proxy_auth_allow_insecure: args.upstream_proxy_auth_allow_insecure.then_some(true), - proxy_connect_by_hostname: args.upstream_proxy_connect_by_hostname.then_some(true), - }, - proxy_ca_bundle: args.upstream_proxy_ca_bundle.clone(), - ipv6_egress: openshell_core::SupervisorIpv6EgressConfig { - policy_dns_ipv6_egress: args.policy_dns_ipv6_egress, - nat64_prefixes: args.nat64_prefixes.clone(), - }, - provider_spiffe_workload_api_tcp_endpoint: args - .provider_spiffe_workload_api_tcp_endpoint - .clone(), - provider_spiffe_allow_guest_tcp: args.provider_spiffe_allow_guest_tcp, - gpu_enabled: args.gpu, - gpu_mem_mib: args.gpu_mem_mib, - gpu_vcpus: args.gpu_vcpus, - sandbox_uid: args.sandbox_uid, - sandbox_gid: args.sandbox_gid, - rootfs_tar_staging_dir: args.rootfs_tar_staging_dir.clone(), - rootfs_tar_max_bytes: args.rootfs_tar_max_bytes, - enable_bind_mounts: args.enable_bind_mounts, - }) - .await - .map_err(|err| miette::miette!("{err}"))?; - - let socket_cleanup = driver.clone(); - let result = match listen_mode { - ComputeDriverListenMode::Unix { - socket_path, - expected_peer_pid, - } => { - prepare_compute_driver_socket(&socket_path).map_err(|err| miette::miette!("{err}"))?; - - info!(socket = %socket_path.display(), "Starting vm compute driver"); - let listener = UnixListener::bind(&socket_path).into_diagnostic()?; - restrict_socket_permissions(&socket_path).map_err(|err| miette::miette!("{err}"))?; - let result = tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(ComputeDriverServer::new(driver)) - .serve_with_incoming_shutdown( - AuthenticatedUnixIncoming::new(listener, expected_peer_pid), - shutdown_signal(), - ) - .await - .into_diagnostic(); - let _ = std::fs::remove_file(&socket_path); - result - } - ComputeDriverListenMode::Tcp(bind_address) => { - info!(address = %bind_address, "Starting unauthenticated dev vm compute driver"); - tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(ComputeDriverServer::new(driver)) - .serve_with_shutdown(bind_address, shutdown_signal()) - .await - .into_diagnostic() - } - }; - socket_cleanup.remove_socket_root(); - result -} - -#[derive(Debug, Clone, PartialEq, Eq)] -enum ComputeDriverListenMode { - Unix { - socket_path: PathBuf, - expected_peer_pid: Option, - }, - Tcp(SocketAddr), -} - -fn compute_driver_listen_mode(args: &Args) -> std::result::Result { - if let Some(socket_path) = args.bind_socket.clone() { - if args.expected_peer_pid.is_none() && !args.allow_same_uid_peer { - return Err( - "--expected-peer-pid is required with --bind-socket; use --allow-same-uid-peer only for local development" - .to_string(), - ); - } - return Ok(ComputeDriverListenMode::Unix { - socket_path, - expected_peer_pid: args.expected_peer_pid, - }); - } - - if !args.allow_unauthenticated_tcp { - return Err( - "--bind-socket is required; unauthenticated TCP mode is disabled unless --allow-unauthenticated-tcp is set for local development" - .to_string(), - ); - } - - let Some(bind_address) = args.bind_address else { - return Err("--bind-address is required with --allow-unauthenticated-tcp".to_string()); - }; - - Ok(ComputeDriverListenMode::Tcp(bind_address)) -} - -fn build_vm_launch_config(args: &Args) -> std::result::Result { - let root_disk = args - .vm_root_disk - .clone() - .ok_or_else(|| "--vm-root-disk is required in internal VM mode".to_string())?; - let overlay_disk = args - .vm_overlay_disk - .clone() - .ok_or_else(|| "--vm-overlay-disk is required in internal VM mode".to_string())?; - let image_disk = args.vm_image_disk.clone(); - let exec_path = args - .vm_exec - .clone() - .ok_or_else(|| "--vm-exec is required in internal VM mode".to_string())?; - let console_output = args - .vm_console_output - .clone() - .ok_or_else(|| "--vm-console-output is required in internal VM mode".to_string())?; - - let backend = match args.vm_backend.as_deref() { - Some("qemu") => VmBackend::Qemu, - Some("libkrun") | None => VmBackend::Libkrun, - Some(other) => return Err(format!("unknown VM backend: {other}")), - }; - - let mounts = args - .vm_mount - .iter() - .map(|m| parse_vm_mount_arg(m)) - .collect::, _>>()?; - - Ok(VmLaunchConfig { - root_disk, - overlay_disk, - image_disk, - kernel_image: args.vm_kernel_image.clone(), - vcpus: args.vm_vcpus, - mem_mib: args.vm_mem_mib, - exec_path, - args: Vec::new(), - env: args.vm_env.clone(), - workdir: args.vm_workdir.clone(), - log_level: args.vm_krun_log_level, - console_output, - backend, - gpu_bdf: args.vm_gpu_bdf.clone(), - vsock_cid: args.vm_vsock_cid, - vsock_port_map: match ( - args.vm_vsock_control_port, - args.vm_vsock_control_socket.clone(), - ) { - (Some(guest_port), Some(host_socket)) => Some(VsockPortMap { - guest_port, - host_socket, - host_initiated: !args.vm_vsock_runtime_initiated, - }), - (None, None) => None, - _ => { - return Err( - "--vm-vsock-control-port and --vm-vsock-control-socket must be set together" - .to_string(), - ); - } - }, - mounts, - }) -} - -fn parse_vm_mount_arg(arg: &str) -> std::result::Result { - // Split from the right: the driver generates the tag and mode, so a tab - // in the source can never shift them. - let mut parts = arg.rsplitn(3, '\t'); - let mode = parts - .next() - .ok_or_else(|| format!("invalid --vm-mount format: {arg}"))?; - let tag = parts - .next() - .ok_or_else(|| format!("invalid --vm-mount format (missing tag): {arg}"))?; - let source = parts - .next() - .ok_or_else(|| format!("invalid --vm-mount format (missing source): {arg}"))?; - let read_only = match mode { - "ro" => true, - "rw" => false, - _ => { - return Err(format!( - "invalid --vm-mount mode '{mode}': expected 'ro' or 'rw'" - )); - } - }; - Ok(VmMount { - host_path: PathBuf::from(source), - tag: tag.to_string(), - read_only, - }) -} - -#[cfg(target_os = "macos")] -fn maybe_reexec_internal_vm_with_runtime_env() -> Result<()> { - use std::os::unix::process::CommandExt as _; - - const REEXEC_ENV: &str = "__OPENSHELL_DRIVER_VM_REEXEC"; - - if std::env::var_os(REEXEC_ENV).is_some() { - return Ok(()); - } - - let runtime_dir = configured_runtime_dir().map_err(|err| miette::miette!("{err}"))?; - let runtime_str = runtime_dir.to_string_lossy(); - let needs_reexec = std::env::var_os("DYLD_LIBRARY_PATH") - .is_none_or(|value| !value.to_string_lossy().contains(runtime_str.as_ref())); - if !needs_reexec { - return Ok(()); - } - - let mut dyld_paths = vec![runtime_dir.clone()]; - if let Some(existing) = std::env::var_os("DYLD_LIBRARY_PATH") { - dyld_paths.extend(std::env::split_paths(&existing)); - } - let joined = std::env::join_paths(&dyld_paths) - .map_err(|err| miette::miette!("join DYLD_LIBRARY_PATH: {err}"))?; - let exe = std::env::current_exe().into_diagnostic()?; - let args: Vec = std::env::args().skip(1).collect(); - - // Use execvp() so the current process is *replaced* by the re-exec'd - // binary — no wrapper process sits between the compute driver and - // the actually-running VM launcher. That avoids two problems: - // 1. An extra process level that survives SIGKILL of the driver - // (the wrapper was reparenting the re-exec'd child to init). - // 2. Signal forwarding: with a wrapper, a SIGTERM to the wrapper - // doesn't reach the child unless we hand-roll forwarding. - // After exec, the child inherits our PID and our procguard arming. - let err = std::process::Command::new(exe) - .args(&args) - .env("DYLD_LIBRARY_PATH", &joined) - .env(VM_RUNTIME_DIR_ENV, runtime_dir) - .env(REEXEC_ENV, "1") - .exec(); - // `exec()` only returns on failure. - Err(miette::miette!("failed to re-exec with runtime env: {err}")) -} - -#[cfg(not(target_os = "macos"))] -// Signature must match the macOS variant which can fail. -#[allow(clippy::unnecessary_wraps)] -fn maybe_reexec_internal_vm_with_runtime_env() -> Result<()> { - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::{Args, ComputeDriverListenMode, compute_driver_listen_mode, parse_vm_mount_arg}; - use clap::Parser; - use std::path::PathBuf; - - #[test] - fn corporate_proxy_flags_parse_into_driver_settings() { - let args = Args::parse_from([ - "openshell-driver-vm", - "--upstream-proxy", - "http://proxy.corp.com:8080", - "--upstream-no-proxy", - "10.0.0.0/8,.svc.cluster.local", - "--upstream-proxy-auth-file", - "/etc/openshell/secrets/proxy-auth", - "--upstream-proxy-auth-allow-insecure", - "--upstream-proxy-connect-by-hostname", - "--upstream-proxy-ca-bundle", - "/etc/openshell/tls/proxy-ca.pem", - ]); - - assert_eq!( - args.upstream_proxy.as_deref(), - Some("http://proxy.corp.com:8080") - ); - assert_eq!( - args.upstream_no_proxy.as_deref(), - Some("10.0.0.0/8,.svc.cluster.local") - ); - assert_eq!( - args.upstream_proxy_auth_file.as_deref(), - Some(PathBuf::from("/etc/openshell/secrets/proxy-auth").as_path()) - ); - assert!(args.upstream_proxy_auth_allow_insecure); - assert!(args.upstream_proxy_connect_by_hostname); - assert_eq!( - args.upstream_proxy_ca_bundle.as_deref(), - Some(PathBuf::from("/etc/openshell/tls/proxy-ca.pem").as_path()) - ); - } - - #[test] - fn ipv6_egress_flags_parse_with_supervisor_names() { - let args = Args::parse_from([ - "openshell-driver-vm", - "--policy-dns-ipv6-egress", - "enabled", - "--nat64-prefix", - "64:ff9b:1::/96", - "--nat64-prefix", - "2001:db8:64::/96", - ]); - assert_eq!( - args.policy_dns_ipv6_egress, - Some(openshell_core::PolicyDnsIpv6Egress::Enabled) - ); - assert_eq!(args.nat64_prefixes, ["64:ff9b:1::/96", "2001:db8:64::/96"]); - assert!( - Args::parse_from(["openshell-driver-vm"]) - .nat64_prefixes - .is_empty() - ); - } - - #[test] - fn corporate_proxy_settings_default_to_unset() { - let args = Args::parse_from(["openshell-driver-vm"]); - assert!(args.upstream_proxy.is_none()); - assert!(args.upstream_no_proxy.is_none()); - assert!(args.upstream_proxy_auth_file.is_none()); - assert!(!args.upstream_proxy_auth_allow_insecure); - assert!(!args.upstream_proxy_connect_by_hostname); - assert!(args.upstream_proxy_ca_bundle.is_none()); - } - - #[test] - fn internal_network_trust_options_have_no_environment_aliases() { - let args = Args::parse_from([ - "openshell-driver-vm", - "--additional-ca-bundle", - "/var/lib/openshell/network/additional-ca.crt", - "--additional-ca-digest", - "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", - "--additional-ca-certificate-count", - "2", - ]); - assert_eq!( - args.additional_ca_bundle.as_deref(), - Some(PathBuf::from("/var/lib/openshell/network/additional-ca.crt").as_path()) - ); - assert_eq!( - args.additional_ca_digest.as_deref(), - Some("sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") - ); - assert_eq!(args.additional_ca_certificate_count, Some(2)); - - temp_env::with_vars( - [ - ( - "OPENSHELL_VM_ADDITIONAL_CA_BUNDLE", - Some("/tmp/untrusted.crt"), - ), - ("OPENSHELL_VM_ADDITIONAL_CA_DIGEST", Some("sha256:bad")), - ("OPENSHELL_VM_ADDITIONAL_CA_CERTIFICATE_COUNT", Some("999")), - ], - || { - let args = Args::parse_from(["openshell-driver-vm"]); - assert!(args.additional_ca_bundle.is_none()); - assert!(args.additional_ca_digest.is_none()); - assert!(args.additional_ca_certificate_count.is_none()); - }, - ); - } - - #[test] - fn listen_mode_rejects_default_tcp() { - let args = Args::parse_from(["openshell-driver-vm"]); - let err = compute_driver_listen_mode(&args).expect_err("default TCP should be disabled"); - assert!(err.contains("--bind-socket is required")); - } - - #[test] - fn accepts_canonical_grpc_endpoint_flag() { - let args = Args::try_parse_from([ - "openshell-driver-vm", - "--grpc-endpoint", - "http://127.0.0.1:8080", - ]) - .unwrap(); - assert_eq!(args.grpc_endpoint.as_deref(), Some("http://127.0.0.1:8080")); - } - - #[test] - fn rejects_legacy_openshell_endpoint_flag() { - let error = Args::try_parse_from([ - "openshell-driver-vm", - "--openshell-endpoint", - "http://127.0.0.1:8080", - ]) - .expect_err("legacy --openshell-endpoint must be rejected"); - assert!(error.to_string().contains("--openshell-endpoint")); - } - - #[test] - fn accepts_gateway_otlp_configuration() { - let args = Args::try_parse_from([ - "openshell-driver-vm", - "--otlp-endpoint", - "http://127.0.0.1:4317", - "--gateway-name", - "production-us-west", - ]); - assert!( - args.is_ok(), - "VM driver should accept the gateway OTLP endpoint" - ); - } - - #[test] - fn listen_mode_rejects_bind_address_without_tcp_opt_in() { - let args = Args::parse_from(["openshell-driver-vm", "--bind-address", "127.0.0.1:50061"]); - let err = - compute_driver_listen_mode(&args).expect_err("TCP bind should require explicit opt-in"); - assert!(err.contains("--allow-unauthenticated-tcp")); - } - - #[test] - fn listen_mode_requires_bind_address_with_tcp_opt_in() { - let args = Args::parse_from(["openshell-driver-vm", "--allow-unauthenticated-tcp"]); - let err = - compute_driver_listen_mode(&args).expect_err("TCP opt-in should require an address"); - assert!(err.contains("--bind-address is required")); - } - - #[test] - fn listen_mode_accepts_explicit_unauthenticated_tcp() { - let args = Args::parse_from([ - "openshell-driver-vm", - "--allow-unauthenticated-tcp", - "--bind-address", - "127.0.0.1:50061", - ]); - assert_eq!( - compute_driver_listen_mode(&args).unwrap(), - ComputeDriverListenMode::Tcp("127.0.0.1:50061".parse().unwrap()) - ); - } - - #[test] - fn listen_mode_requires_expected_peer_pid_for_uds() { - let args = Args::parse_from([ - "openshell-driver-vm", - "--bind-socket", - "/tmp/compute-driver.sock", - ]); - let err = compute_driver_listen_mode(&args) - .expect_err("UDS should require gateway peer pid by default"); - assert!(err.contains("--expected-peer-pid is required")); - } - - #[test] - fn listen_mode_accepts_uds_with_expected_peer_pid() { - let args = Args::parse_from([ - "openshell-driver-vm", - "--bind-socket", - "/tmp/compute-driver.sock", - "--expected-peer-pid", - "42", - ]); - assert_eq!( - compute_driver_listen_mode(&args).unwrap(), - ComputeDriverListenMode::Unix { - socket_path: PathBuf::from("/tmp/compute-driver.sock"), - expected_peer_pid: Some(42), - } - ); - } - - #[test] - fn listen_mode_accepts_explicit_same_uid_uds_dev_mode() { - let args = Args::parse_from([ - "openshell-driver-vm", - "--bind-socket", - "/tmp/compute-driver.sock", - "--allow-same-uid-peer", - ]); - assert_eq!( - compute_driver_listen_mode(&args).unwrap(), - ComputeDriverListenMode::Unix { - socket_path: PathBuf::from("/tmp/compute-driver.sock"), - expected_peer_pid: None, - } - ); - } - - #[test] - fn parse_vm_mount_arg_parses_readonly() { - let m = parse_vm_mount_arg("/host/src\tosfs0\tro").unwrap(); - assert_eq!(m.host_path, PathBuf::from("/host/src")); - assert_eq!(m.tag, "osfs0"); - assert!(m.read_only); - } - - #[test] - fn parse_vm_mount_arg_parses_readwrite() { - let m = parse_vm_mount_arg("/host/src\tosfs1\trw").unwrap(); - assert!(!m.read_only); - } - - #[test] - fn parse_vm_mount_arg_keeps_tag_and_mode_when_source_has_tab() { - let m = parse_vm_mount_arg("/host/src\tvfs9\trw\tosfs0\tro").unwrap(); - assert_eq!(m.host_path, PathBuf::from("/host/src\tvfs9\trw")); - assert_eq!(m.tag, "osfs0"); - assert!(m.read_only); - } - - #[test] - fn parse_vm_mount_arg_rejects_unknown_mode() { - let err = parse_vm_mount_arg("/host/src\tosfs0\treadonly").unwrap_err(); - assert!(err.contains("expected 'ro' or 'rw'")); - } - - #[test] - fn parse_vm_mount_arg_rejects_missing_fields() { - assert!(parse_vm_mount_arg("/host/src\tosfs0").is_err()); - assert!(parse_vm_mount_arg("/host/src").is_err()); - } -} diff --git a/crates/openshell-driver-vm/src/otel_tracing.rs b/crates/openshell-driver-vm/src/otel_tracing.rs deleted file mode 100644 index a931ff502e..0000000000 --- a/crates/openshell-driver-vm/src/otel_tracing.rs +++ /dev/null @@ -1,19 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! OpenTelemetry tracing identity for the VM compute driver. - -pub const TRACING: openshell_otel::ComputeDriverTracing = openshell_otel::compute_driver_tracing!(); - -#[cfg(test)] -mod tests { - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn driver_spans_reach_otlp_collector_with_resource_identity() { - openshell_otel_test_support::assert_compute_driver_tracing( - super::TRACING, - openshell_core::VERSION, - "vm.provision", - ) - .await; - } -} diff --git a/crates/openshell-driver-vm/src/preparation.rs b/crates/openshell-driver-vm/src/preparation.rs deleted file mode 100644 index 115580e862..0000000000 --- a/crates/openshell-driver-vm/src/preparation.rs +++ /dev/null @@ -1,1066 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Own image-preparation processes and the files they may still be writing. -//! -//! A lease is inherited by every preparation subprocess. Cancellation first -//! kills and reaps the worker; staging is removed only after the last lease -//! descriptor closes. A restarted driver uses the same proof of inactivity. - -#![allow(unsafe_code)] - -use std::fs::{self, File, OpenOptions}; -use std::io::{self, Read, Write}; -use std::os::fd::AsRawFd; -use std::os::unix::fs::{OpenOptionsExt, PermissionsExt as _}; -use std::path::{Path, PathBuf}; -use std::process::{ExitStatus, Stdio}; -use std::sync::Arc; -use std::time::Duration; - -use nix::sys::signal::{Signal, killpg}; -use nix::unistd::Pid; -use serde::{Deserialize, Serialize}; -use tokio::process::{Child, ChildStdout, Command}; -use tokio::sync::Mutex; -use tonic::Status; - -use super::{ - OverlayPreparation, RuntimeImagePlan, SandboxOwnerIdentity, VmDriverConfig, - WorkloadIdentityRequest, -}; - -const ATTEMPTS_DIR: &str = "preparations"; -const REQUEST_FILE: &str = "request.json"; -const LEASE_MARKER: &[u8] = b"openshell-image-preparation-v1\n"; -const CLEANUP_TIMEOUT: Duration = Duration::from_secs(10); - -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(super) struct Request { - pub config: VmDriverConfig, - pub sandbox_id: String, - pub image_ref: String, - pub rootfs_tar: Option, - pub bootstrap_only: bool, - pub overlay: Option, - pub lease_fd: i32, - pub parent_pid: u32, -} - -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(super) struct OverlayRequest { - pub source_disk: PathBuf, - pub preparation: OverlayPreparation, - pub requested_identity: Option, -} - -/// Keep the requested selectors across the worker boundary. The worker must -/// validate them against the persisted overlay owner before changing any files; -/// the parent's current default identity cannot substitute for that owner. -#[derive(Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(super) struct WorkloadIdentitySelectors { - user: String, - group: String, -} - -impl From<&WorkloadIdentityRequest> for WorkloadIdentitySelectors { - fn from(request: &WorkloadIdentityRequest) -> Self { - Self { - user: request.user.clone(), - group: request.group.clone(), - } - } -} - -impl From for WorkloadIdentityRequest { - fn from(selectors: WorkloadIdentitySelectors) -> Self { - Self { - user: selectors.user, - group: selectors.group, - } - } -} - -#[derive(Serialize, Deserialize)] -pub(super) enum Output { - Images(RuntimeImagePlan), - Overlay(SandboxOwnerIdentity), -} - -#[derive(Serialize, Deserialize)] -pub(super) enum Message { - Event(Vec), - Complete(Result), -} - -pub(super) struct Attempt { - pub directory: PathBuf, - lease_path: PathBuf, - lease: Option, - child: Option, -} - -/// Cleanup survives cancellation of the provisioning future itself. Lifecycle -/// calls also await the same mutex, so they cannot report completion early. -pub(super) struct CleanupOnDrop(pub Arc>); - -impl Drop for CleanupOnDrop { - fn drop(&mut self) { - let attempt = self.0.clone(); - tokio::spawn(async move { - if let Err(error) = attempt.lock().await.cleanup().await { - tracing::warn!(%error, "image preparation cleanup incomplete; staging retained"); - } - }); - } -} - -impl Attempt { - /// Create and lock the lease before publishing the directory. A concurrent - /// reconciler can never observe this attempt without its ownership lock. - pub fn create(cache_root: &Path) -> io::Result { - let root = cache_root.join(ATTEMPTS_DIR); - fs::create_dir_all(&root)?; - let random = - u128::from_ne_bytes(openshell_crypto::random_bytes::<16>().map_err(io::Error::other)?); - let name = format!("attempt-{random:032x}"); - let directory = root.join(&name); - let lease_path = root.join(format!("{name}.lease")); - let mut lease = OpenOptions::new() - .read(true) - .write(true) - .create_new(true) - .mode(0o600) - .open(&lease_path)?; - lock(&lease, false)?; - lease.write_all(LEASE_MARKER)?; - lease.sync_data()?; - fs::create_dir(&directory)?; - Ok(Self { - directory, - lease_path, - lease: Some(lease), - child: None, - }) - } - - /// Spawn while the caller holds the sandbox registry lock, then register - /// this attempt before yielding. Stop/delete cannot miss a live worker. - pub fn spawn(&mut self, launcher: &Path, mut request: Request) -> io::Result { - let lease = self - .lease - .as_ref() - .ok_or_else(|| io::Error::other("preparation lease is closed"))?; - let fd = lease.as_raw_fd(); - request.lease_fd = fd; - request.parent_pid = std::process::id(); - let request_path = self.directory.join(REQUEST_FILE); - let mut file = OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(&request_path)?; - serde_json::to_writer(&mut file, &request)?; - file.flush()?; - let mut command = Command::new(launcher); - command.arg("--internal-prepare-image").arg(request_path); - command - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::inherit()); - command.process_group(0).kill_on_drop(true); - // SAFETY: the child only makes an async-signal-safe fcntl call. The - // parent keeps this descriptor open until the child has exited. - unsafe { - command.pre_exec(move || { - if libc::fcntl(fd, libc::F_SETFD, 0) == -1 { - return Err(io::Error::last_os_error()); - } - Ok(()) - }); - } - let mut child = command.spawn()?; - let stdout = child - .stdout - .take() - .ok_or_else(|| io::Error::other("preparation stdout is missing"))?; - self.child = Some(child); - Ok(stdout) - } - - pub async fn wait(&mut self) -> io::Result { - // EOF can precede observable process exit. Let normal worker teardown - // finish before signaling, preserving its real status and reserving - // its PID until any remaining descendants have been stopped. - wait_for_worker_exit(self.child.as_ref().and_then(Child::id)).await?; - self.kill_group()?; - self.child - .as_mut() - .ok_or_else(|| io::Error::other("preparation worker is missing"))? - .wait() - .await - } - - /// Do not report successful cleanup while a formatter or other descendant - /// still owns the lease. Preserve uncertain staging for the next reconcile. - pub async fn cleanup(&mut self) -> Result<(), Status> { - let signal_result = self.kill_group(); - #[cfg(target_os = "macos")] - let signal_result = match signal_result { - // Darwin can reject signaling an exiting process before waitid - // exposes its terminal status. Keep immediate cancellation first, - // then retry the same guarded signal only after observing exit. - Err(error) if error.raw_os_error() == Some(libc::EPERM) => { - wait_for_worker_exit(self.child.as_ref().and_then(Child::id)) - .await - .and_then(|()| self.kill_group()) - } - result => result, - }; - signal_result - .map_err(|error| Status::internal(format!("terminate image preparation: {error}")))?; - if let Some(child) = self.child.as_mut() { - tokio::time::timeout(CLEANUP_TIMEOUT, child.wait()) - .await - .map_err(|_| { - Status::deadline_exceeded("image preparation did not stop; staging retained") - })? - .map_err(|error| Status::internal(format!("reap image preparation: {error}")))?; - } - // Do not explicitly unlock: inherited descriptors must continue to - // protect files until the last worker or descendant closes its copy. - self.lease.take(); - let deadline = tokio::time::Instant::now() + CLEANUP_TIMEOUT; - loop { - match reclaim(&self.directory, &self.lease_path) { - Ok(true) => return Ok(()), - Ok(false) if tokio::time::Instant::now() < deadline => { - tokio::time::sleep(Duration::from_millis(20)).await; - } - Ok(false) => { - return Err(Status::deadline_exceeded( - "image preparation descendants still own staging; files retained", - )); - } - Err(error) => { - return Err(Status::internal(format!( - "reclaim image preparation staging: {error}" - ))); - } - } - } - } - - // macOS may replace the staging lease when proving an exited process group - // has no remaining owner; other platforms only read the worker state. - #[cfg_attr(not(target_os = "macos"), allow(clippy::needless_pass_by_ref_mut))] - fn kill_group(&mut self) -> io::Result<()> { - if let Some(id) = self.child.as_ref().and_then(Child::id) { - let pid = i32::try_from(id).map_err(io::Error::other)?; - match killpg(Pid::from_raw(pid), Signal::SIGKILL) { - Ok(()) | Err(nix::errno::Errno::ESRCH) => {} - #[cfg(target_os = "macos")] - Err(nix::errno::Errno::EPERM) - if self.exited_worker_has_no_descendant_owner(id)? => {} - Err(error) => return Err(io::Error::from_raw_os_error(error as i32)), - } - } - Ok(()) - } - - /// Darwin rejects signals to a group containing only an exited leader. - /// Accept that case only while its PID remains reserved and no descendant - /// owns the inherited staging lease. Live or uncertain ownership still fails. - #[cfg(target_os = "macos")] - fn exited_worker_has_no_descendant_owner(&mut self, id: u32) -> io::Result { - if !worker_has_exited(id)? { - return Ok(false); - } - - // Open the probe before dropping our copy so a concurrent reconciler - // cannot remove the lease pathname between release and open. Reacquire - // ownership on success and retain it until the caller reaps the worker. - let lease = OpenOptions::new() - .read(true) - .write(true) - .custom_flags(libc::O_NOFOLLOW) - .open(&self.lease_path)?; - self.lease.take(); - if !lock(&lease, true)? { - return Ok(false); - } - self.lease = Some(lease); - Ok(true) - } -} - -/// Observe termination without releasing the PID or process-group identity. -fn worker_has_exited(id: u32) -> io::Result { - // SAFETY: waitid writes initialized storage. WNOWAIT leaves the owned - // child unreaped, so its PID cannot be reused before descendant signaling. - let mut status: libc::siginfo_t = unsafe { std::mem::zeroed() }; - if unsafe { - libc::waitid( - libc::P_PID, - id, - &raw mut status, - libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, - ) - } != 0 - { - return Err(io::Error::last_os_error()); - } - Ok(matches!( - status.si_code, - libc::CLD_EXITED | libc::CLD_KILLED | libc::CLD_DUMPED - )) -} - -/// Bound EOF-to-exit observation without blocking the runtime or reaping. -/// Dropping this future leaves the worker available to cancellation cleanup. -async fn wait_for_worker_exit(id: Option) -> io::Result<()> { - let Some(id) = id else { - return Ok(()); - }; - tokio::time::timeout(CLEANUP_TIMEOUT, async { - loop { - if worker_has_exited(id)? { - return Ok(()); - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .map_err(|_| { - io::Error::new( - io::ErrorKind::TimedOut, - "image preparation worker did not exit before cleanup deadline", - ) - })? -} - -impl Drop for Attempt { - fn drop(&mut self) { - // Runtime shutdown may prevent the asynchronous reaper from running. - // Signal only this worker's still-unreaped process group; the lease - // remains held by descendants until the kernel closes their files. - let _ = self.kill_group(); - } -} - -/// Remove only directories created by this protocol whose inherited lease has -/// no remaining owner. Legacy staging and shared committed images are outside -/// this namespace and are never inferred to be inactive from their age. -pub(super) fn reconcile(cache_root: &Path) -> io::Result<()> { - let root = cache_root.join(ATTEMPTS_DIR); - let entries = match fs::read_dir(&root) { - Ok(entries) => entries, - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(error), - }; - for entry in entries { - let entry = entry?; - let name = entry.file_name(); - let Some(name) = name.to_str().filter(|name| valid_attempt_name(name)) else { - continue; - }; - if !entry.file_type()?.is_dir() { - continue; - } - if let Err(error) = reclaim(&entry.path(), &root.join(format!("{name}.lease"))) { - tracing::warn!(path = %entry.path().display(), %error, "image preparation ownership uncertain; staging retained"); - } - } - Ok(()) -} - -fn valid_attempt_name(name: &str) -> bool { - name.strip_prefix("attempt-").is_some_and(|suffix| { - suffix.len() == 32 && suffix.bytes().all(|byte| byte.is_ascii_hexdigit()) - }) -} - -fn reclaim(directory: &Path, lease_path: &Path) -> io::Result { - if !directory.try_exists()? && !lease_path.try_exists()? { - return Ok(true); - } - let lease = match OpenOptions::new() - .read(true) - .write(true) - .custom_flags(libc::O_NOFOLLOW) - .open(lease_path) - { - Ok(lease) if lease.metadata()?.is_file() => lease, - Ok(_) => return Ok(false), - Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false), - Err(error) => return Err(error), - }; - if !lock(&lease, true)? { - return Ok(false); - } - let mut marker = Vec::new(); - (&lease).take(64).read_to_end(&mut marker)?; - if marker != LEASE_MARKER { - return Ok(false); - } - match remove_staging_tree(directory) { - Ok(()) => {} - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => return Err(error), - } - match fs::remove_file(lease_path) { - Ok(()) => {} - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => return Err(error), - } - Ok(true) -} - -/// Remove a private staging tree after its writers have stopped. Image -/// directory modes may deny the driver permission to unlink their children. -pub(super) fn remove_staging_tree(path: &Path) -> io::Result<()> { - match fs::remove_dir_all(path) { - Err(err) if err.kind() == io::ErrorKind::PermissionDenied => {} - result => return result, - } - - let mut pending = vec![path.to_owned()]; - while let Some(dir) = pending.pop() { - if dir.symlink_metadata()?.is_dir() { - fs::set_permissions(&dir, fs::Permissions::from_mode(0o700))?; - for child in dir.read_dir()? { - let child = child?; - if child.file_type()?.is_dir() { - pending.push(child.path()); - } - } - } - } - fs::remove_dir_all(path) -} - -fn lock(file: &File, nonblocking: bool) -> io::Result { - let operation = libc::LOCK_EX | if nonblocking { libc::LOCK_NB } else { 0 }; - // SAFETY: flock receives a valid borrowed file descriptor and no pointers. - if unsafe { libc::flock(file.as_raw_fd(), operation) } == 0 { - return Ok(true); - } - let error = io::Error::last_os_error(); - if nonblocking && error.kind() == io::ErrorKind::WouldBlock { - Ok(false) - } else { - Err(error) - } -} - -pub(super) fn cache_lock(cache_root: &Path) -> io::Result { - let file = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) - .mode(0o600) - .custom_flags(libc::O_NOFOLLOW) - .open(cache_root.join("preparation.lock"))?; - lock(&file, false)?; - Ok(file) -} - -/// Publish a complete staged image without replacing a ready cache entry. -/// Preparation stays outside this lock; only the readiness recheck and atomic -/// rename are serialized across workers. Call from a blocking task so the -/// lock remains owned until publication finishes even if its waiter is dropped. -pub(super) fn publish_cache_file( - cache_root: &Path, - staged: &Path, - destination: &Path, - expected_size: Option, -) -> io::Result<()> { - let _lease = cache_lock(cache_root)?; - match fs::metadata(destination) { - Ok(metadata) - if expected_size.is_none_or(|size| metadata.is_file() && metadata.len() == size) => - { - return Ok(()); - } - Ok(_) => {} - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => return Err(error), - } - fs::rename(staged, destination) -} - -pub(super) fn read_request(path: &Path) -> Result<(Request, PathBuf), String> { - use std::os::unix::fs::MetadataExt; - let file = OpenOptions::new() - .read(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) - .open(path) - .map_err(|error| error.to_string())?; - let metadata = file.metadata().map_err(|error| error.to_string())?; - if !metadata.is_file() || metadata.len() > 1024 * 1024 { - return Err( - "image preparation request must be a regular file no larger than 1 MiB".to_string(), - ); - } - let request: Request = serde_json::from_reader(file).map_err(|error| error.to_string())?; - let directory = path - .parent() - .ok_or("preparation request has no directory")?; - let name = directory - .file_name() - .and_then(|name| name.to_str()) - .filter(|name| valid_attempt_name(name)) - .ok_or("invalid preparation directory name")?; - let expected_root = super::image_cache_root_dir(&request.config.state_dir).join(ATTEMPTS_DIR); - if path.file_name().and_then(|name| name.to_str()) != Some(REQUEST_FILE) - || directory.parent() != Some(expected_root.as_path()) - { - return Err("preparation request is outside the driver staging directory".to_string()); - } - let lease_file = OpenOptions::new() - .read(true) - .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) - .open(expected_root.join(format!("{name}.lease"))) - .map_err(|error| error.to_string())?; - let lease = lease_file.metadata().map_err(|error| error.to_string())?; - if !lease.is_file() { - return Err("image preparation lease must be a regular file".to_string()); - } - let mut marker = Vec::new(); - lease_file - .take(64) - .read_to_end(&mut marker) - .map_err(|error| error.to_string())?; - if marker != LEASE_MARKER { - return Err("image preparation lease marker is invalid".to_string()); - } - // SAFETY: fstat writes only to the supplied initialized stat storage. An - // invalid inherited descriptor is rejected rather than taken into ownership. - let mut inherited: libc::stat = unsafe { std::mem::zeroed() }; - if request.lease_fd < 3 || unsafe { libc::fstat(request.lease_fd, &raw mut inherited) } != 0 { - return Err("image preparation lease was not inherited".to_string()); - } - // Match MetadataExt::dev's representation: Darwin dev_t is signed, while - // Linux dev_t is already u64. The cast intentionally preserves that API's - // conversion, including the sign extension of a signed device identifier. - #[allow(clippy::cast_sign_loss, trivial_numeric_casts)] - let inherited_device = inherited.st_dev as u64; - if inherited.st_ino != lease.ino() || inherited_device != lease.dev() { - return Err("image preparation lease was not inherited".to_string()); - } - Ok((request, directory.to_path_buf())) -} - -/// A process-group watcher also covers host utilities on Linux, where a -/// parent-death signal on the worker alone cannot kill its children. -pub(super) fn watch_parent(parent_pid: u32) -> Result<(), String> { - let expected = i32::try_from(parent_pid).map_err(|error| error.to_string())?; - if nix::unistd::getpgrp() != nix::unistd::getpid() { - return Err("preparation worker must own its process group".to_string()); - } - std::thread::Builder::new() - .name("image-prep-parent".to_string()) - .spawn(move || { - loop { - if nix::unistd::getppid().as_raw() != expected { - let _ = killpg(nix::unistd::getpgrp(), Signal::SIGKILL); - std::process::exit(1); - } - std::thread::sleep(Duration::from_millis(50)); - } - }) - .map_err(|error| error.to_string())?; - Ok(()) -} - -pub(super) fn send(message: &Message) -> io::Result<()> { - let mut output = io::stdout().lock(); - serde_json::to_writer(&mut output, message)?; - output.write_all(b"\n")?; - output.flush() -} - -#[cfg(test)] -mod tests { - use super::*; - use std::os::unix::fs::{PermissionsExt, symlink}; - - #[test] - fn removes_inaccessible_staging_directories_without_following_links() { - let temp = tempfile::tempdir().unwrap(); - let dir = temp.path().join("staged"); - let outside = temp.path().join("outside"); - fs::create_dir(&dir).unwrap(); - fs::create_dir(&outside).unwrap(); - fs::write(outside.join("keep"), b"outside").unwrap(); - fs::set_permissions(&outside, fs::Permissions::from_mode(0o750)).unwrap(); - symlink(&outside, dir.join("link")).unwrap(); - fs::set_permissions(&dir, fs::Permissions::from_mode(0o000)).unwrap(); - remove_staging_tree(&dir).unwrap(); - assert!(!dir.exists()); - assert_eq!(fs::read(outside.join("keep")).unwrap(), b"outside"); - assert_eq!( - fs::metadata(outside).unwrap().permissions().mode() & 0o777, - 0o750 - ); - } - - fn request(root: &Path) -> Request { - Request { - config: VmDriverConfig { - state_dir: root.to_path_buf(), - ..VmDriverConfig::default() - }, - sandbox_id: "test-sandbox".to_string(), - image_ref: "test-image".to_string(), - rootfs_tar: None, - bootstrap_only: false, - overlay: None, - lease_fd: -1, - parent_pid: 0, - } - } - - async fn wait_for_file(path: &Path) { - tokio::time::timeout(Duration::from_secs(5), async { - while !path.exists() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("worker readiness"); - } - - async fn wait_for_worker_exit_without_reaping(attempt: &Attempt) { - let id = attempt.child.as_ref().unwrap().id().unwrap(); - tokio::time::timeout(Duration::from_secs(5), async { - loop { - let exited = { - // SAFETY: waitid writes initialized exit information and - // WNOWAIT leaves the owned child's PID reserved for cleanup. - let mut status: libc::siginfo_t = unsafe { std::mem::zeroed() }; - assert_eq!( - unsafe { - libc::waitid( - libc::P_PID, - id, - &raw mut status, - libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, - ) - }, - 0 - ); - matches!( - status.si_code, - libc::CLD_EXITED | libc::CLD_KILLED | libc::CLD_DUMPED - ) - }; - if exited { - break; - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("worker must exit without being reaped"); - } - - async fn worker_at_stdout_eof(temp: &tempfile::TempDir, script: &str) -> Attempt { - let launcher = temp.path().join("worker"); - fs::write(&launcher, script).unwrap(); - fs::set_permissions(&launcher, fs::Permissions::from_mode(0o700)).unwrap(); - let cache = super::super::image_cache_root_dir(temp.path()); - let mut attempt = Attempt::create(&cache).unwrap(); - let mut stdout = attempt.spawn(&launcher, request(temp.path())).unwrap(); - let mut output = Vec::new(); - tokio::time::timeout( - Duration::from_secs(5), - tokio::io::AsyncReadExt::read_to_end(&mut stdout, &mut output), - ) - .await - .expect("worker must close stdout") - .unwrap(); - attempt - } - - #[tokio::test] - async fn stdout_eof_keeps_successful_worker_exit_status() { - let temp = tempfile::tempdir().unwrap(); - // stdout can close before the kernel exposes the final exit status. - // Keep that interval deterministic without requiring scheduler timing. - let mut attempt = - worker_at_stdout_eof(&temp, "#!/bin/sh\nexec 1>&-\nsleep 0.1\nexit 0\n").await; - let status = attempt.wait().await; - attempt.cleanup().await.expect("cleanup EOF worker"); - - let status = status.expect("wait after stdout EOF"); - assert!(status.success(), "worker exit after stdout EOF: {status}"); - assert!(!attempt.directory.exists()); - } - - #[tokio::test] - async fn stdout_eof_with_live_descendant_cleans_group_after_worker_exit() { - let temp = tempfile::tempdir().unwrap(); - let mut attempt = worker_at_stdout_eof( - &temp, - "#!/bin/sh\nsleep 300 >/dev/null &\nexec 1>&-\nsleep 0.1\nexit 0\n", - ) - .await; - let status = attempt.wait().await; - attempt.cleanup().await.expect("stop inherited lease owner"); - - let status = status.expect("preserve leader status"); - assert!(status.success(), "worker exit with descendant: {status}"); - assert!(!attempt.directory.exists()); - assert!(attempt.child.as_ref().unwrap().id().is_none()); - } - - #[tokio::test] - async fn cancelling_stdout_eof_wait_leaves_worker_for_cleanup() { - let temp = tempfile::tempdir().unwrap(); - let mut attempt = worker_at_stdout_eof(&temp, "#!/bin/sh\nexec 1>&-\nsleep 300\n").await; - let result = tokio::time::timeout(Duration::from_millis(50), attempt.wait()).await; - attempt - .cleanup() - .await - .expect("cancelled wait cleans worker"); - - assert!(result.is_err(), "waiting for exit must remain cancellable"); - assert!(!attempt.directory.exists()); - assert!(attempt.child.as_ref().unwrap().id().is_none()); - } - - #[cfg(target_os = "macos")] - #[tokio::test] - async fn cleanup_after_stdout_eof_waits_for_exit_publication() { - // Repeated natural exits exercise Darwin's short interval between - // closing stdout and making terminal status observable to waitid. - for _ in 0..8 { - let temp = tempfile::tempdir().unwrap(); - let mut attempt = worker_at_stdout_eof(&temp, "#!/bin/sh\nexit 0\n").await; - let result = attempt.cleanup().await; - if result.is_err() { - // Reap this owned worker even when checking faulty behavior. - attempt.cleanup().await.expect("retry owned test cleanup"); - } - result.expect("natural EOF must not fail cancellation cleanup"); - assert!(!attempt.directory.exists()); - } - } - - #[tokio::test] - async fn completed_worker_without_descendants_keeps_successful_exit_status() { - let temp = tempfile::tempdir().unwrap(); - let cache = super::super::image_cache_root_dir(temp.path()); - let launcher = temp.path().join("worker"); - fs::write(&launcher, "#!/bin/sh\nexit 0\n").unwrap(); - fs::set_permissions(&launcher, fs::Permissions::from_mode(0o700)).unwrap(); - let mut attempt = Attempt::create(&cache).unwrap(); - let directory = attempt.directory.clone(); - let _stdout = attempt.spawn(&launcher, request(temp.path())).unwrap(); - wait_for_worker_exit_without_reaping(&attempt).await; - - // macOS rejects killpg for a group containing only a zombie. The - // completed worker must still return its original successful status. - assert!( - attempt - .wait() - .await - .expect("completed worker status") - .success() - ); - attempt.cleanup().await.expect("reclaim completed attempt"); - assert!(!directory.exists()); - assert!(attempt.child.as_ref().unwrap().id().is_none()); - } - - #[tokio::test] - async fn exited_worker_with_live_descendant_stops_writer_before_cleanup() { - let temp = tempfile::tempdir().unwrap(); - let cache = super::super::image_cache_root_dir(temp.path()); - let launcher = temp.path().join("worker"); - fs::write(&launcher, "#!/bin/sh\nsleep 300 &\nexit 0\n").unwrap(); - fs::set_permissions(&launcher, fs::Permissions::from_mode(0o700)).unwrap(); - let mut attempt = Attempt::create(&cache).unwrap(); - let directory = attempt.directory.clone(); - let _stdout = attempt.spawn(&launcher, request(temp.path())).unwrap(); - wait_for_worker_exit_without_reaping(&attempt).await; - - #[cfg(target_os = "macos")] - { - let id = attempt.child.as_ref().unwrap().id().unwrap(); - assert!( - !attempt.exited_worker_has_no_descendant_owner(id).unwrap(), - "an exited leader cannot prove its live descendant stopped" - ); - assert!(directory.exists()); - } - attempt - .cleanup() - .await - .expect("kill the live descendant before reclaiming its staging"); - assert!(!directory.exists()); - assert!(attempt.child.as_ref().unwrap().id().is_none()); - } - - #[tokio::test] - async fn cleanup_kills_and_reaps_worker_and_formatter_before_removing_staging() { - let temp = tempfile::tempdir().unwrap(); - let cache = super::super::image_cache_root_dir(temp.path()); - let launcher = temp.path().join("worker"); - // The shell and the simulated formatter both inherit the attempt lease. - // Killing only the shell leaves the lease locked and makes cleanup fail. - fs::write(&launcher, "#!/bin/sh\nroot=$(dirname \"$2\")\nsleep 300 &\nprintf '%s' \"$!\" > \"$root/ready\"\nwait\n").unwrap(); - fs::set_permissions(&launcher, fs::Permissions::from_mode(0o700)).unwrap(); - let mut attempt = Attempt::create(&cache).unwrap(); - let directory = attempt.directory.clone(); - let _stdout = attempt.spawn(&launcher, request(temp.path())).unwrap(); - wait_for_file(&directory.join("ready")).await; - #[cfg(target_os = "macos")] - { - let id = attempt.child.as_ref().unwrap().id().unwrap(); - assert!(!attempt.exited_worker_has_no_descendant_owner(id).unwrap()); - assert!(attempt.lease.is_some(), "a live worker retains its lease"); - } - reconcile(&cache).unwrap(); - assert!(directory.exists(), "a live formatter protects its staging"); - attempt - .cleanup() - .await - .expect("stop and reclaim preparation"); - assert!(!directory.exists()); - assert!(!attempt.lease_path.exists()); - assert!( - attempt - .child - .as_mut() - .unwrap() - .try_wait() - .unwrap() - .is_some() - ); - attempt.cleanup().await.expect("cleanup is idempotent"); - } - - #[tokio::test] - async fn aborting_provisioning_still_runs_cleanup() { - let temp = tempfile::tempdir().unwrap(); - let cache = super::super::image_cache_root_dir(temp.path()); - let attempt = Arc::new(Mutex::new(Attempt::create(&cache).unwrap())); - let directory = attempt.lock().await.directory.clone(); - fs::write(directory.join("partial.ext4"), b"unfinished image").unwrap(); - let (ready, started) = tokio::sync::oneshot::channel(); - let task = tokio::spawn({ - let attempt = attempt.clone(); - async move { - let _cleanup = CleanupOnDrop(attempt); - ready.send(()).unwrap(); - std::future::pending::<()>().await; - } - }); - started.await.unwrap(); - task.abort(); - assert!(task.await.unwrap_err().is_cancelled()); - tokio::time::timeout(Duration::from_secs(5), async { - while directory.exists() { - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await - .expect("cancelled future must reclaim its staging"); - } - - #[test] - fn restart_reclaims_inactive_attempts_and_preserves_active_shared_and_unknown_data() { - let temp = tempfile::tempdir().unwrap(); - let cache = super::super::image_cache_root_dir(temp.path()); - let attempts = cache.join(ATTEMPTS_DIR); - fs::create_dir_all(&attempts).unwrap(); - // Model files left by a terminated driver without opening a live lease. - // A dropped lease can remain locked briefly when a concurrent fork has - // inherited its descriptor and not yet closed it during exec. - let inactive_directory = attempts.join(format!("attempt-{:032x}", 3)); - fs::create_dir(&inactive_directory).unwrap(); - fs::write(inactive_directory.join("partial.ext4"), b"unfinished").unwrap(); - fs::write(inactive_directory.with_extension("lease"), LEASE_MARKER).unwrap(); - let active = Attempt::create(&cache).unwrap(); - let committed = cache.join("shared-image"); - fs::create_dir(&committed).unwrap(); - fs::write(committed.join("rootfs.ext4"), b"valid shared image").unwrap(); - let legacy = cache.join("image.staging-legacy"); - fs::create_dir(&legacy).unwrap(); - let unmarked = attempts.join(format!("attempt-{:032x}", 1)); - fs::create_dir(&unmarked).unwrap(); - let link = attempts.join(format!("attempt-{:032x}", 2)); - symlink(&committed, &link).unwrap(); - fs::write(unmarked.with_extension("lease"), b"unrelated lock").unwrap(); - - reconcile(&cache).unwrap(); - - assert!(!inactive_directory.exists()); - assert!(active.directory.exists()); - assert_eq!( - fs::read(committed.join("rootfs.ext4")).unwrap(), - b"valid shared image" - ); - assert!(legacy.exists()); - assert!(unmarked.exists()); - assert!(link.is_symlink()); - } - - #[tokio::test] - async fn separate_workers_serialize_cache_publication() { - let temp = tempfile::tempdir().unwrap(); - let cache = temp.path().to_path_buf(); - let first = cache_lock(&cache).unwrap(); - let (entered, mut receiver) = tokio::sync::mpsc::channel(1); - let second = tokio::task::spawn_blocking(move || { - let _second = cache_lock(&cache).unwrap(); - entered.blocking_send(()).unwrap(); - }); - assert!( - tokio::time::timeout(Duration::from_millis(50), receiver.recv()) - .await - .is_err() - ); - drop(first); - tokio::time::timeout(Duration::from_secs(5), receiver.recv()) - .await - .unwrap() - .unwrap(); - second.await.unwrap(); - } - - #[test] - fn cache_lock_child_process_helper() { - let Some(root) = std::env::var_os("OPENSHELL_TEST_PUBLICATION_LOCK_ROOT") else { - return; - }; - let root = PathBuf::from(root); - let name = std::env::var("OPENSHELL_TEST_PUBLICATION_LOCK_NAME").unwrap(); - fs::write(root.join(format!("{name}.waiting")), b"waiting").unwrap(); - if name == "second" { - let probe = OpenOptions::new() - .read(true) - .write(true) - .open(root.join("preparation.lock")) - .unwrap(); - assert!( - !lock(&probe, true).unwrap(), - "first process must own the kernel lock" - ); - fs::write(root.join("second.contended"), b"contended").unwrap(); - } - if name == "second" { - publish_cache_file( - &root, - &root.join("second.staged"), - &root.join("committed"), - Some(5), - ) - .unwrap(); - fs::write(root.join("second.acquired"), b"published").unwrap(); - return; - } - let _lock = cache_lock(&root).unwrap(); - fs::write(root.join(format!("{name}.acquired")), b"acquired").unwrap(); - let mut release = [0_u8; 1]; - io::stdin().read_exact(&mut release).unwrap(); - } - - struct LockHelper(std::process::Child); - - impl Drop for LockHelper { - fn drop(&mut self) { - let _ = self.0.kill(); - let _ = self.0.wait(); - } - } - - #[test] - fn publication_lock_is_exclusive_across_processes_and_released_on_death() { - let root = tempfile::tempdir().unwrap(); - let spawn = |name: &str| { - LockHelper( - std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "driver::preparation::tests::cache_lock_child_process_helper", - "--nocapture", - ]) - .env("OPENSHELL_TEST_PUBLICATION_LOCK_ROOT", root.path()) - .env("OPENSHELL_TEST_PUBLICATION_LOCK_NAME", name) - .stdin(Stdio::piped()) - .stdout(Stdio::null()) - .stderr(Stdio::inherit()) - .spawn() - .unwrap(), - ) - }; - let wait_for = |name: &str| { - let deadline = std::time::Instant::now() + Duration::from_secs(5); - while !root.path().join(name).exists() { - assert!( - std::time::Instant::now() < deadline, - "helper did not reach {name}" - ); - std::thread::sleep(Duration::from_millis(10)); - } - }; - fs::write(root.path().join("second.staged"), b"later").unwrap(); - let mut first = spawn("first"); - wait_for("first.acquired"); - let mut second = spawn("second"); - wait_for("second.contended"); - assert!( - !root.path().join("second.acquired").exists(), - "second process bypassed lock" - ); - // The lock holder commits before dying. The queued publisher must read - // readiness only after it owns the lock and preserve this complete image. - fs::write(root.path().join("committed"), b"first").unwrap(); - first.0.kill().unwrap(); - first.0.wait().unwrap(); - wait_for("second.acquired"); - assert!(second.0.wait().unwrap().success()); - assert_eq!(fs::read(root.path().join("committed")).unwrap(), b"first"); - assert!(root.path().join("second.staged").exists()); - assert!(root.path().join("preparation.lock").exists()); - // An invalid-sized template can be replaced; a valid rootfs cannot. - fs::write(root.path().join("second.staged"), b"new!").unwrap(); - publish_cache_file( - root.path(), - &root.path().join("second.staged"), - &root.path().join("committed"), - Some(4), - ) - .unwrap(); - assert_eq!(fs::read(root.path().join("committed")).unwrap(), b"new!"); - fs::write(root.path().join("third.staged"), b"third").unwrap(); - publish_cache_file( - root.path(), - &root.path().join("third.staged"), - &root.path().join("committed"), - None, - ) - .unwrap(); - assert_eq!(fs::read(root.path().join("committed")).unwrap(), b"new!"); - } - - #[test] - fn worker_rejects_request_without_inherited_lease() { - let temp = tempfile::tempdir().unwrap(); - let cache = super::super::image_cache_root_dir(temp.path()); - let attempt = Attempt::create(&cache).unwrap(); - let path = attempt.directory.join(REQUEST_FILE); - fs::write(&path, serde_json::to_vec(&request(temp.path())).unwrap()).unwrap(); - let error = read_request(&path) - .err() - .expect("missing inherited fd rejected"); - assert!(error.contains("lease was not inherited")); - } -} diff --git a/crates/openshell-driver-vm/src/procguard.rs b/crates/openshell-driver-vm/src/procguard.rs deleted file mode 100644 index 5f89f0848c..0000000000 --- a/crates/openshell-driver-vm/src/procguard.rs +++ /dev/null @@ -1,197 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Cross-platform "die when my parent dies" primitive. -//! -//! The VM driver spawns a chain of subprocesses (compute driver → `--internal-run-vm` -//! launcher → libkrun fork). If any link in that chain is killed -//! with SIGKILL — or simply crashes — the children are reparented to init -//! and survive indefinitely, leaking libkrun workers. -//! -//! This module exposes two functions: -//! * [`die_with_parent`] — configure the kernel (Linux) or a helper -//! thread (BSDs, incl. macOS) to SIGKILL the current process when its -//! parent dies. Call it from `main` in every subprocess we spawn -//! along the chain. Idempotent-ish (each call is a full setup — see -//! the runtime.rs comment at the single call site). -//! * [`die_with_parent_cleanup`] — same as above, but on the BSD path a -//! best-effort cleanup callback runs *before* this process exits. -//! This matters when we own a non-Rust child that -//! cannot arm its own procguard; the callback lets us SIGTERM it -//! first. -//! -//! The Linux path uses `nix::sys::prctl::set_pdeathsig(SIGKILL)`, and -//! the BSD path uses `smol-rs/polling` with its `kqueue::Process` + -//! `ProcessOps::Exit` filter. Both are well-tested library surfaces; -//! we keep only the glue code and the pre-arming parent-liveness -//! re-check. - -/// Arrange for the current process to receive SIGKILL if its parent dies. -/// -/// On Linux this sets `PR_SET_PDEATHSIG` to SIGKILL (via -/// `nix::sys::prctl`). The kernel delivers SIGKILL the moment -/// `getppid()` changes away from the original parent. -/// -/// On the BSD family (macOS, FreeBSD, etc.) this spawns a detached -/// helper thread that uses `kqueue` with `EVFILT_PROC | NOTE_EXIT` on -/// the parent PID. When the parent exits the thread calls `exit(1)`, -/// which is sufficient for our use case — we are not a critical daemon -/// that needs to drain state; we are a VM launcher / gRPC driver whose -/// entire job is tied to the parent's lifetime. -pub fn die_with_parent() -> Result<(), String> { - die_with_parent_cleanup(|| ()) -} - -/// Like [`die_with_parent`], but run `cleanup` before terminating. -/// -/// The cleanup hook is best-effort and async-signal-unsafe — it runs on -/// the helper thread immediately before terminating the process. Use this -/// when we own children that cannot arm their own procguard; the cleanup -/// hook is the only chance we get to send them SIGTERM after the kernel -/// reparents us. -/// -/// On Linux the cleanup is a no-op: `PR_SET_PDEATHSIG` delivers SIGKILL -/// directly to us, there is no Rust-controlled moment between "parent -/// died" and "we die" in which we could run a callback. -pub fn die_with_parent_cleanup(cleanup: F) -> Result<(), String> -where - F: FnOnce() + Send + 'static, -{ - #[cfg(target_os = "linux")] - { - // Linux has no opportunity for a cleanup hook — the kernel - // delivers SIGKILL directly. Callers that need pre-exit cleanup - // must combine this with a `pre_exec` PR_SET_PDEATHSIG on their - // children (so the kernel cascades) or rely on process-group - // killpg from a signal handler in the parent. - let _ = cleanup; // intentionally dropped - install_linux_pdeathsig() - } - - #[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "dragonfly", - ))] - { - install_bsd_kqueue_watcher(cleanup) - } - - #[cfg(not(any( - target_os = "linux", - target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "dragonfly", - )))] - { - let _ = cleanup; - Ok(()) - } -} - -#[cfg(target_os = "linux")] -fn install_linux_pdeathsig() -> Result<(), String> { - use nix::sys::signal::Signal; - use nix::unistd::getppid; - - // Race: if the parent already died between fork/exec and this call, - // `getppid()` now returns 1 and PR_SET_PDEATHSIG will never fire. - // Read the current parent first so we can detect that case and exit. - let original_ppid = getppid(); - if original_ppid == nix::unistd::Pid::from_raw(1) { - return Err("process was already orphaned before procguard armed".to_string()); - } - - nix::sys::prctl::set_pdeathsig(Signal::SIGKILL) - .map_err(|err| format!("prctl(PR_SET_PDEATHSIG) failed: {err}"))?; - - // Re-check after arming: the parent may have died between getppid() - // and prctl(). If so, PR_SET_PDEATHSIG missed its window. - if getppid() != original_ppid { - return Err("parent exited before procguard could arm".to_string()); - } - - Ok(()) -} - -#[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", - target_os = "dragonfly", -))] -fn install_bsd_kqueue_watcher(cleanup: F) -> Result<(), String> -where - F: FnOnce() + Send + 'static, -{ - use nix::unistd::getppid; - use polling::os::kqueue::{PollerKqueueExt, Process, ProcessOps}; - use polling::{Events, PollMode, Poller}; - - let parent_pid = getppid(); - if parent_pid == nix::unistd::Pid::from_raw(1) { - return Err("process was already orphaned before procguard armed".to_string()); - } - let parent_pid_nz = std::num::NonZeroI32::new(parent_pid.as_raw()) - .ok_or_else(|| "getppid returned 0 unexpectedly".to_string())?; - - // Build the poller on the caller's thread so any setup error - // surfaces synchronously. `EVFILT_PROC | NOTE_EXIT` is a one-shot - // filter, so `PollMode::Oneshot` matches the kernel semantics. - // - // SAFETY: `Process::from_pid` requires the PID to "be tied to an - // actual child process". Our parent is alive at this point — we - // re-check `getppid()` immediately after registration to close the - // race where the parent dies between the read above and the - // `add_filter` call. The BSD kqueue implementation accepts any - // live PID, not just our own children; the "child" wording in the - // polling docs is carried over from historical terminology in the - // kqueue(2) manpage. The kernel guarantees NOTE_EXIT fires if the - // PID is valid at registration. - let poller = Poller::new().map_err(|err| format!("polling: Poller::new failed: {err}"))?; - let key = 1; - #[allow(unsafe_code)] - // SAFETY requirement is documented on the enclosing function: the - // PID was just read from `getppid()` and re-checked below, so it - // points at a live process. `Process::from_pid` is an - // entry-in-the-kernel-table registration — the kernel validates - // the PID when the filter is added. - let filter = unsafe { Process::from_pid(parent_pid_nz, ProcessOps::Exit) }; - poller - .add_filter(filter, key, PollMode::Oneshot) - .map_err(|err| format!("polling: add_filter(NOTE_EXIT, {parent_pid_nz}) failed: {err}"))?; - - // Between getppid() and the registered filter the parent may - // already have died. Detect that and abort so the caller can bail. - if getppid() != parent_pid { - return Err("parent exited before procguard could arm".to_string()); - } - - // Hand off to a dedicated OS thread. Block in `poller.wait()` - // until the single NOTE_EXIT event fires, run the cleanup, then - // exit. We prefer `exit(1)` over `kill(getpid, SIGKILL)` so the - // callback gets to complete — SIGKILL would race it. Our children - // have their own procguards armed and will notice `getppid() == - // 1` shortly after, so we do not need Linux-semantics exactness. - std::thread::Builder::new() - .name("procguard".to_string()) - .spawn(move || { - let mut events = Events::new(); - // Block indefinitely; the filter is Oneshot so we expect - // exactly one event (parent's NOTE_EXIT) or a spurious - // wakeup we treat the same way. - let _ = poller.wait(&mut events, None); - let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(cleanup)); - std::process::exit(1); - }) - .map(|_| ()) - .map_err(|e| format!("failed to spawn procguard thread: {e}")) -} diff --git a/crates/openshell-driver-vm/src/registry_cache_tests.rs b/crates/openshell-driver-vm/src/registry_cache_tests.rs deleted file mode 100644 index b71d0d5db0..0000000000 --- a/crates/openshell-driver-vm/src/registry_cache_tests.rs +++ /dev/null @@ -1,680 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use super::*; -use oci_client::client::ClientProtocol; -use oci_client::manifest::OCI_IMAGE_INDEX_MEDIA_TYPE; -use tokio::io::AsyncReadExt as _; - -/// A loopback registry with independent HEAD identity and GET contents. Blob -/// requests without fixture contents fail before reaching a VM or formatter. -struct Registry { - address: String, - requests: Arc>>, - server: JoinHandle<()>, -} - -impl Registry { - async fn start( - head_digest: String, - objects: HashMap>, - get_digest: Option, - mut retry_once: bool, - ) -> Self { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap().to_string(); - let requests = Arc::new(std::sync::Mutex::new(Vec::new())); - let recorded = requests.clone(); - let server = tokio::spawn(async move { - loop { - let (mut stream, _) = listener.accept().await.unwrap(); - openshell_core::net::set_tcp_nodelay_best_effort(&stream); - let mut request = Vec::new(); - while !request.ends_with(b"\r\n\r\n") { - request.push(stream.read_u8().await.unwrap()); - assert!(request.len() < 16 * 1024); - } - let request = String::from_utf8(request).unwrap(); - let mut parts = request.split_whitespace(); - let method = parts.next().unwrap(); - let path = parts.next().unwrap(); - recorded.lock().unwrap().push(format!("{method} {path}")); - let manifest = path.strip_prefix("/v2/test/image/manifests/"); - let mut digest = None; - let (status, body) = if path == "/v2/" { - ("200 OK", b"{}".as_slice()) - } else if manifest.is_some() && method == "HEAD" { - digest = Some(head_digest.clone()); - ("200 OK", b"".as_slice()) - } else if let Some(body) = manifest.and_then(|key| objects.get(key)) { - if retry_once { - retry_once = false; - ("503 Service Unavailable", b"retry".as_slice()) - } else { - digest = Some(get_digest.clone().unwrap_or_else(|| sha256(body))); - ("200 OK", body.as_slice()) - } - } else if let Some(body) = path - .strip_prefix("/v2/test/image/blobs/") - .and_then(|key| objects.get(key)) - { - ("200 OK", body.as_slice()) - } else { - ("404 Not Found", b"fixture has no blob".as_slice()) - }; - let digest_header = digest.map_or_else(String::new, |value| { - format!("Docker-Content-Digest: {value}\r\n") - }); - let response = format!( - "HTTP/1.1 {status}\r\nContent-Type: application/json\r\n{digest_header}Content-Length: {}\r\nConnection: close\r\n\r\n", - body.len() - ); - stream.write_all(response.as_bytes()).await.unwrap(); - stream.write_all(body).await.unwrap(); - stream.shutdown().await.unwrap(); - } - }); - Self { - address, - requests, - server, - } - } - - async fn with_layers(layers: Vec<(&str, Vec)>) -> Self { - let mut manifest: serde_json::Value = serde_json::from_slice(&manifest("config")).unwrap(); - let mut objects = HashMap::new(); - manifest["layers"] = layers - .into_iter() - .map(|(media_type, bytes)| { - let digest = sha256(&bytes); - let descriptor = serde_json::json!({ - "mediaType": media_type, "digest": digest, "size": bytes.len() - }); - objects.insert(digest, bytes); - descriptor - }) - .collect(); - let body = serde_json::to_vec(&manifest).unwrap(); - let digest = sha256(&body); - objects.insert(digest.clone(), body.clone()); - objects.insert("latest".into(), body); - Self::start(digest, objects, None, false).await - } - - fn reference(&self, digest: Option<&str>) -> String { - let suffix = digest.map_or_else(|| ":latest".to_string(), |value| format!("@{value}")); - format!("{}/test/image{suffix}", self.address) - } - - fn requests(&self) -> Vec { - self.requests.lock().unwrap().clone() - } -} - -impl Drop for Registry { - fn drop(&mut self) { - self.server.abort(); - } -} - -fn client() -> OciClient { - OciClient::new(ClientConfig { - protocol: ClientProtocol::Http, - platform_resolver: Some(Box::new(linux_platform_resolver)), - no_proxy: Some("*".to_string()), - read_timeout: Some(Duration::from_secs(5)), - connect_timeout: Some(Duration::from_secs(5)), - ..Default::default() - }) -} - -fn sha256(body: &[u8]) -> String { - format!("sha256:{:x}", Sha256::digest(body)) -} - -fn manifest(label: &str) -> Vec { - serde_json::to_vec(&serde_json::json!({ - "schemaVersion": 2, - "mediaType": OCI_IMAGE_MEDIA_TYPE, - "config": { - "mediaType": "application/vnd.oci.image.config.v1+json", - "digest": sha256(label.as_bytes()), - "size": label.len(), - }, - "layers": [{ - "mediaType": "application/vnd.oci.image.layer.v1.tar", - "digest": sha256(label.as_bytes()), - "size": label.len(), - }], - })) - .unwrap() -} - -fn index(body: &[u8]) -> Vec { - serde_json::to_vec(&serde_json::json!({ - "schemaVersion": 2, - "mediaType": OCI_IMAGE_INDEX_MEDIA_TYPE, - "manifests": [{ - "mediaType": OCI_IMAGE_MEDIA_TYPE, - "digest": sha256(body), - "size": body.len(), - "platform": { "os": "linux", "architecture": linux_oci_arch() }, - }], - })) - .unwrap() -} - -fn driver(root: &Path) -> VmDriver { - let socket_root_fd = rustix::fs::open( - root, - rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY, - rustix::fs::Mode::empty(), - ) - .unwrap(); - VmDriver { - config: VmDriverConfig { - state_dir: root.to_path_buf(), - ..Default::default() - }, - socket_root: root.to_path_buf(), - socket_root_fd: Arc::new(socket_root_fd), - launcher_bin: root.join("unused-vm-launcher"), - registry: Arc::new(Mutex::new(HashMap::new())), - image_cache_lock: Arc::new(Mutex::new(())), - preparation_root: None, - events: broadcast::channel(WATCH_BUFFER).0, - gpu_inventory: None, - lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), - } -} - -async fn ensure_image( - driver: &VmDriver, - image_ref: &str, - client: &OciClient, - bootstrap: bool, -) -> Result { - if bootstrap { - driver - .ensure_cached_registry_rootfs_image( - "test", - image_ref, - client, - &RegistryAuth::Anonymous, - ) - .await - } else { - driver - .ensure_prepared_registry_image_disk( - "test", - image_ref, - Path::new("unused"), - client, - &RegistryAuth::Anonymous, - ) - .await - .map(|prepared| prepared.image_identity) - } -} - -async fn rejects_unbound_manifest(bootstrap: bool) { - // The GET body and its header agree with each other, but not with HEAD. - // Before the fix this passed manifest verification and requested blobs. - let trusted = manifest("trusted"); - let replacement = manifest("replacement"); - let trusted_digest = sha256(&trusted); - let registry = Registry::start( - trusted_digest.clone(), - HashMap::from([ - ("latest".to_string(), replacement.clone()), - (trusted_digest.clone(), replacement), - ]), - None, - false, - ) - .await; - let root = tempfile::tempdir().unwrap(); - let driver = driver(root.path()); - let identity = if bootstrap { - bootstrap_image_cache_identity(&trusted_digest) - } else { - prepared_image_cache_identity(&trusted_digest, &driver.config) - }; - // An upgrade must not silently reuse an entry populated by older code. - let legacy_identity = if bootstrap { - format!( - "sandbox-bootstrap-rootfs-ext4-v5:openshell-{}:guest-{}:{trusted_digest}", - openshell_core::VERSION, - sandbox_guest_runtime_identity(), - ) - } else { - format!( - "sandbox-prepared-rootfs-ext4-umoci-v3:openshell-{}:image-account:{trusted_digest}", - openshell_core::VERSION, - ) - }; - assert_ne!(legacy_identity, identity); - let legacy_path = image_cache_rootfs_image(root.path(), &legacy_identity); - fs::create_dir_all(legacy_path.parent().unwrap()).unwrap(); - fs::write(&legacy_path, b"legacy unverified disk").unwrap(); - - let client = client(); - let error = ensure_image(&driver, ®istry.reference(None), &client, bootstrap) - .await - .unwrap_err(); - assert!(error.message().contains("Invalid digest"), "{error}"); - assert!(error.message().contains(&trusted_digest), "{error}"); - assert!( - registry - .requests() - .iter() - .all(|request| !request.contains("/blobs/")) - ); - assert!(!image_cache_rootfs_image(root.path(), &identity).exists()); - - // A subsequent consumer pins the trusted image. It must miss the cache, - // fetch that manifest, and fail rather than receive the replacement disk. - let error = ensure_image( - &driver, - ®istry.reference(Some(&trusted_digest)), - &client, - bootstrap, - ) - .await - .unwrap_err(); - assert!(error.message().contains("Invalid digest"), "{error}"); - assert!(!image_cache_rootfs_image(root.path(), &identity).exists()); - assert_eq!(fs::read(legacy_path).unwrap(), b"legacy unverified disk"); -} - -#[tokio::test] -async fn prepared_registry_cache_rejects_manifest_identity_mismatch() { - rejects_unbound_manifest(false).await; -} - -#[tokio::test] -async fn bootstrap_registry_cache_rejects_manifest_identity_mismatch() { - rejects_unbound_manifest(true).await; -} - -async fn accepts_sha512_pin(bootstrap: bool) { - let trusted = manifest("trusted"); - for is_index in [false, true] { - let top = if is_index { - index(&trusted) - } else { - trusted.clone() - }; - let digest = format!("sha512:{:x}", sha2::Sha512::digest(&top)); - // Canonical SHA-256 response headers are valid for a SHA-512 request. - // The complete pin must still be checked, including for an index. - let registry = Registry::start( - sha256(&top), - HashMap::from([(digest.clone(), top), (sha256(&trusted), trusted.clone())]), - None, - false, - ) - .await; - let root = tempfile::tempdir().unwrap(); - let driver = driver(root.path()); - let error = ensure_image( - &driver, - ®istry.reference(Some(&digest)), - &client(), - bootstrap, - ) - .await - .unwrap_err(); - // Reaching the deliberate blob 404 proves real cache staging and - // manifest verification succeeded without requiring a VM or formatter. - let expected = if bootstrap { - "failed to download layer" - } else { - "failed to download config" - }; - assert!(error.message().contains(expected), "{error}"); - assert!(error.message().contains("404 Not Found"), "{error}"); - let requests = registry.requests(); - assert!(requests.contains(&format!("GET /v2/test/image/manifests/{digest}"))); - assert!(!requests.iter().any(|request| request.starts_with("HEAD "))); - if is_index { - assert!(requests.contains(&format!( - "GET /v2/test/image/manifests/{}", - sha256(&trusted) - ))); - } - assert!(requests.contains(&format!("GET /v2/test/image/blobs/{}", sha256(b"trusted")))); - } -} - -#[tokio::test] -async fn bootstrap_registry_cache_accepts_sha512_pins_and_canonical_sha256_headers() { - accepts_sha512_pin(true).await; -} - -#[tokio::test] -async fn prepared_registry_cache_accepts_sha512_pins_and_canonical_sha256_headers() { - accepts_sha512_pin(false).await; -} - -#[tokio::test] -async fn registry_pulls_pin_single_and_index_manifests_across_tag_changes_and_retries() { - let trusted = manifest("trusted"); - let replacement = manifest("replacement"); - for is_index in [false, true] { - for caller_pinned in [false, true] { - let top = if is_index { - index(&trusted) - } else { - trusted.clone() - }; - let top_digest = sha256(&top); - let registry = Registry::start( - top_digest.clone(), - HashMap::from([ - ("latest".to_string(), replacement.clone()), - (top_digest.clone(), top), - (sha256(&trusted), trusted.clone()), - ]), - None, - true, - ) - .await; - let client = client(); - let reference = parse_registry_reference( - ®istry.reference(caller_pinned.then_some(top_digest.as_str())), - ) - .unwrap(); - let (reference, identity) = - pin_registry_reference(&client, &reference, &RegistryAuth::Anonymous) - .await - .unwrap(); - let (pulled, platform_digest) = - retry_registry_request_with_delay("test manifest", Duration::ZERO, || { - client.pull_image_manifest(&reference, &RegistryAuth::Anonymous) - }) - .await - .unwrap(); - assert_eq!(identity, top_digest); - assert_eq!(platform_digest, sha256(&trusted)); - assert_eq!(pulled.config.digest, sha256(b"trusted")); - let requests = registry.requests(); - assert!( - !requests - .iter() - .any(|request| request == "GET /v2/test/image/manifests/latest") - ); - assert_eq!( - requests - .iter() - .filter(|request| request.starts_with("HEAD ")) - .count(), - usize::from(!caller_pinned) - ); - assert_eq!( - requests - .iter() - .filter( - |request| *request == &format!("GET /v2/test/image/manifests/{top_digest}") - ) - .count(), - 2 - ); - } - } -} - -#[tokio::test] -async fn registry_pulls_reject_changed_index_children_and_forged_get_headers() { - let trusted = manifest("trusted"); - let replacement = manifest("replacement"); - for is_index in [false, true] { - let top = if is_index { - index(&trusted) - } else { - trusted.clone() - }; - let digest = sha256(&top); - let registry = Registry::start( - digest.clone(), - HashMap::from([ - (digest.clone(), top), - (sha256(&trusted), replacement.clone()), - ]), - // Single manifest: even a forged GET header must not make the - // replacement valid. Index: the child's own valid header differs. - (!is_index).then(|| digest.clone()), - false, - ) - .await; - let client = client(); - let reference = parse_registry_reference(®istry.reference(Some(&digest))).unwrap(); - let (reference, _) = pin_registry_reference(&client, &reference, &RegistryAuth::Anonymous) - .await - .unwrap(); - let error = client - .pull_image_manifest(&reference, &RegistryAuth::Anonymous) - .await - .unwrap_err(); - assert!(error.to_string().contains("Invalid digest"), "{error}"); - } -} - -#[tokio::test] -async fn registry_cache_preserves_caller_digest_when_head_uses_another_algorithm() { - let trusted = manifest("trusted"); - let digest = sha256(&trusted); - let registry = Registry::start( - format!("sha512:{:x}", sha2::Sha512::digest(b"replacement")), - HashMap::new(), - None, - false, - ) - .await; - let root = tempfile::tempdir().unwrap(); - let driver = driver(root.path()); - let client = client(); - for bootstrap in [false, true] { - let identity = if bootstrap { - bootstrap_image_cache_identity(&digest) - } else { - prepared_image_cache_identity(&digest, &driver.config) - }; - let path = image_cache_rootfs_image(root.path(), &identity); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(&path, b"verified cached disk").unwrap(); - assert_eq!( - ensure_image( - &driver, - ®istry.reference(Some(&digest)), - &client, - bootstrap - ) - .await - .unwrap(), - identity, - ); - assert_eq!(fs::read(path).unwrap(), b"verified cached disk"); - } - assert!( - registry - .requests() - .iter() - .all(|request| request == "GET /v2/") - ); -} - -#[tokio::test] -async fn bootstrap_registry_cache_hit_for_a_digest_pin_makes_no_registry_request() { - let body = manifest("pinned"); - let digest = sha256(&body); - let registry = Registry::start( - digest.clone(), - HashMap::from([("latest".to_string(), body.clone()), (digest.clone(), body)]), - None, - false, - ) - .await; - let root = tempfile::tempdir().unwrap(); - let driver = driver(root.path()); - let client = client(); - - // Not cached yet: a digest pin still authenticates and fetches (and here - // fails at the blobs the fixture does not serve). - ensure_image(&driver, ®istry.reference(Some(&digest)), &client, true) - .await - .unwrap_err(); - assert!( - registry - .requests() - .iter() - .any(|request| request.contains(&format!("/manifests/{digest}"))), - "{:?}", - registry.requests() - ); - - // Cached: the same pin boots from the cache with no request at all. - let identity = bootstrap_image_cache_identity(&digest); - let path = image_cache_rootfs_image(root.path(), &identity); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(&path, b"cached disk").unwrap(); - let before = registry.requests().len(); - let resolved = ensure_image(&driver, ®istry.reference(Some(&digest)), &client, true) - .await - .unwrap(); - assert_eq!(resolved, identity); - assert_eq!( - registry.requests().len(), - before, - "a digest-pinned cache hit reached the registry: {:?}", - ®istry.requests()[before..] - ); - - // A tag naming the same content still resolves through the registry. - let resolved = ensure_image(&driver, ®istry.reference(None), &client, true) - .await - .unwrap(); - assert_eq!(resolved, identity); - assert!( - registry.requests()[before..] - .iter() - .any(|request| request == "HEAD /v2/test/image/manifests/latest"), - "{:?}", - registry.requests() - ); -} - -#[tokio::test] -async fn empty_bootstrap_layers_reuse_one_staging_directory() { - let empty = tests::gzip_bytes(&[]); - let mut layers = vec![("application/vnd.oci.image.layer.v1.tar+gzip", empty); 3]; - layers.push(( - "application/vnd.oci.image.layer.v1.tar", - tests::tar_bytes_with_file("over-limit", b"x"), - )); - let registry = Registry::with_layers(layers).await; - let image = registry.reference(None); - let state = tempfile::tempdir().unwrap(); - let mut driver = driver(state.path()); - driver.config.bootstrap_extraction_max_bytes = std::num::NonZeroU64::new(1); - let scratch = state.path().join("stage"); - let error = driver - .pull_registry_image_rootfs( - "test", - &client(), - &parse_registry_reference(&image).unwrap(), - &RegistryAuth::Anonymous, - &image, - &scratch, - &scratch.join("rootfs"), - ) - .await - .unwrap_err(); - assert!(error.message().contains("decoded layer tars"), "{error}"); - let staging_dirs = fs::read_dir(scratch.join("layers")) - .unwrap() - .map(Result::unwrap) - .filter(|entry| entry.file_type().unwrap().is_dir()) - .count(); - assert_eq!(staging_dirs, 1); -} - -#[tokio::test] -async fn bootstrap_extraction_limit_spans_layers_and_cleans_failed_build() { - let mut lower = tar::Builder::new(Vec::new()); - let mut dir = tar::Header::new_gnu(); - dir.set_entry_type(tar::EntryType::Directory); - dir.set_mode(0o555); - dir.set_size(0); - lower - .append_data(&mut dir, "readonly", std::io::empty()) - .unwrap(); - tests::append_test_tar_file(&mut lower, "readonly/empty", b""); - tests::append_test_tar_file(&mut lower, "shared", &[1; 4096]); - let lower = lower.into_inner().unwrap(); - let upper = tests::tar_bytes_with_file("shared", &[2; 4096]); - let registry = Registry::with_layers(vec![ - ( - "application/vnd.oci.image.layer.v1.tar+gzip", - tests::gzip_bytes(&lower), - ), - ( - "application/vnd.oci.image.layer.v1.tar+zstd", - zstd::encode_all(&upper[..], 0).unwrap(), - ), - ]) - .await; - let image = registry.reference(None); - let client = client(); - let state = tempfile::tempdir().unwrap(); - let mut driver = driver(state.path()); - let attempt = state.path().join("attempt"); - fs::create_dir(&attempt).unwrap(); - driver.preparation_root = Some(attempt.clone()); - // Four path components staged and three entries merged in the lower layer. - // The upper file is charged again when staged and when merged. - driver.config.bootstrap_extraction_max_bytes = std::num::NonZeroU64::new(9 * 4096 - 1); - let error = ensure_image(&driver, &image, &client, true) - .await - .unwrap_err(); - assert!( - error.message().contains("bootstrap extraction limit"), - "{error}" - ); - assert!(attempt.read_dir().unwrap().next().is_none()); - assert!( - fs::read_dir(image_cache_root_dir(state.path())) - .unwrap() - .next() - .is_none(), - "a rejected image must not leave a cache entry" - ); - - driver.config.bootstrap_extraction_max_bytes = std::num::NonZeroU64::new(9 * 4096); - let staging = state.path().join("retry"); - let rootfs = staging.join("rootfs"); - driver - .pull_registry_image_rootfs( - "test", - &client, - &parse_registry_reference(&image).unwrap(), - &RegistryAuth::Anonymous, - &image, - &staging, - &rootfs, - ) - .await - .unwrap(); - assert_eq!(fs::read(rootfs.join("shared")).unwrap(), [2; 4096]); - assert!(!staging.join("layers").exists()); - assert_eq!( - fs::metadata(rootfs.join("readonly")) - .unwrap() - .permissions() - .mode() - & 0o777, - 0o555 - ); - fs::set_permissions(rootfs.join("readonly"), fs::Permissions::from_mode(0o755)).unwrap(); -} diff --git a/crates/openshell-driver-vm/src/rootfs.rs b/crates/openshell-driver-vm/src/rootfs.rs deleted file mode 100644 index a292e81994..0000000000 --- a/crates/openshell-driver-vm/src/rootfs.rs +++ /dev/null @@ -1,1891 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -use flate2::read::MultiGzDecoder; -use sha2::{Digest, Sha256}; -use std::fs; -use std::fs::File; -#[cfg(test)] -use std::io::BufWriter; -use std::io::{BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write}; -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::sync::OnceLock; -use std::sync::atomic::{AtomicU64, Ordering}; - -use crate::driver::{DEFAULT_SANDBOX_UID, PREPARED_IMAGE_ROOTFS_DIR}; - -const SANDBOX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-sandbox.zst")); -const SUPERVISOR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-supervisor.zst")); -const VM_INIT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-vm-init.zst")); -const UMOCI: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/umoci.zst")); -const ROOTFS_VARIANT_MARKER: &str = ".openshell-rootfs-variant"; -/// Leading bytes of a gzip stream, used to recognize `.tar.gz`/`.tgz` input -/// without trusting the file name. -pub const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b]; -const SANDBOX_GUEST_INIT_PATH: &str = "/srv/openshell-vm-sandbox-init.sh"; -const SANDBOX_SUPERVISOR_PATH: &str = openshell_core::driver_utils::SUPERVISOR_CONTAINER_BINARY; -const SANDBOX_UMOCI_PATH: &str = openshell_core::container_paths::VM_UMOCI_PATH; -const SANDBOX_VM_INIT_PATH: &str = "/opt/openshell/bin/openshell-vm-init"; -const ROOTFS_IMAGE_MIN_SIZE_BYTES: u64 = 512 * 1024 * 1024; -const ROOTFS_IMAGE_MIN_HEADROOM_BYTES: u64 = 256 * 1024 * 1024; -const EXT4_IMAGE_MIN_HEADROOM_BYTES: u64 = 16 * 1024 * 1024; -static INJECTION_COUNTER: AtomicU64 = AtomicU64::new(0); - -pub const fn sandbox_guest_init_path() -> &'static str { - SANDBOX_GUEST_INIT_PATH -} - -/// Identity of every embedded artifact materialized into a bootstrap rootfs. -/// -/// Including this in the image-cache key makes local, uncommitted guest-sandbox -/// changes invalidate the cache even when the `OpenShell` version is unchanged. -pub fn sandbox_guest_runtime_identity() -> String { - let mut hasher = Sha256::new(); - hasher.update(SANDBOX); - hasher.update(VM_INIT); - hasher.update(UMOCI); - hasher.update(include_bytes!("../scripts/openshell-vm-sandbox-init.sh")); - format!("{:x}", hasher.finalize()) -} - -/// Materialize the supervisor embedded in the VM driver for host-side use. -pub fn extract_host_supervisor(path: &Path) -> Result<(), String> { - if SUPERVISOR.is_empty() { - return Err( - "host supervisor is not embedded; run `mise run vm:supervisor` and rebuild openshell-driver-vm" - .to_string(), - ); - } - let supervisor = embedded_host_supervisor()?; - install_host_supervisor_atomically(path, &supervisor)?; - validate_host_supervisor(path) -} - -pub fn validate_host_supervisor(path: &Path) -> Result<(), String> { - validate_host_supervisor_digest(path, embedded_host_supervisor_digest()?) -} - -fn validate_host_supervisor_digest(path: &Path, expected: [u8; 32]) -> Result<(), String> { - let metadata = fs::symlink_metadata(path) - .map_err(|error| format!("inspect cached host supervisor {}: {error}", path.display()))?; - if !metadata.file_type().is_file() { - return Err(format!( - "cached host supervisor is not a regular file: {}", - path.display() - )); - } - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - if metadata.permissions().mode() & 0o111 == 0 { - return Err(format!( - "cached host supervisor is not executable: {}", - path.display() - )); - } - } - let actual = sha256_reader( - File::open(path) - .map_err(|error| format!("open cached host supervisor {}: {error}", path.display()))?, - ) - .map_err(|error| format!("hash cached host supervisor {}: {error}", path.display()))?; - if actual != expected { - return Err(format!( - "cached host supervisor content does not match embedded runtime: {}", - path.display() - )); - } - Ok(()) -} - -fn embedded_host_supervisor() -> Result, String> { - zstd::decode_all(Cursor::new(SUPERVISOR)) - .map_err(|error| format!("decompress host supervisor: {error}")) -} - -fn embedded_host_supervisor_digest() -> Result<[u8; 32], String> { - static DIGEST: OnceLock> = OnceLock::new(); - DIGEST - .get_or_init(|| embedded_host_supervisor().map(|bytes| sha256_bytes(&bytes))) - .clone() -} - -fn sha256_bytes(bytes: &[u8]) -> [u8; 32] { - Sha256::digest(bytes).into() -} - -fn sha256_reader(mut reader: impl Read) -> std::io::Result<[u8; 32]> { - let mut hasher = Sha256::new(); - let mut buffer = [0_u8; 16 * 1024]; - loop { - let read = reader.read(&mut buffer)?; - if read == 0 { - break; - } - hasher.update(&buffer[..read]); - } - Ok(hasher.finalize().into()) -} - -fn install_host_supervisor_atomically(path: &Path, bytes: &[u8]) -> Result<(), String> { - let parent = path - .parent() - .filter(|parent| !parent.as_os_str().is_empty()) - .ok_or_else(|| format!("host supervisor path has no parent: {}", path.display()))?; - fs::create_dir_all(parent).map_err(|error| format!("create {}: {error}", parent.display()))?; - let temporary = parent.join(format!( - ".openshell-sandbox.tmp-{}-{}", - std::process::id(), - INJECTION_COUNTER.fetch_add(1, Ordering::Relaxed) - )); - let result = (|| { - let mut options = fs::OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt as _; - options.mode(0o755); - } - let mut file = options - .open(&temporary) - .map_err(|error| format!("create {}: {error}", temporary.display()))?; - file.write_all(bytes) - .map_err(|error| format!("write {}: {error}", temporary.display()))?; - file.sync_all() - .map_err(|error| format!("sync {}: {error}", temporary.display()))?; - fs::rename(&temporary, path).map_err(|error| { - format!( - "commit cached host supervisor {} to {}: {error}", - temporary.display(), - path.display() - ) - })?; - File::open(parent) - .and_then(|directory| directory.sync_all()) - .map_err(|error| format!("sync host supervisor cache {}: {error}", parent.display())) - })(); - if result.is_err() { - let _ = fs::remove_file(&temporary); - } - result -} - -#[allow(clippy::similar_names)] -pub fn prepare_sandbox_rootfs_from_image_root( - rootfs: &Path, - image_identity: &str, - sandbox_uid: Option, - sandbox_gid: Option, -) -> Result<(), String> { - prepare_sandbox_rootfs(rootfs, sandbox_uid, sandbox_gid)?; - validate_sandbox_rootfs(rootfs)?; - fs::write( - rootfs.join(ROOTFS_VARIANT_MARKER), - format!("{}:image:{image_identity}\n", env!("CARGO_PKG_VERSION")), - ) - .map_err(|e| format!("write rootfs variant marker: {e}"))?; - Ok(()) -} - -/// Extract a rootfs tarball, transparently decompressing gzip archives. -/// -/// Compression is detected from the magic bytes rather than the file name: -/// `--from` accepts `.tar.gz` and `.tgz`, but nothing guarantees a caller's -/// extension matches the bytes, and the archives this crate stages internally -/// carry no extension at all. -pub fn extract_rootfs_archive_to(archive_path: &Path, dest: &Path) -> Result<(), String> { - if dest.exists() { - fs::remove_dir_all(dest) - .map_err(|e| format!("remove old rootfs {}: {e}", dest.display()))?; - } - - fs::create_dir_all(dest).map_err(|e| format!("create rootfs dir {}: {e}", dest.display()))?; - let file = - File::open(archive_path).map_err(|e| format!("open {}: {e}", archive_path.display()))?; - let mut reader = BufReader::new(file); - let compressed = reader - .fill_buf() - .map_err(|e| format!("read {}: {e}", archive_path.display()))? - .starts_with(&GZIP_MAGIC); - if compressed { - unpack_tar_reader(MultiGzDecoder::new(reader), dest) - } else { - unpack_tar_reader(reader, dest) - } -} - -fn unpack_tar_reader(reader: impl Read, dest: &Path) -> Result<(), String> { - tar::Archive::new(reader) - .unpack(dest) - .map_err(|e| format!("extract rootfs tarball into {}: {e}", dest.display())) -} - -#[cfg(test)] -pub fn create_rootfs_archive_from_dir(source: &Path, archive_path: &Path) -> Result<(), String> { - if let Some(parent) = archive_path.parent() { - fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?; - } - - let file = File::create(archive_path) - .map_err(|e| format!("create {}: {e}", archive_path.display()))?; - let writer = BufWriter::new(file); - let mut builder = tar::Builder::new(writer); - append_rootfs_tree_to_archive(&mut builder, source, Path::new("")).map_err(|e| { - format!( - "archive {} into {}: {e}", - source.display(), - archive_path.display() - ) - })?; - builder - .finish() - .map_err(|e| format!("finalize {}: {e}", archive_path.display())) -} - -pub fn create_rootfs_image_from_dir(source: &Path, image_path: &Path) -> Result<(), String> { - let image_size = rootfs_image_size_bytes(source)?; - create_ext4_image_from_dir_with_size(source, image_path, image_size)?; - if let Err(err) = normalize_sandbox_owner_in_rootfs_image(source, image_path) { - let _ = fs::remove_file(image_path); - return Err(err); - } - Ok(()) -} - -pub fn create_ext4_image_from_dir_with_size( - source: &Path, - image_path: &Path, - image_size: u64, -) -> Result<(), String> { - if let Some(parent) = image_path.parent() { - fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?; - } - if image_path.exists() { - fs::remove_file(image_path) - .map_err(|e| format!("remove old rootfs image {}: {e}", image_path.display()))?; - } - - let required_size = ext4_image_min_size_bytes(source)?; - if image_size < required_size { - return Err(format!( - "ext4 image size {} bytes is too small for {} (requires at least {} bytes)", - image_size, - source.display(), - required_size - )); - } - - let image = File::create(image_path) - .map_err(|e| format!("create rootfs image {}: {e}", image_path.display()))?; - image - .set_len(image_size) - .map_err(|e| format!("size rootfs image {}: {e}", image_path.display()))?; - drop(image); - - if let Err(err) = format_ext4_image_from_dir(source, image_path) { - let _ = fs::remove_file(image_path); - return Err(err); - } - - Ok(()) -} - -pub fn clone_or_copy_sparse_file(source: &Path, dest: &Path) -> Result<(), String> { - if let Some(parent) = dest.parent() { - fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?; - } - if dest.exists() { - fs::remove_file(dest).map_err(|e| format!("remove old file {}: {e}", dest.display()))?; - } - - let clone_error = match try_clone_file(source, dest) { - Ok(()) => return Ok(()), - Err(err) => { - let _ = fs::remove_file(dest); - err - } - }; - - copy_sparse_file(source, dest).map_err(|copy_error| { - format!( - "clone {} to {} failed ({clone_error}); sparse copy failed: {copy_error}", - source.display(), - dest.display() - ) - }) -} - -pub fn write_rootfs_image_file( - image_path: &Path, - guest_path: &str, - contents: &[u8], -) -> Result<(), String> { - ensure_rootfs_image_parent_dirs(image_path, guest_path); - - let tmp_path = temporary_injection_path(image_path); - fs::write(&tmp_path, contents).map_err(|e| format!("write {}: {e}", tmp_path.display()))?; - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - let _ = fs::remove_file(&tmp_path); - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - let Some(quoted_tmp_path) = debugfs_quote_argument(&tmp_path.to_string_lossy()) else { - let _ = fs::remove_file(&tmp_path); - return Err(format!( - "invalid debugfs injection path '{}'", - tmp_path.display() - )); - }; - let _ = run_debugfs(image_path, &format!("rm {quoted_guest_path}")); - let result = run_debugfs( - image_path, - &format!("write {quoted_tmp_path} {quoted_guest_path}"), - ); - let _ = fs::remove_file(&tmp_path); - result -} - -pub fn remove_rootfs_image_file(image_path: &Path, guest_path: &str) -> Result<(), String> { - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - run_debugfs(image_path, &format!("rm {quoted_guest_path}")) -} - -pub fn set_rootfs_image_file_mode( - image_path: &Path, - guest_path: &str, - mode: u32, -) -> Result<(), String> { - let regular_file_mode = 0o100_000 | (mode & 0o7777); - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - run_debugfs( - image_path, - &format!("set_inode_field {quoted_guest_path} mode 0{regular_file_mode:o}"), - ) -} - -/// Replay the ext4 journal and repair automatically correctable filesystem -/// state before the driver mutates a preserved guest disk offline. -pub fn recover_rootfs_image(image_path: &Path) -> Result<(), String> { - let mut command = e2fs_command("e2fsck")?; - let path = PathBuf::from(command.get_program()); - let output = command.arg("-p").arg("-f").arg(image_path).output(); - match output { - Ok(output) if matches!(output.status.code(), Some(0..=2)) => Ok(()), - Ok(output) => Err(format!( - "{} failed with status {}\nstdout: {}\nstderr: {}", - path.display(), - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )), - Err(error) => Err(format!("run {}: {error}", path.display())), - } -} - -#[cfg(target_os = "macos")] -fn try_clone_file(source: &Path, dest: &Path) -> Result<(), String> { - let output = Command::new("cp") - .arg("-c") - .arg(source) - .arg(dest) - .output() - .map_err(|e| format!("run cp -c: {e}"))?; - if output.status.success() { - return Ok(()); - } - Err(format!( - "cp -c failed with status {}\nstdout: {}\nstderr: {}", - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )) -} - -#[cfg(target_os = "linux")] -fn try_clone_file(source: &Path, dest: &Path) -> Result<(), String> { - let output = Command::new("cp") - .arg("--reflink=auto") - .arg("--sparse=always") - .arg(source) - .arg(dest) - .output() - .map_err(|e| format!("run cp --reflink=auto: {e}"))?; - if output.status.success() { - return Ok(()); - } - Err(format!( - "cp --reflink=auto --sparse=always failed with status {}\nstdout: {}\nstderr: {}", - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )) -} - -#[cfg(not(any(target_os = "macos", target_os = "linux")))] -fn try_clone_file(_source: &Path, _dest: &Path) -> Result<(), String> { - Err("no platform clone command available".to_string()) -} - -fn copy_sparse_file(source: &Path, dest: &Path) -> Result<(), String> { - const BUFFER_SIZE: usize = 1024 * 1024; - - let mut source_file = - File::open(source).map_err(|e| format!("open {}: {e}", source.display()))?; - let mut dest_file = - File::create(dest).map_err(|e| format!("create {}: {e}", dest.display()))?; - let mut buffer = vec![0_u8; BUFFER_SIZE]; - let mut size = 0_u64; - - loop { - let read = source_file - .read(&mut buffer) - .map_err(|e| format!("read {}: {e}", source.display()))?; - if read == 0 { - break; - } - - if buffer[..read].iter().all(|byte| *byte == 0) { - let skip = - i64::try_from(read).map_err(|_| format!("sparse copy chunk too large: {read}"))?; - dest_file - .seek(SeekFrom::Current(skip)) - .map_err(|e| format!("seek {}: {e}", dest.display()))?; - } else { - dest_file - .write_all(&buffer[..read]) - .map_err(|e| format!("write {}: {e}", dest.display()))?; - } - size += read as u64; - } - - dest_file - .set_len(size) - .map_err(|e| format!("size {}: {e}", dest.display())) -} - -#[cfg(test)] -fn append_rootfs_tree_to_archive( - builder: &mut tar::Builder>, - source: &Path, - archive_prefix: &Path, -) -> Result<(), String> { - let mut entries = fs::read_dir(source) - .map_err(|e| format!("read {}: {e}", source.display()))? - .collect::, _>>() - .map_err(|e| format!("read {}: {e}", source.display()))?; - entries.sort_by_key(fs::DirEntry::file_name); - - for entry in entries { - let entry_name = entry.file_name(); - let source_path = entry.path(); - let archive_path = if archive_prefix.as_os_str().is_empty() { - entry_name.into() - } else { - archive_prefix.join(entry_name) - }; - let metadata = fs::symlink_metadata(&source_path) - .map_err(|e| format!("stat {}: {e}", source_path.display()))?; - let file_type = metadata.file_type(); - - if file_type.is_dir() { - builder - .append_dir(&archive_path, &source_path) - .map_err(|e| format!("append dir {}: {e}", source_path.display()))?; - append_rootfs_tree_to_archive(builder, &source_path, &archive_path)?; - continue; - } - - if file_type.is_file() { - let mut file = File::open(&source_path) - .map_err(|e| format!("open {}: {e}", source_path.display()))?; - builder - .append_file(&archive_path, &mut file) - .map_err(|e| format!("append file {}: {e}", source_path.display()))?; - continue; - } - - if file_type.is_symlink() { - append_symlink_to_archive(builder, &source_path, &archive_path, &metadata)?; - continue; - } - - return Err(format!( - "unsupported rootfs entry type at {}", - source_path.display() - )); - } - - Ok(()) -} - -#[cfg(test)] -fn append_symlink_to_archive( - builder: &mut tar::Builder>, - source_path: &Path, - archive_path: &Path, - metadata: &fs::Metadata, -) -> Result<(), String> { - let target = fs::read_link(source_path) - .map_err(|e| format!("readlink {}: {e}", source_path.display()))?; - let mut header = tar::Header::new_gnu(); - header.set_metadata(metadata); - header.set_size(0); - header.set_cksum(); - builder - .append_link(&mut header, archive_path, target) - .map_err(|e| format!("append symlink {}: {e}", source_path.display())) -} - -#[allow(clippy::similar_names)] -fn prepare_sandbox_rootfs( - rootfs: &Path, - sandbox_uid: Option, - sandbox_gid: Option, -) -> Result<(), String> { - for relative in ["opt/openshell/.initialized", "opt/openshell/.rootfs-type"] { - remove_rootfs_path(rootfs, relative)?; - } - - let init_path = rootfs.join("srv/openshell-vm-sandbox-init.sh"); - if let Some(parent) = init_path.parent() { - create_guest_dir_all(parent)?; - } - fs::write( - &init_path, - include_str!("../scripts/openshell-vm-sandbox-init.sh"), - ) - .map_err(|e| format!("write {}: {e}", init_path.display()))?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - - fs::set_permissions(&init_path, fs::Permissions::from_mode(0o755)) - .map_err(|e| format!("chmod {}: {e}", init_path.display()))?; - } - - ensure_supervisor_binary(rootfs)?; - ensure_vm_init_binary(rootfs)?; - ensure_umoci_binary(rootfs)?; - - let opt_dir = rootfs.join("opt/openshell"); - create_guest_dir_all(&opt_dir)?; - fs::write(opt_dir.join(".rootfs-type"), "sandbox\n") - .map_err(|e| format!("write sandbox rootfs marker: {e}"))?; - ensure_sandbox_guest_user(rootfs, sandbox_uid, sandbox_gid)?; - create_sandbox_mountpoint(&rootfs.join("sandbox"))?; - create_sandbox_mountpoint(&rootfs.join("image-cache"))?; - create_sandbox_mountpoint(&rootfs.join("lower"))?; - create_sandbox_mountpoint(&rootfs.join("overlay"))?; - create_sandbox_mountpoint(&rootfs.join("newroot"))?; - - Ok(()) -} - -pub fn validate_sandbox_rootfs(rootfs: &Path) -> Result<(), String> { - require_rootfs_path(rootfs, SANDBOX_GUEST_INIT_PATH)?; - require_rootfs_path(rootfs, SANDBOX_SUPERVISOR_PATH)?; - require_rootfs_path(rootfs, SANDBOX_VM_INIT_PATH)?; - require_rootfs_path(rootfs, SANDBOX_UMOCI_PATH)?; - require_any_rootfs_path(rootfs, &["/bin/bash"])?; - require_any_rootfs_path(rootfs, &["/bin/mount", "/usr/bin/mount"])?; - require_any_rootfs_path( - rootfs, - &[ - "/usr/sbin/chroot", - "/usr/bin/chroot", - "/sbin/chroot", - "/bin/chroot", - ], - )?; - require_any_rootfs_path(rootfs, &["/bin/sed", "/usr/bin/sed"])?; - Ok(()) -} - -fn create_sandbox_mountpoint(path: &Path) -> Result<(), String> { - create_guest_dir_all(path)?; - chmod_guest_dir(path) -} - -/// Like `create_dir_all`, but each directory it makes is 0755 whatever the -/// umask. The sandbox user must be able to traverse the guest rootfs. -fn create_guest_dir_all(path: &Path) -> Result<(), String> { - if path.is_dir() { - return Ok(()); - } - if let Some(parent) = path.parent() { - create_guest_dir_all(parent)?; - } - fs::create_dir(path).map_err(|e| format!("create {}: {e}", path.display()))?; - chmod_guest_dir(path) -} - -fn chmod_guest_dir(path: &Path) -> Result<(), String> { - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - - fs::set_permissions(path, fs::Permissions::from_mode(0o755)) - .map_err(|e| format!("chmod {}: {e}", path.display()))?; - } - #[cfg(not(unix))] - let _ = path; - Ok(()) -} - -fn rootfs_image_size_bytes(source: &Path) -> Result { - let used = directory_size_bytes(source)?; - let headroom = (used / 4).max(ROOTFS_IMAGE_MIN_HEADROOM_BYTES); - let size = (used + headroom).max(ROOTFS_IMAGE_MIN_SIZE_BYTES); - Ok(round_up_to_mib(size)) -} - -fn ext4_image_min_size_bytes(source: &Path) -> Result { - let used = directory_size_bytes(source)?; - Ok(round_up_to_mib(used + EXT4_IMAGE_MIN_HEADROOM_BYTES)) -} - -fn directory_size_bytes(path: &Path) -> Result { - let metadata = - fs::symlink_metadata(path).map_err(|e| format!("stat {}: {e}", path.display()))?; - if metadata.file_type().is_file() || metadata.file_type().is_symlink() { - return Ok(metadata.len()); - } - if !metadata.file_type().is_dir() { - return Ok(0); - } - - let mut size = 4096; - for entry in fs::read_dir(path).map_err(|e| format!("read {}: {e}", path.display()))? { - let entry = entry.map_err(|e| format!("read {}: {e}", path.display()))?; - size += directory_size_bytes(&entry.path())?; - } - Ok(size) -} - -fn round_up_to_mib(bytes: u64) -> u64 { - const MIB: u64 = 1024 * 1024; - bytes.div_ceil(MIB) * MIB -} - -fn format_ext4_image_from_dir(source: &Path, image_path: &Path) -> Result<(), String> { - let path = openshell_core::e2fsprogs::resolve(&["mke2fs", "mkfs.ext4"])?; - let output = Command::new(&path) - .arg("-q") - .arg("-F") - .arg("-t") - .arg("ext4") - .arg("-E") - .arg("root_owner=0:0") - .arg("-d") - .arg(source) - .arg(image_path) - .output() - .map_err(|error| format!("run {}: {error}", path.display()))?; - if output.status.success() { - return Ok(()); - } - // A selected formatter failure must retain its diagnostics. Retrying with - // another installation can overwrite a partial image and hide the cause. - Err(format!( - "failed to create ext4 rootfs image from {}: {} failed with status {}\nstdout: {}\nstderr: {}", - source.display(), - path.display(), - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )) -} - -fn ensure_rootfs_image_parent_dirs(image_path: &Path, guest_path: &str) { - let Some(parent) = Path::new(guest_path).parent() else { - return; - }; - let mut current = String::new(); - for component in parent.components() { - let part = component.as_os_str().to_string_lossy(); - if part == "/" || part.is_empty() { - continue; - } - current.push('/'); - current.push_str(&part); - let _ = run_debugfs(image_path, &format!("mkdir {current}")); - } -} - -fn normalize_sandbox_owner_in_rootfs_image(source: &Path, image_path: &Path) -> Result<(), String> { - let sandbox_dir = source.join("sandbox"); - if !sandbox_dir.exists() { - return Ok(()); - } - - let Some((uid, gid)) = sandbox_guest_user_ids(source)? else { - return Ok(()); - }; - - let mut commands = Vec::new(); - if !collect_sandbox_owner_commands(&sandbox_dir, "/sandbox", uid, gid, &mut commands)? { - return Ok(()); - } - if commands.is_empty() { - return Ok(()); - } - - run_debugfs_batch(image_path, &commands) -} - -fn collect_sandbox_owner_commands( - source_path: &Path, - guest_path: &str, - uid: u32, - gid: u32, - commands: &mut Vec, -) -> Result { - let metadata = fs::symlink_metadata(source_path).map_err(|e| { - format!( - "stat {} for rootfs ownership normalization: {e}", - source_path.display() - ) - })?; - if metadata.file_type().is_symlink() { - return Ok(true); - } - - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - return Ok(false); - }; - commands.push(format!("set_inode_field {quoted_guest_path} uid {uid}")); - commands.push(format!("set_inode_field {quoted_guest_path} gid {gid}")); - - if !metadata.is_dir() { - return Ok(true); - } - - let mut entries = fs::read_dir(source_path) - .map_err(|e| { - format!( - "read {} for rootfs ownership normalization: {e}", - source_path.display() - ) - })? - .collect::, _>>() - .map_err(|e| { - format!( - "read {} entry for rootfs ownership normalization: {e}", - source_path.display() - ) - })?; - entries.sort_by_key(fs::DirEntry::file_name); - - for entry in entries { - let file_name = entry.file_name(); - let Some(file_name) = file_name.to_str() else { - return Ok(false); - }; - let child_guest_path = format!("{guest_path}/{file_name}"); - if !collect_sandbox_owner_commands(&entry.path(), &child_guest_path, uid, gid, commands)? { - return Ok(false); - } - } - - Ok(true) -} - -fn debugfs_quote_absolute_path(path: &str) -> Option { - if path.is_empty() || !path.starts_with('/') { - return None; - } - - debugfs_quote_argument(path) -} - -fn debugfs_quote_argument(argument: &str) -> Option { - if argument.is_empty() { - return None; - } - - let mut quoted = String::with_capacity(argument.len() + 2); - quoted.push('"'); - for ch in argument.chars() { - match ch { - '\0' | '\n' | '\r' => return None, - '\\' => quoted.push_str("\\\\"), - '"' => quoted.push_str("\\\""), - _ => quoted.push(ch), - } - } - quoted.push('"'); - Some(quoted) -} - -/// Read the sandbox account identity directly from an ext4 rootfs image. -/// -/// Persisted VM overlays may outlive the prepared-image cache layout that -/// created them. Reading the matching old lower disk lets the driver preserve -/// that overlay's real ownership contract during an upgrade. -pub fn sandbox_guest_user_ids_from_image(image_path: &Path) -> Result, String> { - if ext4_image_has_directory(image_path, PREPARED_IMAGE_ROOTFS_DIR)? { - let passwd = format!("{PREPARED_IMAGE_ROOTFS_DIR}/etc/passwd"); - return sandbox_guest_user_ids_from_image_path(image_path, &passwd); - } - sandbox_guest_user_ids_from_image_path(image_path, "/etc/passwd") -} - -/// Read a sandbox account copied into an overlay upper layer. -/// -/// An upper-layer passwd file is the most direct evidence of the identity an -/// existing overlay observed, so migration consults it before any lower image. -pub fn sandbox_guest_user_ids_from_overlay_image( - image_path: &Path, -) -> Result, String> { - sandbox_guest_user_ids_from_image_path(image_path, "/upper/etc/passwd") -} - -/// Check, without mounting, whether an ext4 image has a directory at -/// `guest_path`. Symlinks are not followed. -pub fn ext4_image_has_directory(image_path: &Path, guest_path: &str) -> Result { - let quoted_path = debugfs_quote_absolute_path(guest_path) - .ok_or_else(|| format!("invalid debugfs guest path '{guest_path}'"))?; - let command = format!("stat {quoted_path}"); - let output = e2fs_command("debugfs")? - .arg("-R") - .arg(&command) - .arg(image_path) - .output(); - match output { - Ok(output) if output.status.success() => { - // debugfs exits 0 whether or not the path exists; the answer - // is only in its output. - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - if stdout.contains("Type: directory") { - return Ok(true); - } - if stdout.contains("Type: ") || stderr.contains("File not found") { - return Ok(false); - } - Err(format!( - "debugfs command '{command}' produced unrecognized output for {}\nstdout: {stdout}\nstderr: {stderr}", - image_path.display() - )) - } - Ok(output) => Err(format!( - "debugfs command '{command}' failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry", - image_path.display(), - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )), - Err(error) => Err(format!( - "debugfs command '{command}' failed for {}: {error}. Install e2fsprogs (debugfs) and retry", - image_path.display() - )), - } -} - -fn sandbox_guest_user_ids_from_image_path( - image_path: &Path, - guest_path: &str, -) -> Result, String> { - let metadata = fs::metadata(image_path) - .map_err(|error| format!("stat rootfs image {}: {error}", image_path.display()))?; - if !metadata.is_file() { - return Err(format!( - "rootfs image {} is not a regular file", - image_path.display() - )); - } - - let quoted_path = debugfs_quote_absolute_path(guest_path) - .expect("the static passwd path is a valid debugfs path"); - let command = format!("cat {quoted_path}"); - let output = e2fs_command("debugfs")? - .arg("-R") - .arg(&command) - .arg(image_path) - .output(); - match output { - Ok(output) if output.status.success() => { - let passwd = String::from_utf8(output.stdout).map_err(|error| { - format!( - "read {guest_path} from {} as UTF-8: {error}", - image_path.display() - ) - })?; - parse_sandbox_guest_user_ids(&passwd, &image_path.display().to_string()) - } - Ok(output) => Err(format!( - "debugfs command '{command}' failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry", - image_path.display(), - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )), - Err(error) => Err(format!( - "debugfs command '{command}' failed for {}: {error}. Install e2fsprogs (debugfs) and retry", - image_path.display() - )), - } -} - -fn sandbox_guest_user_ids(rootfs: &Path) -> Result, String> { - let passwd_path = rootfs.join("etc/passwd"); - if !passwd_path.exists() { - return Ok(None); - } - - let passwd = fs::read_to_string(&passwd_path) - .map_err(|e| format!("read {}: {e}", passwd_path.display()))?; - parse_sandbox_guest_user_ids(&passwd, &passwd_path.display().to_string()) -} - -fn parse_sandbox_guest_user_ids(passwd: &str, source: &str) -> Result, String> { - for line in passwd.lines() { - let mut parts = line.split(':'); - if parts.next() != Some("sandbox") { - continue; - } - let _password = parts.next(); - let uid = parts - .next() - .ok_or_else(|| format!("sandbox entry in {source} is missing uid"))? - .parse::() - .map_err(|e| format!("sandbox uid in {source} is invalid: {e}"))?; - let gid = parts - .next() - .ok_or_else(|| format!("sandbox entry in {source} is missing gid"))? - .parse::() - .map_err(|e| format!("sandbox gid in {source} is invalid: {e}"))?; - return Ok(Some((uid, gid))); - } - - Ok(None) -} - -fn run_debugfs_batch(image_path: &Path, commands: &[String]) -> Result<(), String> { - let command_path = temporary_injection_path(image_path); - let mut contents = commands.join("\n"); - contents.push('\n'); - fs::write(&command_path, contents) - .map_err(|e| format!("write {}: {e}", command_path.display()))?; - - let result = run_debugfs_batch_file(image_path, &command_path); - let _ = fs::remove_file(&command_path); - result -} - -fn run_debugfs_batch_file(image_path: &Path, command_path: &Path) -> Result<(), String> { - let output = e2fs_command("debugfs")? - .arg("-w") - .arg("-f") - .arg(command_path) - .arg(image_path) - .output(); - match output { - Ok(output) if output.status.success() => Ok(()), - Ok(output) => Err(format!( - "debugfs batch {} failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry", - command_path.display(), - image_path.display(), - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )), - Err(error) => Err(format!( - "debugfs batch {} failed for {}: {error}. Install e2fsprogs (debugfs) and retry", - command_path.display(), - image_path.display() - )), - } -} - -fn run_debugfs(image_path: &Path, command: &str) -> Result<(), String> { - let output = e2fs_command("debugfs")? - .arg("-w") - .arg("-R") - .arg(command) - .arg(image_path) - .output(); - match output { - Ok(output) if output.status.success() => Ok(()), - Ok(output) => Err(format!( - "debugfs command '{command}' failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry", - image_path.display(), - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )), - Err(error) => Err(format!( - "debugfs command '{command}' failed for {}: {error}. Install e2fsprogs (debugfs) and retry", - image_path.display() - )), - } -} - -fn e2fs_command(tool: &str) -> Result { - // Preflight and image operations must execute the same selected file with - // the same inherited environment, including when PATH is restricted. - Ok(Command::new(openshell_core::e2fsprogs::resolve(&[tool])?)) -} - -fn temporary_injection_path(image_path: &Path) -> PathBuf { - let n = INJECTION_COUNTER.fetch_add(1, Ordering::Relaxed); - let parent = image_path.parent().unwrap_or_else(|| Path::new(".")); - parent.join(format!( - ".openshell-rootfs-inject-{}-{n}", - std::process::id() - )) -} - -#[allow(clippy::similar_names)] -fn ensure_sandbox_guest_user( - rootfs: &Path, - sandbox_uid: Option, - sandbox_gid: Option, -) -> Result<(), String> { - // An image's sandbox account is part of its filesystem contract. Leave it - // intact unless an operator explicitly configured either side of the - // identity. A missing account still gets the OpenShell default. - if sandbox_uid.is_none() && sandbox_gid.is_none() && sandbox_guest_user_ids(rootfs)?.is_some() { - return Ok(()); - } - - let sandbox_uid = sandbox_uid.unwrap_or(DEFAULT_SANDBOX_UID); - let sandbox_gid = sandbox_gid.unwrap_or(sandbox_uid); - let etc_dir = rootfs.join("etc"); - fs::create_dir_all(&etc_dir).map_err(|e| format!("create {}: {e}", etc_dir.display()))?; - - replace_or_append_line( - &etc_dir.join("group"), - &format!("sandbox:x:{sandbox_gid}:"), - |line| line.starts_with("sandbox:"), - )?; - replace_or_append_line(&etc_dir.join("gshadow"), "sandbox:!::", |line| { - line.starts_with("sandbox:") - })?; - replace_or_append_line( - &etc_dir.join("passwd"), - &format!("sandbox:x:{sandbox_uid}:{sandbox_gid}:OpenShell Sandbox:/sandbox:/bin/bash"), - |line| line.starts_with("sandbox:"), - )?; - replace_or_append_line( - &etc_dir.join("shadow"), - "sandbox:!:20123:0:99999:7:::", - |line| line.starts_with("sandbox:"), - )?; - - Ok(()) -} - -fn replace_or_append_line( - path: &Path, - line: &str, - matches: impl Fn(&str) -> bool, -) -> Result<(), String> { - let contents = if path.exists() { - fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))? - } else { - String::new() - }; - let mut output = String::with_capacity(contents.len().max(line.len() + 1)); - let mut replaced = false; - for existing in contents.lines() { - if matches(existing) { - if replaced { - continue; - } - output.push_str(line); - replaced = true; - } else { - output.push_str(existing); - } - output.push('\n'); - } - if !replaced { - output.push_str(line); - output.push('\n'); - } - - fs::write(path, output).map_err(|e| format!("write {}: {e}", path.display())) -} - -fn ensure_supervisor_binary(rootfs: &Path) -> Result<(), String> { - let path = rootfs.join(SANDBOX_SUPERVISOR_PATH.trim_start_matches('/')); - if SUPERVISOR.is_empty() { - if !path.exists() { - return Err( - "sandbox supervisor not embedded. Build openshell-driver-vm with OPENSHELL_VM_RUNTIME_COMPRESSED_DIR set and run `mise run vm:setup && mise run vm:supervisor` first" - .to_string(), - ); - } - } else { - if let Some(parent) = path.parent() { - create_guest_dir_all(parent)?; - } - - let sandbox = zstd::decode_all(Cursor::new(SANDBOX)) - .map_err(|e| format!("decompress sandbox: {e}"))?; - fs::write(&path, sandbox).map_err(|e| format!("write {}: {e}", path.display()))?; - } - - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - - fs::set_permissions(&path, fs::Permissions::from_mode(0o755)) - .map_err(|e| format!("chmod {}: {e}", path.display()))?; - } - - Ok(()) -} - -fn ensure_vm_init_binary(rootfs: &Path) -> Result<(), String> { - let path = rootfs.join(SANDBOX_VM_INIT_PATH.trim_start_matches('/')); - if VM_INIT.is_empty() { - if !path.exists() { - return Err( - "VM guest init helper not embedded. Build openshell-driver-vm with OPENSHELL_VM_RUNTIME_COMPRESSED_DIR set and run `mise run vm:supervisor` first" - .to_string(), - ); - } - } else { - if let Some(parent) = path.parent() { - create_guest_dir_all(parent)?; - } - let helper = zstd::decode_all(Cursor::new(VM_INIT)) - .map_err(|e| format!("decompress VM guest init helper: {e}"))?; - fs::write(&path, helper).map_err(|e| format!("write {}: {e}", path.display()))?; - } - - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - - fs::set_permissions(&path, fs::Permissions::from_mode(0o755)) - .map_err(|e| format!("chmod {}: {e}", path.display()))?; - } - - Ok(()) -} - -fn ensure_umoci_binary(rootfs: &Path) -> Result<(), String> { - let path = rootfs.join(SANDBOX_UMOCI_PATH.trim_start_matches('/')); - if UMOCI.is_empty() { - if !path.exists() { - return Err( - "umoci not embedded. Build openshell-driver-vm with OPENSHELL_VM_RUNTIME_COMPRESSED_DIR set and run `mise run vm:setup` first" - .to_string(), - ); - } - } else { - if let Some(parent) = path.parent() { - create_guest_dir_all(parent)?; - } - - let umoci = - zstd::decode_all(Cursor::new(UMOCI)).map_err(|e| format!("decompress umoci: {e}"))?; - fs::write(&path, umoci).map_err(|e| format!("write {}: {e}", path.display()))?; - } - - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - - fs::set_permissions(&path, fs::Permissions::from_mode(0o755)) - .map_err(|e| format!("chmod {}: {e}", path.display()))?; - } - - Ok(()) -} - -fn require_rootfs_path(rootfs: &Path, relative: &str) -> Result<(), String> { - let candidate = rootfs.join(relative.trim_start_matches('/')); - if candidate.exists() { - Ok(()) - } else { - Err(format!( - "prepared rootfs is missing {}", - candidate.display() - )) - } -} - -fn require_any_rootfs_path(rootfs: &Path, candidates: &[&str]) -> Result<(), String> { - if candidates - .iter() - .any(|candidate| rootfs.join(candidate.trim_start_matches('/')).exists()) - { - Ok(()) - } else { - Err(format!( - "prepared rootfs is missing one of: {}", - candidates.join(", ") - )) - } -} - -fn remove_rootfs_path(rootfs: &Path, relative: &str) -> Result<(), String> { - let path = rootfs.join(relative); - if !path.exists() { - return Ok(()); - } - - let result = if path.is_dir() { - fs::remove_dir_all(&path) - } else { - fs::remove_file(&path) - }; - result.map_err(|e| format!("remove {}: {e}", path.display())) -} - -#[cfg(test)] -mod tests { - use super::*; - #[cfg(target_os = "linux")] - use std::os::unix::fs::PermissionsExt as _; - use std::path::PathBuf; - use std::sync::atomic::{AtomicU64, Ordering}; - use std::time::{SystemTime, UNIX_EPOCH}; - - #[cfg(target_os = "linux")] - #[test] - fn host_supervisor_cache_rejects_wrong_content_and_installs_atomically() { - let directory = tempfile::tempdir().expect("cache directory"); - let destination = directory.path().join("openshell-sandbox"); - fs::write(&destination, b"stale executable").expect("write stale cache"); - fs::set_permissions(&destination, fs::Permissions::from_mode(0o755)) - .expect("make stale cache executable"); - let expected = sha256_bytes(b"trusted supervisor"); - - assert!(validate_host_supervisor_digest(&destination, expected).is_err()); - install_host_supervisor_atomically(&destination, b"trusted supervisor") - .expect("atomically replace cache"); - validate_host_supervisor_digest(&destination, expected).expect("validate installed cache"); - assert_eq!(fs::read(&destination).unwrap(), b"trusted supervisor"); - assert!(fs::read_dir(directory.path()).unwrap().all(|entry| { - !entry - .unwrap() - .file_name() - .to_string_lossy() - .contains(".tmp-") - })); - } - - #[test] - fn prepare_sandbox_rootfs_rewrites_guest_layout() { - let dir = unique_temp_dir(); - let rootfs = dir.join("rootfs"); - - fs::create_dir_all(rootfs.join("etc")).expect("create etc"); - fs::create_dir_all(rootfs.join("opt/openshell/bin")).expect("create openshell bin"); - fs::write(rootfs.join("opt/openshell/.initialized"), b"yes").expect("write initialized"); - write_fake_runtime_binaries(&rootfs); - fs::write( - rootfs.join("etc/passwd"), - "root:x:0:0:root:/root:/bin/bash\nsandbox:x:998:997:Sandbox:/sandbox:/bin/sh\n", - ) - .expect("write passwd"); - fs::write(rootfs.join("etc/group"), "root:x:0:\nsandbox:x:997:\n").expect("write group"); - fs::write(rootfs.join("etc/hosts"), "127.0.0.1 localhost\n").expect("write hosts"); - fs::create_dir_all(rootfs.join("bin")).expect("create bin"); - fs::create_dir_all(rootfs.join("sbin")).expect("create sbin"); - fs::write(rootfs.join("bin/bash"), b"bash").expect("write bash"); - fs::write(rootfs.join("bin/mount"), b"mount").expect("write mount"); - fs::write(rootfs.join("bin/chroot"), b"chroot").expect("write chroot"); - fs::write(rootfs.join("bin/sed"), b"sed").expect("write sed"); - fs::write(rootfs.join("sbin/ip"), b"ip").expect("write ip"); - - // Use a non-standard UID so the test doesn't collide with the default. - let uid = 20001; - prepare_sandbox_rootfs(&rootfs, Some(uid), Some(uid)).expect("prepare sandbox rootfs"); - validate_sandbox_rootfs(&rootfs).expect("validate sandbox rootfs"); - - assert!(rootfs.join("srv/openshell-vm-sandbox-init.sh").is_file()); - assert!(rootfs.join("opt/openshell/bin/umoci").is_file()); - assert!(rootfs.join("opt/openshell/bin/openshell-vm-init").is_file()); - let init_script = fs::read_to_string(rootfs.join("srv/openshell-vm-sandbox-init.sh")) - .expect("read guest init"); - assert!( - init_script.contains( - "launch-capability-free \"$_sandbox_uid\" \"$_sandbox_gid\" \"$_sandbox_bootstrap_guest\"" - ) - ); - assert!(init_script.contains("OPENSHELL_VM_SANDBOX_BOOTSTRAP")); - // The shell script is embedded verbatim in the guest rootfs, so these - // assertions pin its launch contract at the packaging boundary. - assert!(init_script.contains("exec \"$chroot_bin\" /newroot \"$supervisor\" \"$@\"")); - assert!(!init_script.contains("--library-path")); - assert!(!init_script.contains("\"$loader\"")); - assert!(!init_script.contains("ld-linux")); - assert!(init_script.contains(" reconcile_sandbox_account\n setup_sandbox_workdir")); - assert!( - init_script - .contains("chown \"${_sandbox_uid}:${_sandbox_gid}\" \"$_sandbox_state_dir\"") - ); - assert!(init_script.contains("chmod 0700 \"$_sandbox_state_dir\"")); - assert!(!init_script.contains("--backend-name=in-pod")); - assert!(!init_script.contains("@ISOLATION_INTERFACE_VERSION@")); - assert!(!init_script.contains("8.8.8.8")); - assert!(!init_script.contains("VM_NET_")); - assert!(rootfs.join("sandbox").is_dir()); - assert!(rootfs.join("image-cache").is_dir()); - assert!(rootfs.join("lower").is_dir()); - assert!(rootfs.join("overlay").is_dir()); - assert!(rootfs.join("newroot").is_dir()); - assert!( - fs::read_dir(rootfs.join("sandbox")) - .expect("read sandbox") - .next() - .is_none() - ); - let passwd = fs::read_to_string(rootfs.join("etc/passwd")).expect("read passwd"); - assert!(passwd.contains(&format!( - "sandbox:x:{uid}:{uid}:OpenShell Sandbox:/sandbox:/bin/bash" - ))); - assert!(!passwd.contains("sandbox:x:998:997:")); - let group = fs::read_to_string(rootfs.join("etc/group")).expect("read group"); - assert!(group.contains(&format!("sandbox:x:{uid}:"))); - assert!(!group.contains("sandbox:x:997:")); - assert_eq!( - fs::read_to_string(rootfs.join("etc/hosts")).expect("read hosts"), - "127.0.0.1 localhost\n" - ); - - let _ = fs::remove_dir_all(&dir); - } - - /// Runs the shipped guest init's `configure_hosts` against `root`. - /// - /// The function is cut out of the real script so the test exercises the - /// shell that boots the guest rather than a Rust reimplementation of it. - fn run_guest_configure_hosts(root: &Path) -> std::process::Output { - let script = include_str!("../scripts/openshell-vm-sandbox-init.sh"); - let start = script - .find("configure_hosts() {\n") - .expect("guest init defines configure_hosts"); - let tail = &script[start..]; - let end = tail - .find("\n}\n") - .expect("configure_hosts closes at column zero") - + "\n}\n".len(); - let program = format!( - "set -euo pipefail\n\ - ts() {{ :; }}\n\ - root_path() {{ printf '%s%s\\n' \"${{ROOT_PREFIX:-}}\" \"$1\"; }}\n\ - {}\n\ - configure_hosts\n", - &tail[..end] - ); - Command::new("bash") - .arg("-c") - .arg(program) - .env("ROOT_PREFIX", root) - .output() - .expect("run configure_hosts") - } - - #[test] - fn guest_init_populates_missing_or_empty_hosts_and_keeps_image_hosts() { - let dir = unique_temp_dir(); - let etc = dir.join("etc"); - fs::create_dir_all(&etc).expect("create etc"); - let hosts = etc.join("hosts"); - let loopback = "127.0.0.1 localhost\n::1 localhost ip6-localhost ip6-loopback\n"; - - // An image that ships no hosts file at all. - let output = run_guest_configure_hosts(&dir); - assert!(output.status.success(), "{output:?}"); - assert_eq!(fs::read_to_string(&hosts).expect("read hosts"), loopback); - - // The usual OCI placeholder: present but empty. - fs::write(&hosts, "").expect("write empty hosts"); - let output = run_guest_configure_hosts(&dir); - assert!(output.status.success(), "{output:?}"); - assert_eq!(fs::read_to_string(&hosts).expect("read hosts"), loopback); - - // A hosts file authored by the image is not rewritten. - let authored = "10.1.2.3 build-host\n"; - fs::write(&hosts, authored).expect("write authored hosts"); - let output = run_guest_configure_hosts(&dir); - assert!(output.status.success(), "{output:?}"); - assert_eq!(fs::read_to_string(&hosts).expect("read hosts"), authored); - - // An image-authored symlink is left alone, and an absolute target - // outside the workload root is never written through. - let outside = dir.join("outside-hosts"); - fs::write(&outside, "").expect("write outside hosts"); - fs::remove_file(&hosts).expect("remove hosts"); - std::os::unix::fs::symlink(&outside, &hosts).expect("link hosts"); - let output = run_guest_configure_hosts(&dir); - assert!(output.status.success(), "{output:?}"); - assert_eq!(fs::read_to_string(&outside).expect("read outside"), ""); - assert!( - fs::symlink_metadata(&hosts) - .expect("stat hosts") - .file_type() - .is_symlink() - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn guest_init_boot_path_configures_hosts_after_the_account_and_before_networking() { - // The step only helps if the boot function itself calls it, so look at - // the lines of `run_post_overlay_setup` rather than anywhere in the file. - let script = include_str!("../scripts/openshell-vm-sandbox-init.sh"); - let start = script - .find("run_post_overlay_setup() {\n") - .expect("guest init defines run_post_overlay_setup"); - let boot = &script[start..]; - let network = boot - .find("openshell-vm-init prepare-network") - .expect("boot function brings up the loopback interface"); - let lines: Vec<&str> = boot[..network].lines().map(str::trim).collect(); - let position = |call: &str| lines.iter().position(|line| *line == call); - let account = position("reconcile_sandbox_account").expect("account reconciled"); - let hosts = position("configure_hosts").expect("boot function calls configure_hosts"); - assert!( - account < hosts, - "hosts are written after the root is set up" - ); - } - - #[cfg(unix)] - #[test] - fn guest_dirs_are_traversable_under_a_private_umask() { - use std::os::unix::fs::PermissionsExt as _; - - // The umask is process-wide, so the check runs in a child. - const DIR: &str = "OPENSHELL_TEST_GUEST_DIR"; - if let Ok(dir) = std::env::var(DIR) { - create_guest_dir_all(&Path::new(&dir).join("opt/openshell/bin")).expect("create dirs"); - return; - } - - let dir = unique_temp_dir(); - let test = "rootfs::tests::guest_dirs_are_traversable_under_a_private_umask"; - let status = Command::new("sh") - .args(["-c", "umask 077; exec \"$0\" --exact \"$1\""]) - .arg(std::env::current_exe().expect("test binary")) - .arg(test) - .env(DIR, &dir) - .status() - .expect("run child"); - assert!(status.success()); - - for path in ["opt", "opt/openshell", "opt/openshell/bin"] { - let mode = fs::metadata(dir.join(path)).expect("stat").permissions(); - assert_eq!(mode.mode() & 0o777, 0o755, "{path}"); - } - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn guest_init_normalizes_the_overlay_root_before_mounting_it() { - // Overlayfs takes the root's owner and mode from upper, which the host - // creates under the gateway's umask. A private umask would make / 0700 - // and unreadable to the sandbox user. - let script = include_str!("../scripts/openshell-vm-sandbox-init.sh"); - let position = |needle: &str| script.find(needle).unwrap_or_else(|| panic!("{needle}")); - let chown = position("chown 0:0 /overlay/upper"); - let chmod = position("chmod 0755 /overlay/upper"); - let mount = position("mount -t overlay overlay"); - assert!(chown < mount && chmod < mount); - } - - #[test] - fn prepare_sandbox_rootfs_preserves_image_workdir_contents_in_rootfs() { - let dir = unique_temp_dir(); - let rootfs = dir.join("rootfs"); - - fs::create_dir_all(rootfs.join("opt/openshell/bin")).expect("create openshell bin"); - write_fake_runtime_binaries(&rootfs); - fs::create_dir_all(rootfs.join("sandbox")).expect("create sandbox workdir"); - fs::write(rootfs.join("sandbox/app.py"), "print('hello')\n").expect("write app"); - - prepare_sandbox_rootfs(&rootfs, Some(10001), Some(10001)).expect("prepare sandbox rootfs"); - - assert!(rootfs.join("sandbox").is_dir()); - assert_eq!( - fs::read_to_string(rootfs.join("sandbox/app.py")).expect("read app"), - "print('hello')\n" - ); - - let _ = fs::remove_dir_all(&dir); - } - - /// `--from` accepts `.tar.gz` and `.tgz`, so extraction must recognize a - /// gzip stream instead of handing compressed bytes to the tar reader. - #[test] - fn extract_rootfs_archive_accepts_gzip_archives() { - let dir = unique_temp_dir(); - let rootfs = dir.join("rootfs"); - let extracted = dir.join("extracted"); - let archive = dir.join("rootfs.tar"); - let gz_archive = dir.join("rootfs.tar.gz"); - - fs::create_dir_all(rootfs.join("etc")).expect("create etc"); - fs::write(rootfs.join("etc/marker.txt"), "gzip-rootfs\n").expect("write marker"); - create_rootfs_archive_from_dir(&rootfs, &archive).expect("archive rootfs"); - - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - encoder - .write_all(&fs::read(&archive).expect("read archive")) - .expect("gzip archive"); - fs::write(&gz_archive, encoder.finish().expect("finish gzip")).expect("write gzip archive"); - - extract_rootfs_archive_to(&gz_archive, &extracted).expect("extract gzip rootfs"); - - assert_eq!( - fs::read_to_string(extracted.join("etc/marker.txt")).expect("read extracted marker"), - "gzip-rootfs\n" - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[cfg(unix)] - #[test] - fn create_rootfs_archive_preserves_broken_symlinks() { - let dir = unique_temp_dir(); - let rootfs = dir.join("rootfs"); - let extracted = dir.join("extracted"); - let archive = dir.join("rootfs.tar"); - - fs::create_dir_all(rootfs.join("etc")).expect("create etc"); - fs::write(rootfs.join("etc/hosts"), "127.0.0.1 localhost\n").expect("write hosts"); - std::os::unix::fs::symlink("/proc/self/mounts", rootfs.join("etc/mtab")) - .expect("create symlink"); - - create_rootfs_archive_from_dir(&rootfs, &archive).expect("archive rootfs"); - extract_rootfs_archive_to(&archive, &extracted).expect("extract rootfs"); - - let extracted_link = extracted.join("etc/mtab"); - assert!( - fs::symlink_metadata(&extracted_link) - .unwrap() - .file_type() - .is_symlink() - ); - assert_eq!( - fs::read_link(&extracted_link).expect("read extracted symlink"), - PathBuf::from("/proc/self/mounts") - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn clone_or_copy_sparse_file_preserves_size_and_contents() { - let dir = unique_temp_dir(); - fs::create_dir_all(&dir).expect("create temp dir"); - let source = dir.join("source.bin"); - let dest = dir.join("dest.bin"); - - let mut source_file = File::create(&source).expect("create source"); - source_file.write_all(b"head").expect("write head"); - source_file - .seek(SeekFrom::Start(1024 * 1024 + 7)) - .expect("seek source"); - source_file.write_all(b"tail").expect("write tail"); - source_file - .set_len(2 * 1024 * 1024 + 3) - .expect("size source"); - drop(source_file); - - clone_or_copy_sparse_file(&source, &dest).expect("copy sparse file"); - - assert_eq!( - fs::metadata(&dest).expect("stat dest").len(), - 2 * 1024 * 1024 + 3 - ); - let mut dest_file = File::open(&dest).expect("open dest"); - let mut head = [0_u8; 4]; - dest_file.read_exact(&mut head).expect("read head"); - assert_eq!(&head, b"head"); - dest_file - .seek(SeekFrom::Start(1024 * 1024 + 7)) - .expect("seek dest"); - let mut tail = [0_u8; 4]; - dest_file.read_exact(&mut tail).expect("read tail"); - assert_eq!(&tail, b"tail"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn recover_rootfs_image_accepts_clean_ext4_image() { - if e2fs_command("e2fsck").is_err() { - return; - } - - let dir = unique_temp_dir(); - let source = dir.join("source"); - let image = dir.join("overlay.ext4"); - fs::create_dir_all(source.join("upper")).expect("create source upperdir"); - fs::create_dir_all(source.join("work")).expect("create source workdir"); - create_ext4_image_from_dir_with_size(&source, &image, 64 * 1024 * 1024) - .expect("create ext4 image"); - - recover_rootfs_image(&image).expect("recover clean ext4 image"); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn ext4_image_has_directory_distinguishes_directories_files_and_missing_paths() { - if e2fs_command("debugfs").is_err() { - return; - } - - let dir = unique_temp_dir(); - let source = dir.join("source"); - let image = dir.join("prepared.ext4"); - fs::create_dir_all(source.join("image-rootfs/bin")).expect("create image rootfs"); - fs::write(source.join("regular"), "file\n").expect("write regular file"); - create_ext4_image_from_dir_with_size(&source, &image, 64 * 1024 * 1024) - .expect("create ext4 image"); - - assert!(ext4_image_has_directory(&image, "/image-rootfs").expect("stat directory")); - assert!(!ext4_image_has_directory(&image, "/regular").expect("stat regular file")); - assert!(!ext4_image_has_directory(&image, "/missing").expect("stat missing path")); - assert!(ext4_image_has_directory(&image, "relative").is_err()); - - let not_ext4 = dir.join("not-ext4.img"); - fs::write(¬_ext4, vec![0_u8; 64 * 1024]).expect("write non-ext4 image"); - assert!(ext4_image_has_directory(¬_ext4, "/image-rootfs").is_err()); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn sandbox_guest_user_ids_reads_existing_sandbox_user() { - let dir = unique_temp_dir(); - let rootfs = dir.join("rootfs"); - fs::create_dir_all(rootfs.join("etc")).expect("create etc"); - fs::write( - rootfs.join("etc/passwd"), - "root:x:0:0:root:/root:/bin/bash\nsandbox:x:998:997:Sandbox:/sandbox:/bin/sh\n", - ) - .expect("write passwd"); - - assert_eq!( - sandbox_guest_user_ids(&rootfs).expect("read sandbox user"), - Some((998, 997)) - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn collect_sandbox_owner_commands_quotes_guest_paths() { - let dir = unique_temp_dir(); - let sandbox_dir = dir.join("sandbox"); - fs::create_dir_all(sandbox_dir.join("dir with space")).expect("create sandbox tree"); - fs::write(sandbox_dir.join("dir with space/file.txt"), "hello\n").expect("write file"); - - let mut commands = Vec::new(); - assert!( - collect_sandbox_owner_commands(&sandbox_dir, "/sandbox", 998, 997, &mut commands) - .expect("collect commands") - ); - - assert!(commands.contains(&"set_inode_field \"/sandbox\" uid 998".to_string())); - assert!(commands.contains(&"set_inode_field \"/sandbox\" gid 997".to_string())); - assert!( - commands.contains( - &"set_inode_field \"/sandbox/dir with space/file.txt\" uid 998".to_string() - ) - ); - assert!( - commands.contains( - &"set_inode_field \"/sandbox/dir with space/file.txt\" gid 997".to_string() - ) - ); - - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn debugfs_quote_argument_quotes_source_paths_with_spaces() { - assert_eq!( - debugfs_quote_argument("/tmp/openshell state/.openshell-rootfs-inject-123-0"), - Some("\"/tmp/openshell state/.openshell-rootfs-inject-123-0\"".to_string()) - ); - assert_eq!( - debugfs_quote_argument("/tmp/path/with\\backslash/and\"quote"), - Some("\"/tmp/path/with\\\\backslash/and\\\"quote\"".to_string()) - ); - assert_eq!(debugfs_quote_argument("/tmp/bad\npath"), None); - } - - fn run_tool_fixture_test(test: &str, directory: &Path) { - // Isolate PATH in a child test process. Other tests may prepare images - // concurrently and must never observe this deliberately broken tool. - let output = Command::new(std::env::current_exe().expect("test executable")) - .args(["--exact", test, "--nocapture"]) - .env("PATH", directory) - .env("OPENSHELL_ROOTFS_TOOL_TEST_ROOT", directory) - .output() - .expect("isolated tool test"); - assert!( - output.status.success(), - "stdout: {}\nstderr: {}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ); - } - - #[test] - fn formatter_preserves_selected_tool_failure_without_retry() { - use std::os::unix::fs::PermissionsExt as _; - - if let Some(directory) = std::env::var_os("OPENSHELL_ROOTFS_TOOL_TEST_ROOT") { - let directory = PathBuf::from(directory); - let image = directory.join("rootfs.ext4"); - File::create(&image) - .expect("image") - .set_len(16 * 1024 * 1024) - .expect("image size"); - let source = directory.join("source"); - fs::create_dir(&source).expect("source directory"); - let error = format_ext4_image_from_dir(&source, &image) - .expect_err("the selected formatter failure must not select another installation"); - assert!(error.contains("selected-formatter-failed"), "{error}"); - assert!(error.contains("42"), "{error}"); - return; - } - let directory = tempfile::tempdir().expect("tool installation"); - for (name, body) in [ - ("mke2fs", "echo selected-formatter-failed >&2\nexit 42"), - ("mkfs.ext4", "exit 0"), - ] { - let path = directory.path().join(name); - fs::write(&path, format!("#!/bin/sh\n{body}\n")).expect("tool fixture"); - fs::set_permissions(path, fs::Permissions::from_mode(0o755)).expect("executable"); - } - run_tool_fixture_test( - "rootfs::tests::formatter_preserves_selected_tool_failure_without_retry", - directory.path(), - ); - } - - #[test] - fn recovery_preserves_selected_path_and_execution_errors() { - use std::os::unix::fs::PermissionsExt as _; - - if let Some(directory) = std::env::var_os("OPENSHELL_ROOTFS_TOOL_TEST_ROOT") { - let directory = PathBuf::from(directory); - let path = directory.join("e2fsck"); - for (script, expected) in [ - ( - "#!/nonexistent/e2fsprogs-interpreter\n", - "No such file or directory", - ), - ( - "#!/bin/sh\necho recovery-failed >&2\nexit 4\n", - "recovery-failed", - ), - ] { - fs::write(&path, script).expect("recovery tool"); - fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("executable"); - let error = recover_rootfs_image(&directory.join("overlay.ext4")) - .expect_err("recovery failure"); - assert!( - error.contains(path.canonicalize().unwrap().to_str().unwrap()), - "{error}" - ); - assert!(error.contains(expected), "{error}"); - } - return; - } - let directory = tempfile::tempdir().expect("tool installation"); - run_tool_fixture_test( - "rootfs::tests::recovery_preserves_selected_path_and_execution_errors", - directory.path(), - ); - } - - fn unique_temp_dir() -> PathBuf { - static COUNTER: AtomicU64 = AtomicU64::new(0); - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("time went backwards") - .as_nanos(); - let suffix = COUNTER.fetch_add(1, Ordering::Relaxed); - std::env::temp_dir().join(format!( - "openshell-driver-vm-rootfs-test-{}-{nanos}-{suffix}", - std::process::id() - )) - } - - fn write_fake_runtime_binaries(rootfs: &Path) { - fs::write( - rootfs.join("opt/openshell/bin/openshell-sandbox"), - b"sandbox", - ) - .expect("write openshell-sandbox"); - fs::write( - rootfs.join("opt/openshell/bin/openshell-vm-init"), - b"vm-init", - ) - .expect("write openshell-vm-init"); - fs::write(rootfs.join("opt/openshell/bin/umoci"), b"umoci").expect("write umoci"); - } - - #[test] - fn sandbox_guest_user_ids_reads_prepared_image_rootfs() { - if e2fs_command("debugfs").is_err() { - return; - } - - let dir = unique_temp_dir(); - let source = dir.join("source"); - fs::create_dir_all(source.join("image-rootfs/etc")).expect("create etc"); - fs::write( - source.join("image-rootfs/etc/passwd"), - "sandbox:x:10001:10001::/sandbox:/bin/sh\n", - ) - .expect("write passwd"); - - let image = dir.join("prepared.ext4"); - create_ext4_image_from_dir_with_size(&source, &image, 64 * 1024 * 1024) - .expect("create ext4 image"); - - assert_eq!( - sandbox_guest_user_ids_from_image(&image).expect("read identity"), - Some((10001, 10001)) - ); - let _ = fs::remove_dir_all(&dir); - } - - #[test] - fn sandbox_guest_user_ids_prepared_image_without_sandbox_user_is_none() { - if e2fs_command("debugfs").is_err() { - return; - } - - let dir = unique_temp_dir(); - let source = dir.join("source"); - fs::create_dir_all(source.join("image-rootfs/etc")).expect("create etc"); - fs::write( - source.join("image-rootfs/etc/passwd"), - "root:x:0:0:root:/root:/bin/sh\n", - ) - .expect("write passwd"); - - let image = dir.join("prepared.ext4"); - create_ext4_image_from_dir_with_size(&source, &image, 64 * 1024 * 1024) - .expect("create ext4 image"); - - assert_eq!( - sandbox_guest_user_ids_from_image(&image).expect("read identity"), - None - ); - let _ = fs::remove_dir_all(&dir); - } -} diff --git a/crates/openshell-driver-vm/src/runtime.rs b/crates/openshell-driver-vm/src/runtime.rs deleted file mode 100644 index ad300d98cf..0000000000 --- a/crates/openshell-driver-vm/src/runtime.rs +++ /dev/null @@ -1,927 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![allow(unsafe_code)] - -use std::ffi::CString; -use std::path::{Path, PathBuf}; -use std::process::{Command as StdCommand, Stdio}; -use std::ptr; -use std::sync::atomic::{AtomicI32, Ordering}; -use std::time::Duration; - -use crate::{embedded_runtime, ffi, procguard, rootfs}; - -pub const VM_RUNTIME_DIR_ENV: &str = "OPENSHELL_VM_RUNTIME_DIR"; -const KRUN_INIT_PID1_ENV: &str = "KRUN_INIT_PID1=1"; - -/// PID of the VM worker process (libkrun fork or QEMU). Zero when not running. -/// Used by the SIGTERM/SIGINT handler to forward signals to the VM. -static CHILD_PID: AtomicI32 = AtomicI32::new(0); - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum VmBackend { - Libkrun, - Qemu, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct VsockPortMap { - pub guest_port: u32, - pub host_socket: PathBuf, - pub host_initiated: bool, -} - -/// A host directory shared into the VM guest via virtiofs. -#[derive(Debug, Clone)] -pub struct VmMount { - pub tag: String, - pub host_path: PathBuf, - pub read_only: bool, -} - -pub struct VmLaunchConfig { - pub root_disk: PathBuf, - pub overlay_disk: PathBuf, - pub image_disk: Option, - pub kernel_image: Option, - pub vcpus: u8, - pub mem_mib: u32, - pub exec_path: String, - pub args: Vec, - pub env: Vec, - pub workdir: String, - pub log_level: u32, - pub console_output: PathBuf, - pub backend: VmBackend, - pub gpu_bdf: Option, - pub vsock_cid: Option, - pub vsock_port_map: Option, - pub mounts: Vec, -} - -pub fn run_vm(config: &VmLaunchConfig) -> Result<(), String> { - match config.backend { - VmBackend::Qemu => run_qemu_vm(config), - VmBackend::Libkrun => run_libkrun_vm(config), - } -} - -fn run_qemu_vm(config: &VmLaunchConfig) -> Result<(), String> { - if !config.mounts.is_empty() { - return Err("virtiofs mounts are not yet supported with the QEMU backend".to_string()); - } - let gpu_bdf = config - .gpu_bdf - .as_deref() - .ok_or("gpu_bdf is required for QEMU backend")?; - let vsock_cid = config - .vsock_cid - .ok_or("vsock_cid is required for QEMU backend")?; - - if !config.root_disk.is_file() { - return Err(format!( - "root disk image not found: {}", - config.root_disk.display() - )); - } - if !config.overlay_disk.is_file() { - return Err(format!( - "overlay disk image not found: {}", - config.overlay_disk.display() - )); - } - if let Some(image_disk) = &config.image_disk - && !image_disk.is_file() - { - return Err(format!("image disk not found: {}", image_disk.display())); - } - - if let Err(err) = procguard::die_with_parent_cleanup(procguard_kill_children) { - return Err(format!("procguard arm failed: {err}")); - } - - #[cfg(target_os = "linux")] - check_kvm_access()?; - - let guest_env = qemu_guest_env_vars(config); - write_guest_env_file(&config.overlay_disk, &guest_env)?; - - let vmlinux = if let Some(kernel_image) = &config.kernel_image { - kernel_image.clone() - } else { - qemu_runtime_dir()?.join("vmlinux") - }; - if !vmlinux.is_file() { - return Err(format!("VM kernel not found: {}", vmlinux.display())); - } - - let kernel_cmdline = build_kernel_cmdline(config); - - let mut qemu_cmd = StdCommand::new("qemu-system-x86_64"); - qemu_cmd - .arg("-machine") - .arg("q35,accel=kvm") - .arg("-cpu") - .arg("host") - .arg("-smp") - .arg(config.vcpus.to_string()) - .arg("-m") - .arg(format!("{}M", config.mem_mib)) - .arg("-nographic") - .arg("-no-reboot") - .args(qemu_network_args()) - .arg("-kernel") - .arg(&vmlinux) - .arg("-append") - .arg(&kernel_cmdline) - .args(qemu_disk_args(config)) - .arg("-device") - .arg("pcie-root-port,id=vsock_root,slot=1") - .arg("-device") - .arg(format!( - "vhost-vsock-pci,guest-cid={vsock_cid},bus=vsock_root" - )) - .arg("-device") - .arg("pcie-root-port,id=gpu_root,slot=2") - .arg("-device") - .arg(format!("vfio-pci,host={gpu_bdf},bus=gpu_root")) - .arg("-serial") - .arg(format!("file:{}", config.console_output.display())); - - qemu_cmd.stdin(Stdio::null()); - qemu_cmd.stdout(Stdio::inherit()); - qemu_cmd.stderr(Stdio::inherit()); - - #[cfg(target_os = "linux")] - { - use nix::sys::signal::Signal; - use std::os::unix::process::CommandExt as _; - unsafe { - qemu_cmd.pre_exec(|| { - nix::sys::prctl::set_pdeathsig(Signal::SIGKILL) - .map_err(|err| std::io::Error::other(format!("pdeathsig: {err}"))) - }); - } - } - - let mut qemu_child = qemu_cmd - .spawn() - .map_err(|e| format!("failed to start QEMU: {e}"))?; - - let qemu_pid = qemu_child.id().cast_signed(); - install_signal_forwarding(qemu_pid); - - let status = qemu_child - .wait() - .map_err(|e| format!("failed to wait for QEMU: {e}"))?; - - CHILD_PID.store(0, Ordering::Relaxed); - - if status.success() { - Ok(()) - } else { - Err(format!("QEMU exited with status {status}")) - } -} - -fn qemu_network_args() -> [&'static str; 2] { - ["-nic", "none"] -} - -fn qemu_disk_args(config: &VmLaunchConfig) -> Vec { - let mut args = vec![ - "-drive".to_string(), - format!( - "file={},if=none,format=raw,id=rootfs,readonly=on", - config.root_disk.display() - ), - "-device".to_string(), - "virtio-blk-pci,drive=rootfs".to_string(), - "-drive".to_string(), - format!( - "file={},if=none,format=raw,id=overlay", - config.overlay_disk.display() - ), - "-device".to_string(), - "virtio-blk-pci,drive=overlay".to_string(), - ]; - if let Some(image_disk) = &config.image_disk { - args.extend([ - "-drive".to_string(), - format!( - "file={},if=none,format=raw,id=image,readonly=on", - image_disk.display() - ), - "-device".to_string(), - "virtio-blk-pci,drive=image".to_string(), - ]); - } - args -} - -/// Write environment variables into the overlay disk so the guest init script -/// can source them after the overlay root is mounted. QEMU does not provide a -/// `krun_set_exec` equivalent, so the launcher injects this small per-sandbox -/// file into the overlay upperdir before boot. -fn write_guest_env_file(overlay_disk: &Path, env_vars: &[String]) -> Result<(), String> { - let mut content = String::new(); - for var in env_vars { - if let Some((key, value)) = var.split_once('=') { - use std::fmt::Write as _; - let _ = writeln!(content, "export {key}=\"{}\"", shell_escape(value)); - } - } - rootfs::write_rootfs_image_file( - overlay_disk, - "/upper/srv/openshell-env.sh", - content.as_bytes(), - ) -} - -fn qemu_guest_env_vars(config: &VmLaunchConfig) -> Vec { - let mut env_vars = config.env.clone(); - if config.gpu_bdf.is_some() { - env_vars.push("GPU_ENABLED=true".to_string()); - } - - env_vars -} - -/// Escape a string for use inside bash double quotes. -fn shell_escape(s: &str) -> String { - s.replace('\\', "\\\\") - .replace('"', "\\\"") - .replace('$', "\\$") - .replace('`', "\\`") - .replace('\n', "\\n") - .replace('\r', "\\r") -} - -fn build_kernel_cmdline(config: &VmLaunchConfig) -> String { - let mut parts = vec![ - "console=ttyS0".to_string(), - "root=/dev/vda".to_string(), - "rootfstype=ext4".to_string(), - "ro".to_string(), - "panic=-1".to_string(), - format!("init={}", config.exec_path), - ]; - - if config.gpu_bdf.is_some() { - parts.push("firmware_class.path=/lib/firmware".to_string()); - } - - parts.join(" ") -} - -/// Shared procguard cleanup callback for both libkrun and QEMU paths. -/// Only async-signal-safe calls: atomic loads and `kill(2)`. -fn procguard_kill_children() { - let child_pid = CHILD_PID.load(Ordering::Relaxed); - if child_pid > 0 { - unsafe { - libc::kill(child_pid, libc::SIGTERM); - } - } - std::thread::sleep(Duration::from_millis(200)); - if child_pid > 0 { - unsafe { - libc::kill(child_pid, libc::SIGKILL); - } - } -} - -fn run_libkrun_vm(config: &VmLaunchConfig) -> Result<(), String> { - if let Some(kernel_image) = &config.kernel_image { - return Err(format!( - "selected kernel image is not supported by this VM backend: {}", - kernel_image.display() - )); - } - if !config.root_disk.is_file() { - return Err(format!( - "root disk image not found: {}", - config.root_disk.display() - )); - } - if !config.overlay_disk.is_file() { - return Err(format!( - "overlay disk image not found: {}", - config.overlay_disk.display() - )); - } - if let Some(image_disk) = &config.image_disk - && !image_disk.is_file() - { - return Err(format!("image disk not found: {}", image_disk.display())); - } - - // Arm procguard before forking libkrun so the VM worker cannot outlive - // the launcher. No network helper is started: the only host/guest data - // paths are the protected vsock mapping below and any operator-enabled - // virtiofs shares. - if let Err(err) = procguard::die_with_parent_cleanup(procguard_kill_children) { - return Err(format!("procguard arm failed: {err}")); - } - - #[cfg(target_os = "linux")] - check_kvm_access()?; - - let runtime_dir = configured_runtime_dir()?; - validate_runtime_dir(&runtime_dir)?; - configure_runtime_loader_env(&runtime_dir)?; - raise_nofile_limit(); - - let vm = VmContext::create(&runtime_dir, config.log_level)?; - vm.set_vm_config(config.vcpus, config.mem_mib)?; - vm.set_disks( - &config.root_disk, - &config.overlay_disk, - config.image_disk.as_deref(), - )?; - vm.set_workdir(&config.workdir)?; - - vm.disable_implicit_vsock()?; - vm.add_vsock(0)?; - if let Some(port_map) = &config.vsock_port_map { - if port_map.host_initiated { - let _ = std::fs::remove_file(&port_map.host_socket); - } - vm.add_vsock_port(port_map)?; - } - - for mount in &config.mounts { - vm.add_virtiofs(&mount.tag, &mount.host_path, mount.read_only)?; - } - - vm.set_console_output(&config.console_output)?; - - let env = libkrun_guest_env(config); - vm.set_exec(&config.exec_path, &config.args, &env)?; - - let pid = unsafe { libc::fork() }; - match pid { - -1 => Err(format!("fork failed: {}", std::io::Error::last_os_error())), - 0 => { - // We are the libkrun worker (the VM's PID 1 inside the guest - // kernel, but a normal host process until krun_start_enter - // fires). Arm procguard so this fork is SIGKILLed if the - // parent launcher dies abruptly. On Linux this uses - // `PR_SET_PDEATHSIG`; on macOS this spawns a kqueue - // NOTE_EXIT watcher thread. - // - // We also SIGKILL ourselves if arming fails — there's no - // safe way to continue if we can't guarantee cleanup. - if let Err(err) = procguard::die_with_parent() { - eprintln!("libkrun worker: procguard arm failed: {err}"); - std::process::exit(1); - } - let ret = vm.start_enter(); - eprintln!("krun_start_enter failed: {ret}"); - std::process::exit(1); - } - _ => { - install_signal_forwarding(pid); - - let status = wait_for_child(pid)?; - CHILD_PID.store(0, Ordering::Relaxed); - if libc::WIFEXITED(status) { - match libc::WEXITSTATUS(status) { - 0 => Ok(()), - code => Err(format!("VM exited with status {code}")), - } - } else if libc::WIFSIGNALED(status) { - let sig = libc::WTERMSIG(status); - Err(format!("VM killed by signal {sig}")) - } else { - Err(format!("VM exited with unexpected wait status {status}")) - } - } - } -} - -fn libkrun_guest_env(config: &VmLaunchConfig) -> Vec { - let mut env = if config.env.is_empty() { - vec![ - "HOME=/root".to_string(), - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".to_string(), - "TERM=xterm".to_string(), - ] - } else { - config.env.clone() - }; - - // libkrun normally keeps /init.krun as PID 1 and forks the configured - // executable. OpenShell's guest init is itself an init process and ends - // by exec'ing the supervisor, so ask libkrun to exec it directly. Keep - // this driver-owned setting authoritative over sandbox image/user env. - env.retain(|value| !value.starts_with("KRUN_INIT_PID1=")); - env.push(KRUN_INIT_PID1_ENV.to_string()); - env -} - -pub fn validate_runtime_dir(dir: &Path) -> Result<(), String> { - if !dir.is_dir() { - return Err(format!( - "VM runtime not found at {}. Run `mise run vm:setup` or set {VM_RUNTIME_DIR_ENV}", - dir.display() - )); - } - - embedded_runtime::validate_runtime_dir(dir) -} - -pub fn configured_runtime_dir() -> Result { - if let Some(path) = std::env::var_os(VM_RUNTIME_DIR_ENV) { - return Ok(PathBuf::from(path)); - } - embedded_runtime::ensure_runtime_extracted() -} - -fn qemu_runtime_dir() -> Result { - configured_runtime_dir().map_err(|_| { - "QEMU backend requires OPENSHELL_VM_RUNTIME_DIR to be set (pointing to a directory \ - containing vmlinux). Set the env var or run `mise run vm:setup`." - .to_string() - }) -} - -#[cfg(target_os = "macos")] -fn configure_runtime_loader_env(runtime_dir: &Path) -> Result<(), String> { - let existing = std::env::var_os("DYLD_FALLBACK_LIBRARY_PATH"); - let mut paths = vec![runtime_dir.to_path_buf()]; - if let Some(existing) = existing { - paths.extend(std::env::split_paths(&existing)); - } - let joined = - std::env::join_paths(paths).map_err(|e| format!("join DYLD_FALLBACK_LIBRARY_PATH: {e}"))?; - unsafe { - std::env::set_var("DYLD_FALLBACK_LIBRARY_PATH", joined); - } - Ok(()) -} - -#[cfg(target_os = "linux")] -fn configure_runtime_loader_env(runtime_dir: &Path) -> Result<(), String> { - let existing = std::env::var_os("LD_LIBRARY_PATH"); - let mut paths = vec![runtime_dir.to_path_buf()]; - if let Some(existing) = existing { - paths.extend(std::env::split_paths(&existing)); - } - let joined = std::env::join_paths(paths).map_err(|e| format!("join LD_LIBRARY_PATH: {e}"))?; - unsafe { - std::env::set_var("LD_LIBRARY_PATH", joined); - } - Ok(()) -} - -#[cfg(not(any(target_os = "macos", target_os = "linux")))] -fn configure_runtime_loader_env(_runtime_dir: &Path) -> Result<(), String> { - Ok(()) -} - -fn raise_nofile_limit() { - #[cfg(unix)] - if let Ok((_, maximum)) = - nix::sys::resource::getrlimit(nix::sys::resource::Resource::RLIMIT_NOFILE) - { - let _ = nix::sys::resource::setrlimit( - nix::sys::resource::Resource::RLIMIT_NOFILE, - maximum, - maximum, - ); - } -} - -fn clamp_log_level(level: u32) -> u32 { - match level { - 0 => ffi::KRUN_LOG_LEVEL_OFF, - 1 => ffi::KRUN_LOG_LEVEL_ERROR, - 2 => ffi::KRUN_LOG_LEVEL_WARN, - 3 => ffi::KRUN_LOG_LEVEL_INFO, - 4 => ffi::KRUN_LOG_LEVEL_DEBUG, - _ => ffi::KRUN_LOG_LEVEL_TRACE, - } -} - -struct VmContext { - krun: &'static ffi::LibKrun, - ctx_id: u32, -} - -impl VmContext { - fn create(runtime_dir: &Path, log_level: u32) -> Result { - let krun = ffi::libkrun(runtime_dir)?; - check( - unsafe { - (krun.krun_init_log)( - ffi::KRUN_LOG_TARGET_DEFAULT, - clamp_log_level(log_level), - ffi::KRUN_LOG_STYLE_AUTO, - ffi::KRUN_LOG_OPTION_NO_ENV, - ) - }, - "krun_init_log", - )?; - - let ctx_id = unsafe { (krun.krun_create_ctx)() }; - if ctx_id < 0 { - return Err(format!("krun_create_ctx failed with error code {ctx_id}")); - } - - Ok(Self { - krun, - ctx_id: ctx_id.cast_unsigned(), - }) - } - - fn set_vm_config(&self, vcpus: u8, mem_mib: u32) -> Result<(), String> { - check( - unsafe { (self.krun.krun_set_vm_config)(self.ctx_id, vcpus, mem_mib) }, - "krun_set_vm_config", - ) - } - - fn set_disks( - &self, - root_disk: &Path, - overlay_disk: &Path, - image_disk: Option<&Path>, - ) -> Result<(), String> { - let root_disk_c = path_to_cstring(root_disk)?; - let block_id_c = CString::new("root").map_err(|e| format!("invalid block id: {e}"))?; - check( - unsafe { - (self.krun.krun_add_disk)( - self.ctx_id, - block_id_c.as_ptr(), - root_disk_c.as_ptr(), - true, - ) - }, - "krun_add_disk", - )?; - - let overlay_disk_c = path_to_cstring(overlay_disk)?; - let overlay_block_id_c = - CString::new("overlay").map_err(|e| format!("invalid block id: {e}"))?; - check( - unsafe { - (self.krun.krun_add_disk)( - self.ctx_id, - overlay_block_id_c.as_ptr(), - overlay_disk_c.as_ptr(), - false, - ) - }, - "krun_add_disk", - )?; - - if let Some(image_disk) = image_disk { - let image_disk_c = path_to_cstring(image_disk)?; - let image_block_id_c = - CString::new("image").map_err(|e| format!("invalid image block id: {e}"))?; - check( - unsafe { - (self.krun.krun_add_disk)( - self.ctx_id, - image_block_id_c.as_ptr(), - image_disk_c.as_ptr(), - true, - ) - }, - "krun_add_disk", - )?; - } - - let device_c = - CString::new("/dev/vda").map_err(|e| format!("invalid root disk device: {e}"))?; - let fstype_c = - CString::new("ext4").map_err(|e| format!("invalid root disk fstype: {e}"))?; - let options_c = - CString::new("ro").map_err(|e| format!("invalid root disk options: {e}"))?; - check( - unsafe { - (self.krun.krun_set_root_disk_remount)( - self.ctx_id, - device_c.as_ptr(), - fstype_c.as_ptr(), - options_c.as_ptr(), - ) - }, - "krun_set_root_disk_remount", - ) - } - - fn set_workdir(&self, workdir: &str) -> Result<(), String> { - let workdir_c = CString::new(workdir).map_err(|e| format!("invalid workdir: {e}"))?; - check( - unsafe { (self.krun.krun_set_workdir)(self.ctx_id, workdir_c.as_ptr()) }, - "krun_set_workdir", - ) - } - - fn disable_implicit_vsock(&self) -> Result<(), String> { - check( - unsafe { (self.krun.krun_disable_implicit_vsock)(self.ctx_id) }, - "krun_disable_implicit_vsock", - ) - } - - fn add_vsock(&self, tsi_features: u32) -> Result<(), String> { - check( - unsafe { (self.krun.krun_add_vsock)(self.ctx_id, tsi_features) }, - "krun_add_vsock", - ) - } - - fn add_vsock_port(&self, port_map: &VsockPortMap) -> Result<(), String> { - let socket_c = path_to_cstring(&port_map.host_socket)?; - check( - unsafe { - (self.krun.krun_add_vsock_port2)( - self.ctx_id, - port_map.guest_port, - socket_c.as_ptr(), - port_map.host_initiated, - ) - }, - "krun_add_vsock_port2", - ) - } - - fn set_console_output(&self, path: &Path) -> Result<(), String> { - let console_c = path_to_cstring(path)?; - check( - unsafe { (self.krun.krun_set_console_output)(self.ctx_id, console_c.as_ptr()) }, - "krun_set_console_output", - ) - } - - fn set_exec(&self, exec_path: &str, args: &[String], env: &[String]) -> Result<(), String> { - let exec_c = CString::new(exec_path).map_err(|e| format!("invalid exec path: {e}"))?; - let argv_slices: Vec<&str> = args.iter().map(String::as_str).collect(); - let (_argv_owners, argv_ptrs) = c_string_array(&argv_slices)?; - let env_slices: Vec<&str> = env.iter().map(String::as_str).collect(); - let (_env_owners, env_ptrs) = c_string_array(&env_slices)?; - - check( - unsafe { - (self.krun.krun_set_exec)( - self.ctx_id, - exec_c.as_ptr(), - argv_ptrs.as_ptr(), - env_ptrs.as_ptr(), - ) - }, - "krun_set_exec", - ) - } - - fn add_virtiofs(&self, tag: &str, host_path: &Path, read_only: bool) -> Result<(), String> { - // KRUN_SEMANTICS_LINUX_SIMPLIFIED: guest ownership is not recorded on - // host files and permission bits are stored on the host directly, not - // in extended attributes. Only the macOS passthrough applies that; on - // Linux the mode just disables attribute caching and idmapped mounts. - const SEMANTICS_SIMPLIFIED: u32 = 1; - let tag_c = CString::new(tag).map_err(|e| format!("invalid virtiofs tag: {e}"))?; - let path_c = path_to_cstring(host_path)?; - let add_virtiofs4 = *self.krun.krun_add_virtiofs4.as_ref().map_err(|err| { - format!("VM bind mounts need a libkrun runtime with virtiofs support: {err}") - })?; - check( - unsafe { - add_virtiofs4( - self.ctx_id, - tag_c.as_ptr(), - path_c.as_ptr(), - 0, - read_only, - SEMANTICS_SIMPLIFIED, - ) - }, - "krun_add_virtiofs4", - ) - } - - fn start_enter(&self) -> i32 { - unsafe { (self.krun.krun_start_enter)(self.ctx_id) } - } -} - -impl Drop for VmContext { - fn drop(&mut self) { - let ret = unsafe { (self.krun.krun_free_ctx)(self.ctx_id) }; - if ret < 0 { - eprintln!( - "warning: krun_free_ctx({}) failed with code {ret}", - self.ctx_id - ); - } - } -} - -fn install_signal_forwarding(pid: i32) { - unsafe { - libc::signal( - libc::SIGINT, - forward_signal as *const () as libc::sighandler_t, - ); - libc::signal( - libc::SIGTERM, - forward_signal as *const () as libc::sighandler_t, - ); - } - CHILD_PID.store(pid, Ordering::Relaxed); -} - -/// Async-signal-safe handler that forwards SIGTERM to the VM worker. -/// -/// Only async-signal-safe libc calls are used — `kill(2)` is listed in -/// POSIX.1-2017 as async-signal-safe, atomic loads are lock-free on the -/// platforms we target. -extern "C" fn forward_signal(_sig: libc::c_int) { - let vm_pid = CHILD_PID.load(Ordering::Relaxed); - if vm_pid > 0 { - unsafe { - libc::kill(vm_pid, libc::SIGTERM); - } - } -} - -fn wait_for_child(pid: i32) -> Result { - let mut status: libc::c_int = 0; - let rc = unsafe { libc::waitpid(pid, &raw mut status, 0) }; - if rc < 0 { - return Err(format!( - "waitpid({pid}) failed: {}", - std::io::Error::last_os_error() - )); - } - Ok(status) -} - -fn check(ret: i32, func: &'static str) -> Result<(), String> { - if ret < 0 { - Err(format!("{func} failed with error code {ret}")) - } else { - Ok(()) - } -} - -fn c_string_array(strings: &[&str]) -> Result<(Vec, Vec<*const libc::c_char>), String> { - let owned: Vec = strings - .iter() - .map(|s| CString::new(*s)) - .collect::, _>>() - .map_err(|e| format!("invalid string array entry: {e}"))?; - let mut ptrs: Vec<*const libc::c_char> = owned.iter().map(|c| c.as_ptr()).collect(); - ptrs.push(ptr::null()); - Ok((owned, ptrs)) -} - -fn path_to_cstring(path: &Path) -> Result { - let path = path - .to_str() - .ok_or_else(|| format!("path is not valid UTF-8: {}", path.display()))?; - CString::new(path).map_err(|e| format!("invalid path string {path}: {e}")) -} - -#[cfg(target_os = "linux")] -fn check_kvm_access() -> Result<(), String> { - std::fs::OpenOptions::new() - .read(true) - .open("/dev/kvm") - .map(|_| ()) - .map_err(|e| { - format!("cannot open /dev/kvm: {e}\nKVM access is required to run microVMs on Linux.") - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn qemu_config() -> VmLaunchConfig { - VmLaunchConfig { - root_disk: PathBuf::from("/rootfs.ext4"), - overlay_disk: PathBuf::from("/overlay.ext4"), - image_disk: None, - kernel_image: None, - vcpus: 2, - mem_mib: 2048, - exec_path: "/srv/openshell-vm-sandbox-init.sh".to_string(), - args: Vec::new(), - env: vec!["OPENSHELL_ENDPOINT=http://10.0.128.1:8080".to_string()], - workdir: "/".to_string(), - log_level: 0, - console_output: PathBuf::from("/console.log"), - backend: VmBackend::Qemu, - gpu_bdf: Some("0000:01:00.0".to_string()), - vsock_cid: Some(4), - vsock_port_map: None, - mounts: Vec::new(), - } - } - - #[test] - fn qemu_guest_env_vars_omit_network_metadata() { - let env = qemu_guest_env_vars(&qemu_config()); - - assert!(env.contains(&"OPENSHELL_ENDPOINT=http://10.0.128.1:8080".to_string())); - assert!(!env.iter().any(|value| value.starts_with("VM_NET_"))); - assert!(env.contains(&"GPU_ENABLED=true".to_string())); - } - - #[test] - fn libkrun_guest_env_runs_guest_init_as_pid_one() { - let env = libkrun_guest_env(&qemu_config()); - - assert!(env.contains(&"OPENSHELL_ENDPOINT=http://10.0.128.1:8080".to_string())); - assert!(env.contains(&KRUN_INIT_PID1_ENV.to_string())); - } - - #[test] - fn libkrun_guest_env_overrides_caller_pid_one_setting() { - let mut config = qemu_config(); - config.env.extend([ - "KRUN_INIT_PID1=0".to_string(), - "KRUN_INIT_PID1=unexpected".to_string(), - ]); - - let env = libkrun_guest_env(&config); - let pid_one_settings = env - .iter() - .filter(|value| value.starts_with("KRUN_INIT_PID1=")) - .collect::>(); - - assert_eq!(pid_one_settings.len(), 1); - assert_eq!(pid_one_settings[0], KRUN_INIT_PID1_ENV); - } - - #[test] - fn libkrun_guest_env_keeps_defaults_when_no_env_is_configured() { - let mut config = qemu_config(); - config.env.clear(); - - let env = libkrun_guest_env(&config); - - assert!(env.contains(&"HOME=/root".to_string())); - assert!(env.contains(&"TERM=xterm".to_string())); - assert!(env.contains(&KRUN_INIT_PID1_ENV.to_string())); - } - - #[test] - fn kernel_cmdline_has_no_guest_network_configuration() { - let cmdline = build_kernel_cmdline(&qemu_config()); - - assert!(cmdline.contains("root=/dev/vda")); - assert!(cmdline.contains("rootfstype=ext4")); - assert!(cmdline.contains(" ro")); - assert!(!cmdline.contains("ip=")); - assert!(cmdline.contains("firmware_class.path=/lib/firmware")); - assert!(!cmdline.contains("VM_NET_IP=")); - assert!(!cmdline.contains("VM_NET_GW=")); - assert!(!cmdline.contains("VM_NET_DNS=")); - assert!(!cmdline.contains("GPU_ENABLED=")); - } - - #[test] - fn qemu_disk_args_attach_base_readonly_and_overlay_readwrite() { - let args = qemu_disk_args(&qemu_config()); - - assert!(args.contains(&"-drive".to_string())); - assert!( - args.contains( - &"file=/rootfs.ext4,if=none,format=raw,id=rootfs,readonly=on".to_string() - ) - ); - assert!(args.contains(&"virtio-blk-pci,drive=rootfs".to_string())); - assert!(args.contains(&"file=/overlay.ext4,if=none,format=raw,id=overlay".to_string())); - assert!( - !args - .iter() - .any(|arg| arg.contains("id=overlay,readonly=on")) - ); - assert!(args.contains(&"virtio-blk-pci,drive=overlay".to_string())); - } - - #[test] - fn qemu_explicitly_disables_implicit_network_devices() { - assert_eq!(qemu_network_args(), ["-nic", "none"]); - } - - #[test] - fn qemu_disk_args_attach_prepared_image_readonly_when_present() { - let mut config = qemu_config(); - config.image_disk = Some(PathBuf::from("/image-rootfs.ext4")); - - let args = qemu_disk_args(&config); - - assert!(args.contains( - &"file=/image-rootfs.ext4,if=none,format=raw,id=image,readonly=on".to_string() - )); - assert!(args.contains(&"virtio-blk-pci,drive=image".to_string())); - } -} diff --git a/crates/openshell-driver-vm/src/serve.rs b/crates/openshell-driver-vm/src/serve.rs deleted file mode 100644 index b419ae2b19..0000000000 --- a/crates/openshell-driver-vm/src/serve.rs +++ /dev/null @@ -1,378 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! The launched-driver commands: `serve` and `preflight`. -//! -//! The gateway starts `serve` with only bootstrap arguments and the operator's -//! `[openshell.drivers.vm]` table on stdin, then delivers gateway-owned -//! metadata with the `Configure` RPC. No VM state is created before -//! `Configure` succeeds. - -use std::path::PathBuf; - -use clap::Parser; -use openshell_core::VERSION; -use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; -use openshell_driver_sdk::launch::{ConfigureRequest, Deferred, Launch, LaunchInfo}; -use openshell_driver_sdk::{GatewayContext, StartResult}; -use openshell_driver_vm::settings::{VmSettings, settings_with_environment}; -use openshell_driver_vm::{VmDriver, VmDriverConfig, procguard}; -use tokio::net::UnixListener; -use tonic::Status; -use tracing::info; - -/// Bootstrap arguments the gateway passes to `serve`. They are frozen for -/// protocol version 1. -#[derive(Parser, Debug)] -#[command(name = "openshell-driver-vm serve")] -struct ServeArgs { - #[arg(long)] - bind_socket: PathBuf, - - #[arg(long)] - expected_peer_pid: u32, - - #[arg(long, default_value = "info")] - log_level: String, - - #[arg(long, env = "OPENSHELL_VM_GPU")] - gpu: bool, - - #[arg(long, env = "OPENSHELL_VM_GPU_MEM_MIB", default_value_t = 8192)] - gpu_mem_mib: u32, - - #[arg(long, env = "OPENSHELL_VM_GPU_VCPUS", default_value_t = 4)] - gpu_vcpus: u8, -} - -/// Run `serve` or `preflight` when that is the first argument, and return the -/// process exit code. Any other invocation returns `None` and takes the -/// standalone path. -pub async fn dispatch() -> Option { - let args: Vec = std::env::args().collect(); - match args.get(1)?.as_str() { - "serve" => { - let parsed = ServeArgs::parse_from( - std::iter::once("openshell-driver-vm serve".to_string()) - .chain(args.into_iter().skip(2)), - ); - Some(serve(parsed).await) - } - "preflight" => Some(preflight()), - _ => None, - } -} - -fn read_settings() -> Result { - let table = openshell_driver_sdk::read_stdin_table() - .map_err(|error| StartResult::invalid_config(format!("read driver table: {error}")))?; - settings_with_environment(&table, &|name| std::env::var(name).ok()) - .map_err(|error| StartResult::invalid_config(error.to_string())) -} - -fn preflight() -> i32 { - match read_settings() { - Ok(_) => 0, - Err(result) => result.report(), - } -} - -async fn serve(args: ServeArgs) -> i32 { - let tracing = openshell_otel::install_deferred_driver_tracing( - openshell_driver_vm::otel_tracing::TRACING, - &args.log_level, - openshell_core::color::stdout_ansi(), - ); - match run(args, tracing).await { - Ok(()) => 0, - Err(result) => result.report(), - } -} - -async fn run( - args: ServeArgs, - tracing: openshell_otel::DeferredDriverTracing, -) -> Result<(), StartResult> { - let settings = read_settings()?; - // The VM driver has no backend to reach before construction, which - // `Configure` triggers: libkrun and image preparation are used per sandbox. - - crate::listener::prepare_compute_driver_socket(&args.bind_socket) - .map_err(StartResult::error)?; - let listener = UnixListener::bind(&args.bind_socket) - .map_err(|error| StartResult::error(format!("bind socket: {error}")))?; - crate::listener::restrict_socket_permissions(&args.bind_socket).map_err(StartResult::error)?; - - // Arm procguard so the driver dies with the gateway instead of orphaning - // its per-sandbox VM launchers. - if let Err(error) = procguard::die_with_parent() { - tracing::warn!(%error, "procguard arm failed; gateway crashes may orphan this driver"); - } - - let log_level = args.log_level.clone(); - let launch = Launch::new( - LaunchInfo { - driver_name: "vm".to_string(), - driver_version: VERSION.to_string(), - features: Vec::new(), - }, - move |request| { - let settings = settings.clone(); - let log_level = log_level.clone(); - let tracing = tracing.clone(); - let gpu = (args.gpu, args.gpu_mem_mib, args.gpu_vcpus); - async move { apply_configure(settings, &log_level, gpu, &tracing, request).await } - }, - ); - let shutdown = launch.shutdown(); - let configured = launch.configured(); - let deferred = Deferred::new(configured.clone(), |driver: &VmDriver| { - ComputeDriverServer::new(driver.clone()) - }); - - info!(socket = %args.bind_socket.display(), "Starting vm compute driver"); - let result = tonic::transport::Server::builder() - .layer(openshell_otel::compute_driver_rpc_layer()) - .add_service(launch.into_server()) - .add_service(deferred) - .serve_with_incoming_shutdown( - crate::listener::AuthenticatedUnixIncoming::new(listener, Some(args.expected_peer_pid)), - openshell_driver_sdk::stop_when_released( - shutdown, - crate::listener::shutdown_signal(), - openshell_driver_sdk::EXTERNAL_STOP_GRACE, - ), - ) - .await; - let _ = std::fs::remove_file(&args.bind_socket); - if let Some(driver) = configured.get() { - driver.remove_socket_root(); - } - result.map_err(|error| StartResult::error(format!("serve: {error}"))) -} - -/// Build the driver from the operator's settings and the gateway's metadata. -async fn apply_configure( - settings: VmSettings, - log_level: &str, - gpu: (bool, u32, u8), - tracing: &openshell_otel::DeferredDriverTracing, - request: ConfigureRequest, -) -> Result { - let gateway = GatewayContext::try_from(&request.gateway.clone().unwrap_or_default())?; - if let Some(export) = openshell_driver_sdk::deferred_export_config( - request.telemetry.as_ref(), - gateway.gateway_name.as_deref(), - VERSION, - )? && let Err(error) = tracing.enable_export(export) - { - tracing::error!(%error, "OTLP exporting could not be started"); - } - let supervisor_otlp = openshell_driver_sdk::supervisor_otlp(request.telemetry.as_ref())?; - let admission = - openshell_driver_sdk::admission_from_json(&request.resource_admission_policy_json)?; - let config = driver_config( - settings, - &gateway, - request.network_trust.as_ref(), - supervisor_otlp, - admission, - log_level, - gpu, - )?; - VmDriver::new(config).await.map_err(Status::internal) -} - -/// The driver configuration for `settings` and the gateway's metadata. An -/// explicit `grpc_endpoint` wins over the gateway context. The gateway -/// supplies the admission policy. -fn driver_config( - settings: VmSettings, - gateway: &GatewayContext, - network_trust: Option<&openshell_driver_sdk::launch::NetworkTrust>, - supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, - admission: openshell_core::resource_admission::DriverAdmissionConfig, - log_level: &str, - (gpu_enabled, gpu_mem_mib, gpu_vcpus): (bool, u32, u8), -) -> Result { - let tls_enabled = gateway.tls_ca_path.is_some(); - let grpc_endpoint = if settings.grpc_endpoint.trim().is_empty() { - let port = gateway.gateway_port.ok_or_else(|| { - Status::invalid_argument( - "grpc_endpoint is required when using the vm compute driver and the gateway sent no port", - ) - })?; - let scheme = if tls_enabled { "https" } else { "http" }; - format!("{scheme}://127.0.0.1:{port}") - } else { - settings.grpc_endpoint - }; - let trust = network_trust.filter(|trust| !trust.artifact_path.is_empty()); - if openshell_driver_sdk::endpoint_uses_tls(&grpc_endpoint) && !tls_enabled { - return Err(Status::invalid_argument( - "grpc_endpoint uses https:// but the gateway supplied no CA path", - )); - } - Ok(VmDriverConfig { - allow_driver_config: admission.allow_driver_config, - resource_admission: admission.resource_admission, - grpc_endpoint, - supervisor_otlp, - supervisor_gateway_name: gateway.gateway_name.clone(), - state_dir: settings.state_dir, - launcher_bin: None, - default_image: settings.default_image, - bootstrap_image: settings.bootstrap_image, - bootstrap_extraction_max_bytes: settings.bootstrap_extraction_max_bytes, - log_level: log_level.to_string(), - krun_log_level: settings.krun_log_level, - vcpus: settings.vcpus, - mem_mib: settings.mem_mib, - overlay_disk_mib: settings.overlay_disk_mib, - guest_tls_ca: gateway.tls_ca_path.clone(), - guest_tls_cert: None, - guest_tls_key: None, - additional_ca_bundle: trust.map(|trust| PathBuf::from(&trust.artifact_path)), - additional_ca_digest: trust.map(|trust| trust.digest.clone()), - additional_ca_certificate_count: trust - .map(|trust| usize::try_from(trust.certificate_count)) - .transpose() - .map_err(|_| Status::invalid_argument("certificate_count is out of range"))?, - additional_ca_snapshot: None, - upstream_proxy: settings.upstream_proxy, - proxy_ca_bundle: settings.proxy_ca_bundle, - ipv6_egress: settings.ipv6_egress, - provider_spiffe_workload_api_tcp_endpoint: settings - .provider_spiffe_workload_api_tcp_endpoint, - provider_spiffe_allow_guest_tcp: settings.provider_spiffe_allow_guest_tcp, - gpu_enabled, - gpu_mem_mib, - gpu_vcpus, - sandbox_uid: settings.sandbox_uid, - sandbox_gid: settings.sandbox_gid, - rootfs_tar_staging_dir: settings.rootfs_tar_staging_dir, - rootfs_tar_max_bytes: settings.rootfs_tar_max_bytes, - enable_bind_mounts: settings.enable_bind_mounts, - }) -} - -#[cfg(test)] -mod tests { - use openshell_driver_sdk::launch::NetworkTrust; - use openshell_driver_vm::settings::settings_from_table; - - use super::*; - - fn config( - table: &str, - gateway: &GatewayContext, - trust: Option<&NetworkTrust>, - ) -> Result { - driver_config( - settings_from_table(table).unwrap(), - gateway, - trust, - openshell_core::sandbox_env::SupervisorOtlp::default(), - openshell_core::resource_admission::DriverAdmissionConfig::default(), - "info", - (false, 8192, 4), - ) - } - - #[test] - fn the_endpoint_defaults_to_the_gateway_loopback_address() { - let plain = GatewayContext { - gateway_port: Some(8080), - ..Default::default() - }; - assert_eq!( - config("", &plain, None).unwrap().grpc_endpoint, - "http://127.0.0.1:8080" - ); - let tls = GatewayContext { - gateway_port: Some(8080), - tls_ca_path: Some("/ca.pem".into()), - ..Default::default() - }; - let built = config("", &tls, None).unwrap(); - assert_eq!(built.grpc_endpoint, "https://127.0.0.1:8080"); - assert_eq!(built.guest_tls_ca, Some("/ca.pem".into())); - } - - #[test] - fn an_explicit_endpoint_wins_but_the_ca_comes_from_the_gateway() { - let gateway = GatewayContext { - gateway_port: Some(8080), - tls_ca_path: Some("/gateway-ca.pem".into()), - gateway_name: Some("gw".to_string()), - bind_address: None, - }; - let built = config("grpc_endpoint = \"https://host.test:9\"", &gateway, None).unwrap(); - assert_eq!(built.grpc_endpoint, "https://host.test:9"); - assert_eq!(built.guest_tls_ca, Some("/gateway-ca.pem".into())); - assert_eq!(built.supervisor_gateway_name.as_deref(), Some("gw")); - } - - #[test] - fn the_admission_policy_comes_from_configure() { - let gateway = GatewayContext { - gateway_port: Some(1), - ..Default::default() - }; - let policy = openshell_core::resource_admission::DriverAdmissionConfig { - allow_driver_config: true, - ..Default::default() - }; - let built = driver_config( - settings_from_table("").unwrap(), - &gateway, - None, - openshell_core::sandbox_env::SupervisorOtlp::default(), - policy, - "info", - (false, 8192, 4), - ) - .unwrap(); - assert!(built.allow_driver_config); - assert!(!config("", &gateway, None).unwrap().allow_driver_config); - } - - #[test] - fn an_https_endpoint_needs_the_gateway_ca() { - let gateway = GatewayContext { - gateway_port: Some(8080), - ..Default::default() - }; - let status = config("grpc_endpoint = \"https://host.test:9\"", &gateway, None).unwrap_err(); - assert_eq!(status.code(), tonic::Code::InvalidArgument); - } - - #[test] - fn a_missing_endpoint_and_port_is_invalid() { - let status = config("", &GatewayContext::default(), None).unwrap_err(); - assert_eq!(status.code(), tonic::Code::InvalidArgument); - } - - #[test] - fn network_trust_reaches_the_driver_config() { - let gateway = GatewayContext { - gateway_port: Some(1), - ..Default::default() - }; - let trust = NetworkTrust { - artifact_path: "/var/lib/ca.crt".to_string(), - digest: "sha256:abc".to_string(), - certificate_count: 2, - }; - let built = config("", &gateway, Some(&trust)).unwrap(); - assert_eq!(built.additional_ca_bundle, Some("/var/lib/ca.crt".into())); - assert_eq!(built.additional_ca_digest.as_deref(), Some("sha256:abc")); - assert_eq!(built.additional_ca_certificate_count, Some(2)); - assert!( - config("", &gateway, None) - .unwrap() - .additional_ca_bundle - .is_none() - ); - } -} diff --git a/crates/openshell-driver-vm/src/settings.rs b/crates/openshell-driver-vm/src/settings.rs deleted file mode 100644 index 580884ce7c..0000000000 --- a/crates/openshell-driver-vm/src/settings.rs +++ /dev/null @@ -1,565 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! The operator's `[openshell.drivers.vm]` table. -//! -//! [`settings_from_table`] is the only place the table is parsed and -//! validated. `serve` and `preflight` both call it, so they agree on whether a -//! table is valid. It has no side effects and needs neither the gateway -//! context nor the backend. - -use std::path::PathBuf; - -use openshell_core::UpstreamProxyConfig; - -/// Why a driver table was rejected. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ConfigError(pub String); - -impl std::fmt::Display for ConfigError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.0) - } -} - -impl std::error::Error for ConfigError {} - -/// Operator-written settings for the VM driver. -/// -/// `driver_dir` is gateway-owned: the gateway reads and removes it before it -/// forwards the table, so it is not accepted here. -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(default, deny_unknown_fields)] -#[allow(clippy::struct_excessive_bools)] -pub struct VmSettings { - /// Working directory for VM driver sandbox state. - pub state_dir: PathBuf, - /// Default sandbox image the driver should use when a request omits one. - pub default_image: String, - /// Optional override of the gateway gRPC endpoint the sandbox guest - /// connects back to, for custom network or NAT setups. Unset, it defaults - /// from the gateway context. The gateway supplies the gateway port and CA. - pub grpc_endpoint: String, - /// Bootstrap image used to boot and prepare VM sandbox target images. - pub bootstrap_image: String, - /// Per-image byte limit for host extraction of registry bootstrap layers. - pub bootstrap_extraction_max_bytes: Option, - /// libkrun log level used by the VM driver helper. - pub krun_log_level: u32, - /// Default vCPU count for VM sandboxes. - pub vcpus: u8, - /// Default memory allocation for VM sandboxes, in MiB. - pub mem_mib: u32, - /// Writable overlay disk size for each VM sandbox, in MiB. - pub overlay_disk_mib: u64, - /// Optional UID override for the VM guest sandbox account. - pub sandbox_uid: Option, - /// Optional GID override for the VM guest sandbox account. - pub sandbox_gid: Option, - /// Directory shared with the gateway for request-scoped rootfs tar staging. - pub rootfs_tar_staging_dir: Option, - /// Maximum accepted rootfs tar size, in bytes, before and after decompression. - pub rootfs_tar_max_bytes: Option, - /// Corporate forward-proxy settings. Flattening preserves the shared - /// local-driver TOML field names. - #[serde(flatten)] - pub upstream_proxy: UpstreamProxyConfig, - /// PEM CA bundle trusted for the corporate proxy and for server - /// certificates re-signed by a TLS-intercepting proxy. - pub proxy_ca_bundle: Option, - /// Policy DNS IPv6 egress mode and NAT64 prefixes for the host-side - /// supervisors. - #[serde(flatten)] - pub ipv6_egress: openshell_core::SupervisorIpv6EgressConfig, - /// Explicit guest-reachable SPIFFE Workload API TCP listener. VM guests - /// cannot receive a host UNIX socket, so this requires acknowledgement. - pub provider_spiffe_workload_api_tcp_endpoint: Option, - pub provider_spiffe_allow_guest_tcp: bool, - /// Allow bind-mounting host directories into VM sandboxes. - pub enable_bind_mounts: bool, -} - -impl VmSettings { - /// Default working directory for VM driver state. - #[must_use] - pub fn default_state_dir() -> PathBuf { - openshell_core::paths::openshell_state_dir().map_or_else( - |_| PathBuf::from("target/openshell-vm-driver"), - |dir| dir.join("vm-driver"), - ) - } - - /// Checks that need neither the gateway context nor the backend. - fn validate(&self) -> Result<(), ConfigError> { - self.ipv6_egress.validate().map_err(ConfigError)?; - if !self.grpc_endpoint.trim().is_empty() { - openshell_driver_sdk::validate_grpc_endpoint(&self.grpc_endpoint) - .map_err(ConfigError)?; - } - if self.bootstrap_image.trim().is_empty() && self.default_image.trim().is_empty() { - return Err(ConfigError( - "bootstrap_image or default_image is required when using the vm compute driver; sandbox images cannot be used as VM bootstrap images".to_string(), - )); - } - let range = openshell_policy::MIN_SANDBOX_UID..=openshell_policy::MAX_SANDBOX_UID; - for (field, value) in [ - ("sandbox_uid", self.sandbox_uid), - ("sandbox_gid", self.sandbox_gid), - ] { - if let Some(value) = value - && !range.contains(&value) - { - return Err(ConfigError(format!( - "{field} {value} is outside the allowed range [{}, {}]", - openshell_policy::MIN_SANDBOX_UID, - openshell_policy::MAX_SANDBOX_UID - ))); - } - } - if self - .rootfs_tar_staging_dir - .as_ref() - .is_some_and(|path| path.as_os_str().is_empty()) - { - return Err(ConfigError( - "rootfs_tar_staging_dir must not be empty when set".to_string(), - )); - } - if self.rootfs_tar_max_bytes == Some(0) { - return Err(ConfigError( - "rootfs_tar_max_bytes must be greater than zero when set".to_string(), - )); - } - self.upstream_proxy.validate().map_err(ConfigError)?; - if let Some(path) = self.proxy_ca_bundle.as_ref() { - if path.as_os_str().is_empty() { - return Err(ConfigError( - "proxy_ca_bundle must not be empty when set".to_string(), - )); - } - if self.upstream_proxy.https_proxy.is_none() { - return Err(ConfigError( - "proxy_ca_bundle is set but no https_proxy is configured".to_string(), - )); - } - } - if let Some(endpoint) = self.provider_spiffe_workload_api_tcp_endpoint.as_deref() { - openshell_core::driver_utils::validate_guest_spiffe_tcp_endpoint( - endpoint, - self.provider_spiffe_allow_guest_tcp, - ) - .map_err(ConfigError)?; - } else if self.provider_spiffe_allow_guest_tcp { - return Err(ConfigError( - "provider_spiffe_allow_guest_tcp is set but no provider_spiffe_workload_api_tcp_endpoint is configured".to_string(), - )); - } - Ok(()) - } -} - -impl Default for VmSettings { - fn default() -> Self { - Self { - state_dir: Self::default_state_dir(), - default_image: openshell_core::image::default_sandbox_image(), - grpc_endpoint: String::new(), - bootstrap_image: String::new(), - bootstrap_extraction_max_bytes: None, - krun_log_level: 1, - vcpus: 2, - mem_mib: 2048, - overlay_disk_mib: 4096, - sandbox_uid: None, - sandbox_gid: None, - rootfs_tar_staging_dir: None, - rootfs_tar_max_bytes: None, - upstream_proxy: UpstreamProxyConfig::default(), - proxy_ca_bundle: None, - ipv6_egress: openshell_core::SupervisorIpv6EgressConfig::default(), - provider_spiffe_workload_api_tcp_endpoint: None, - provider_spiffe_allow_guest_tcp: false, - enable_bind_mounts: false, - } - } -} - -/// Parse and validate the driver table. An empty table is valid and selects -/// the defaults. -pub fn settings_from_table(table: &str) -> Result { - settings_with_environment(table, &|_| None) -} - -/// [`settings_from_table`] with the standalone driver's environment fallbacks. -/// -/// The gateway used to pass only the settings an operator wrote, so a setting -/// left out of the table fell back to the driver's own environment variable. -/// Existing installs rely on that, so a setting the table leaves unset still -/// reads its variable. The table wins when both are set. -pub fn settings_with_environment( - table: &str, - env: &dyn Fn(&str) -> Option, -) -> Result { - let mut settings: VmSettings = toml::from_str(table) - .map_err(|error| ConfigError(format!("invalid vm driver table: {error}")))?; - settings.apply_environment(env)?; - if settings.state_dir.as_os_str().is_empty() { - settings.state_dir = VmSettings::default_state_dir(); - } - settings.validate()?; - Ok(settings) -} - -impl VmSettings { - /// Fill settings the table left unset from their environment variables. - /// - /// For `enable_bind_mounts`, `provider_spiffe_allow_guest_tcp` and - /// `nat64_prefixes`, a `false` or an empty list in the table cannot be told - /// from an omitted key, so the environment can still enable them, as it - /// could when the gateway passed flags. #6002 tracks one precedence rule - /// for these settings. - fn apply_environment( - &mut self, - env: &dyn Fn(&str) -> Option, - ) -> Result<(), ConfigError> { - fn parse(name: &str, value: &str) -> Result - where - T::Err: std::fmt::Display, - { - value - .trim() - .parse() - .map_err(|error| ConfigError(format!("invalid {name}={value:?}: {error}"))) - } - let get = |name: &str| env(name).filter(|value| !value.trim().is_empty()); - - if self.bootstrap_image.trim().is_empty() - && let Some(value) = get("OPENSHELL_VM_BOOTSTRAP_IMAGE") - { - self.bootstrap_image = value; - } - if self.bootstrap_extraction_max_bytes.is_none() - && let Some(value) = get("OPENSHELL_VM_BOOTSTRAP_EXTRACTION_MAX_BYTES") - { - self.bootstrap_extraction_max_bytes = Some(parse( - "OPENSHELL_VM_BOOTSTRAP_EXTRACTION_MAX_BYTES", - &value, - )?); - } - if self.sandbox_uid.is_none() - && let Some(value) = get("OPENSHELL_VM_SANDBOX_UID") - { - self.sandbox_uid = Some(parse("OPENSHELL_VM_SANDBOX_UID", &value)?); - } - if self.sandbox_gid.is_none() - && let Some(value) = get("OPENSHELL_VM_SANDBOX_GID") - { - self.sandbox_gid = Some(parse("OPENSHELL_VM_SANDBOX_GID", &value)?); - } - if self.rootfs_tar_staging_dir.is_none() - && let Some(value) = get("OPENSHELL_VM_ROOTFS_TAR_STAGING_DIR") - { - self.rootfs_tar_staging_dir = Some(value.into()); - } - if self.rootfs_tar_max_bytes.is_none() - && let Some(value) = get("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES") - { - self.rootfs_tar_max_bytes = Some(parse("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES", &value)?); - } - - let proxy = &mut self.upstream_proxy; - if proxy.https_proxy.is_none() { - proxy.https_proxy = get("OPENSHELL_VM_UPSTREAM_PROXY"); - } - if proxy.no_proxy.is_none() { - proxy.no_proxy = get("OPENSHELL_VM_UPSTREAM_NO_PROXY"); - } - if proxy.proxy_auth_file.is_none() { - proxy.proxy_auth_file = get("OPENSHELL_VM_UPSTREAM_PROXY_AUTH_FILE").map(Into::into); - } - // These two acknowledge a proxy setting, and the table validation - // rejects them when that setting is absent. A `false` in the - // environment has always meant "not set", so only `true` sets them. - if proxy.proxy_auth_allow_insecure.is_none() - && let Some(value) = get("OPENSHELL_VM_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE") - && parse::("OPENSHELL_VM_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE", &value)? - { - proxy.proxy_auth_allow_insecure = Some(true); - } - if proxy.proxy_connect_by_hostname.is_none() - && let Some(value) = get("OPENSHELL_VM_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME") - && parse::("OPENSHELL_VM_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME", &value)? - { - proxy.proxy_connect_by_hostname = Some(true); - } - if self.proxy_ca_bundle.is_none() { - self.proxy_ca_bundle = get("OPENSHELL_VM_UPSTREAM_PROXY_CA_BUNDLE").map(Into::into); - } - - if self.provider_spiffe_workload_api_tcp_endpoint.is_none() { - self.provider_spiffe_workload_api_tcp_endpoint = - get("OPENSHELL_PROVIDER_SPIFFE_WORKLOAD_API_TCP_ENDPOINT"); - } - if !self.provider_spiffe_allow_guest_tcp - && let Some(value) = get("OPENSHELL_PROVIDER_SPIFFE_ALLOW_GUEST_TCP") - { - self.provider_spiffe_allow_guest_tcp = - parse("OPENSHELL_PROVIDER_SPIFFE_ALLOW_GUEST_TCP", &value)?; - } - if !self.enable_bind_mounts - && let Some(value) = get("OPENSHELL_VM_ENABLE_BIND_MOUNTS") - { - self.enable_bind_mounts = parse("OPENSHELL_VM_ENABLE_BIND_MOUNTS", &value)?; - } - - if self.ipv6_egress.policy_dns_ipv6_egress.is_none() - && let Some(value) = get("OPENSHELL_VM_POLICY_DNS_IPV6_EGRESS") - { - self.ipv6_egress.policy_dns_ipv6_egress = - Some(value.trim().parse().map_err(|error| { - ConfigError(format!("OPENSHELL_VM_POLICY_DNS_IPV6_EGRESS: {error}")) - })?); - } - if self.ipv6_egress.nat64_prefixes.is_empty() - && let Some(value) = get("OPENSHELL_VM_NAT64_PREFIXES") - { - self.ipv6_egress.nat64_prefixes = value - .split(',') - .map(|prefix| prefix.trim().to_string()) - .filter(|prefix| !prefix.is_empty()) - .collect(); - } - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn an_empty_table_selects_the_defaults() { - let settings = settings_from_table("").unwrap(); - assert_eq!(settings.vcpus, 2); - assert_eq!(settings.mem_mib, 2048); - assert!(settings.grpc_endpoint.is_empty()); - } - - #[test] - fn existing_operator_keys_are_accepted() { - let settings = settings_from_table( - r#" - state_dir = "/var/lib/openshell/vm" - default_image = "example.test/sandbox:1" - bootstrap_image = "example.test/bootstrap:1" - grpc_endpoint = "https://gateway.test:8080" - krun_log_level = 3 - vcpus = 4 - mem_mib = 4096 - overlay_disk_mib = 8192 - sandbox_uid = 10001 - sandbox_gid = 10001 - https_proxy = "http://proxy.test:3128" - proxy_ca_bundle = "/etc/openshell/proxy-ca.pem" - enable_bind_mounts = true - "#, - ) - .unwrap(); - assert_eq!(settings.vcpus, 4); - assert_eq!(settings.sandbox_uid, Some(10001)); - assert_eq!( - settings.upstream_proxy.https_proxy.as_deref(), - Some("http://proxy.test:3128") - ); - } - - #[test] - fn ipv6_egress_settings_are_accepted_and_validated() { - let settings = settings_from_table( - "policy_dns_ipv6_egress = \"disabled\"\nnat64_prefixes = [\"2001:db8:64::/96\"]", - ) - .unwrap(); - assert_eq!(settings.ipv6_egress.nat64_prefixes, ["2001:db8:64::/96"]); - assert!(settings_from_table("nat64_prefixes = [\"not-a-prefix\"]").is_err()); - } - - fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { - move |name| { - pairs - .iter() - .find(|(key, _)| *key == name) - .map(|(_, value)| (*value).to_string()) - } - } - - #[test] - fn unset_settings_fall_back_to_the_environment() { - let settings = settings_with_environment( - "bootstrap_image = \"\"", - &env(&[ - ("OPENSHELL_VM_UPSTREAM_PROXY", "http://proxy.test:3128"), - ("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES", "1048576"), - ("OPENSHELL_VM_BOOTSTRAP_EXTRACTION_MAX_BYTES", "33554432"), - ("OPENSHELL_VM_ENABLE_BIND_MOUNTS", "true"), - ("OPENSHELL_VM_BOOTSTRAP_IMAGE", "example.test/bootstrap:1"), - ( - "OPENSHELL_VM_NAT64_PREFIXES", - "2001:db8:64::/96, 64:ff9b::/96", - ), - ]), - ) - .unwrap(); - assert_eq!( - settings.upstream_proxy.https_proxy.as_deref(), - Some("http://proxy.test:3128") - ); - assert_eq!(settings.rootfs_tar_max_bytes, Some(1_048_576)); - assert_eq!( - settings.bootstrap_extraction_max_bytes, - std::num::NonZeroU64::new(33_554_432) - ); - assert!(settings.enable_bind_mounts); - assert_eq!(settings.bootstrap_image, "example.test/bootstrap:1"); - assert_eq!( - settings.ipv6_egress.nat64_prefixes, - ["2001:db8:64::/96", "64:ff9b::/96"] - ); - } - - #[test] - fn an_environment_false_leaves_the_proxy_acknowledgements_unset() { - let settings = settings_with_environment( - "", - &env(&[ - ("OPENSHELL_VM_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE", "false"), - ("OPENSHELL_VM_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME", "false"), - ]), - ) - .unwrap(); - assert_eq!(settings.upstream_proxy.proxy_auth_allow_insecure, None); - assert_eq!(settings.upstream_proxy.proxy_connect_by_hostname, None); - } - - #[test] - fn an_environment_true_sets_the_proxy_acknowledgements() { - let settings = settings_with_environment( - "https_proxy = \"http://proxy.test:3128\"\nproxy_auth_file = \"/etc/proxy-auth\"", - &env(&[ - ("OPENSHELL_VM_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE", "true"), - ("OPENSHELL_VM_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME", "true"), - ]), - ) - .unwrap(); - assert_eq!( - settings.upstream_proxy.proxy_auth_allow_insecure, - Some(true) - ); - assert_eq!( - settings.upstream_proxy.proxy_connect_by_hostname, - Some(true) - ); - } - - #[test] - fn an_explicit_table_false_is_kept_and_still_needs_its_setting() { - // The table's value wins over the environment, and `false` with no - // auth file is rejected, as it was before the driver read the table. - let error = settings_with_environment( - "proxy_auth_allow_insecure = false", - &env(&[("OPENSHELL_VM_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE", "true")]), - ) - .unwrap_err(); - assert!( - error.to_string().contains("proxy_auth_allow_insecure"), - "{error}" - ); - } - - #[test] - fn the_table_wins_over_the_environment() { - let settings = settings_with_environment( - "https_proxy = \"http://table.test:1\"", - &env(&[("OPENSHELL_VM_UPSTREAM_PROXY", "http://env.test:2")]), - ) - .unwrap(); - assert_eq!( - settings.upstream_proxy.https_proxy.as_deref(), - Some("http://table.test:1") - ); - } - - #[test] - fn a_malformed_environment_value_is_invalid_config() { - let error = - settings_with_environment("", &env(&[("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES", "lots")])) - .unwrap_err(); - assert!( - error.0.contains("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES"), - "{error}" - ); - } - - #[test] - fn unknown_keys_are_rejected() { - let error = settings_from_table("vcpu = 4").unwrap_err(); - assert!(error.0.contains("vcpu"), "{error}"); - } - - #[test] - fn gateway_supplied_values_are_not_driver_keys() { - for key in [ - "guest_tls_ca = \"/ca.pem\"", - "gateway_port = 8080", - "allow_driver_config = true", - "resource_admission = {}", - ] { - assert!(settings_from_table(key).is_err(), "accepted: {key}"); - } - } - - #[test] - fn grpc_endpoint_is_checked_for_syntax_and_scheme() { - settings_from_table("grpc_endpoint = \"https://gw.test:8443\"").unwrap(); - for bad in ["ftp://gw.test:1", "gw.test:8080", "http://"] { - assert!( - settings_from_table(&format!("grpc_endpoint = \"{bad}\"")).is_err(), - "accepted: {bad}" - ); - } - } - - #[test] - fn the_gateway_owned_driver_dir_is_not_a_driver_key() { - assert!(settings_from_table(r#"driver_dir = "/opt/drivers""#).is_err()); - } - - #[test] - fn invalid_values_are_rejected() { - for table in [ - "sandbox_uid = 0", - "rootfs_tar_max_bytes = 0", - "bootstrap_extraction_max_bytes = 0", - "rootfs_tar_staging_dir = \"\"", - "proxy_ca_bundle = \"/ca.pem\"", - "provider_spiffe_allow_guest_tcp = true", - "default_image = \"\"\nbootstrap_image = \"\"", - ] { - assert!(settings_from_table(table).is_err(), "accepted: {table}"); - } - } - - #[test] - fn a_proxy_exclusion_without_a_proxy_names_the_keys() { - let error = settings_from_table("no_proxy = \"10.0.0.0/8\"").unwrap_err(); - assert!(error.0.contains("no_proxy"), "{error}"); - assert!(error.0.contains("https_proxy"), "{error}"); - } - - #[test] - fn an_empty_state_dir_selects_the_default() { - assert_eq!( - settings_from_table("state_dir = \"\"").unwrap().state_dir, - VmSettings::default_state_dir() - ); - } -} diff --git a/crates/openshell-driver-vm/tests/image_preparation.rs b/crates/openshell-driver-vm/tests/image_preparation.rs deleted file mode 100644 index ffa0992c9e..0000000000 --- a/crates/openshell-driver-vm/tests/image_preparation.rs +++ /dev/null @@ -1,383 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "compute-driver")] -#![allow(unsafe_code)] - -use std::fs::{self, File}; -use std::os::fd::AsRawFd; -use std::os::unix::fs::PermissionsExt; -use std::os::unix::process::CommandExt; -use std::process::{Command, Stdio}; - -use openshell_driver_vm::VmDriverConfig; - -/// Exercise the actual worker entry point and a real sparse-file copy without -/// downloading an image, running a VM, or requiring host filesystem utilities. -#[test] -fn worker_publishes_complete_overlay_and_reports_resolved_owner() { - worker_overlay_case(false); -} - -/// Retrying an interrupted first start must never turn an incomplete copy -/// into persisted overlay state. The next retry must still be able to start. -#[test] -fn interrupted_missing_overlay_retry_does_not_publish_partial_state() { - worker_overlay_case(true); -} - -fn worker_overlay_case(interrupt_retry: bool) { - let root = tempfile::tempdir().unwrap(); - let cache = root.path().join("images"); - let attempts = cache.join("preparations"); - let name = "attempt-00000000000000000000000000000001"; - let attempt = attempts.join(name); - fs::create_dir_all(&attempt).unwrap(); - let lease_path = attempts.join(format!("{name}.lease")); - fs::write(&lease_path, b"openshell-image-preparation-v1\n").unwrap(); - let lease = File::open(&lease_path).unwrap(); - let fd = lease.as_raw_fd(); - // SAFETY: this descriptor belongs to the live fixture file. - assert_eq!(unsafe { libc::flock(fd, libc::LOCK_EX) }, 0); - - let size = 1024 * 1024; - let template = cache.join("overlay-templates/sandbox-overlay-ext4-v1/1048576.ext4"); - fs::create_dir_all(template.parent().unwrap()).unwrap(); - let mut expected = vec![0_u8; size]; - expected[..13].copy_from_slice(b"template-data"); - fs::write(&template, &expected).unwrap(); - let sandbox = root.path().join("sandboxes/worker-test"); - fs::create_dir_all(&sandbox).unwrap(); - if interrupt_retry { - // A cancelled Fresh attempt can persist the owner before publishing - // its first overlay. Start retries this state with PreserveExisting. - fs::write( - sandbox.join("sandbox-owner-state"), - b"sandbox-owner-v2:1000:1000\n", - ) - .unwrap(); - } - let source = cache.join("test-image/rootfs.ext4"); - fs::create_dir_all(source.parent().unwrap()).unwrap(); - fs::write(&source, b"identity comes from driver configuration").unwrap(); - let config = VmDriverConfig { - state_dir: root.path().to_path_buf(), - sandbox_uid: Some(1000), - sandbox_gid: Some(1000), - overlay_disk_mib: 1, - ..VmDriverConfig::default() - }; - let request = attempt.join("request.json"); - fs::write( - &request, - serde_json::to_vec(&serde_json::json!({ - "config": config, - "sandbox_id": "worker-test", - "image_ref": "", - "rootfs_tar": null, - "bootstrap_only": false, - "overlay": { - "source_disk": source, - "preparation": if interrupt_retry { "PreserveExisting" } else { "Fresh" }, - }, - "lease_fd": fd, - "parent_pid": std::process::id(), - })) - .unwrap(), - ) - .unwrap(); - let mut command = Command::new(env!("CARGO_BIN_EXE_openshell-driver-vm")); - command - .arg("--internal-prepare-image") - .arg(&request) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .process_group(0); - // SAFETY: only fcntl runs between fork and exec, and the fixture keeps its - // descriptor alive until the worker has exited. - unsafe { - command.pre_exec(move || { - if libc::fcntl(fd, libc::F_SETFD, 0) == -1 { - return Err(std::io::Error::last_os_error()); - } - Ok(()) - }); - } - if interrupt_retry { - let tools = root.path().join("tools"); - fs::create_dir(&tools).unwrap(); - let copy_ready = root.path().join("copy-ready"); - let cp = tools.join("cp"); - // Control only the external copy command. The actual worker selects - // the destination and executes its production preservation checks. - fs::write( - &cp, - "#!/bin/sh\nfor argument in \"$@\"; do destination=\"$argument\"; done\nprintf partial > \"$destination\"\nprintf '%s' \"$destination\" > \"$COPY_READY\"\nsleep 300\n", - ) - .unwrap(); - fs::set_permissions(&cp, fs::Permissions::from_mode(0o700)).unwrap(); - command - .env("PATH", format!("{}:/usr/bin:/bin", tools.display())) - .env("COPY_READY", ©_ready); - let mut interrupted = command.spawn().unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while !copy_ready.exists() && std::time::Instant::now() < deadline { - if interrupted.try_wait().unwrap().is_some() { - break; - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - // Kill and reap even if readiness fails, so failed tests do not leave - // a blocked helper or worker behind. - if interrupted.try_wait().unwrap().is_none() { - let pid = i32::try_from(interrupted.id()).unwrap(); - let _ = nix::sys::signal::killpg( - nix::unistd::Pid::from_raw(pid), - nix::sys::signal::Signal::SIGKILL, - ); - } - interrupted.wait().unwrap(); - assert!(copy_ready.exists(), "worker must reach the controlled copy"); - assert!( - !sandbox.join("overlay.ext4").exists(), - "interrupted retry must leave no partial persisted overlay" - ); - let destination = fs::read_to_string(©_ready).unwrap(); - assert!(std::path::Path::new(&destination).starts_with(&attempt)); - // Retry using the real copy utility. The incomplete attempt image - // must not prevent publishing the complete overlay. - command - .env("PATH", "/usr/bin:/bin") - .env_remove("COPY_READY"); - } - let mut child = command.spawn().unwrap(); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while child.try_wait().unwrap().is_none() { - if std::time::Instant::now() >= deadline { - let pid = i32::try_from(child.id()).unwrap(); - let _ = nix::sys::signal::killpg( - nix::unistd::Pid::from_raw(pid), - nix::sys::signal::Signal::SIGKILL, - ); - let _ = child.wait(); - panic!("image preparation worker timed out"); - } - std::thread::sleep(std::time::Duration::from_millis(10)); - } - let output = child.wait_with_output().unwrap(); - assert!( - output.status.success(), - "{}", - String::from_utf8_lossy(&output.stderr) - ); - let messages = String::from_utf8(output.stdout).unwrap(); - let completion = messages - .lines() - .map(|line| { - serde_json::from_str::(line) - .expect("worker stdout must contain only protocol messages") - }) - .find_map(|message| message.get("Complete").cloned()) - .expect("worker completion"); - assert_eq!( - completion, - serde_json::json!({"Ok": {"Overlay": {"uid": 1000, "gid": 1000}}}) - ); - assert_eq!(fs::read(sandbox.join("overlay.ext4")).unwrap(), expected); - assert_eq!( - fs::read(&template).unwrap(), - expected, - "the shared template is immutable" - ); - assert_eq!( - fs::read_to_string(sandbox.join("sandbox-owner-state")).unwrap(), - "sandbox-owner-v2:1000:1000\n" - ); -} - -struct OwnedPreparationChild { - child: std::process::Child, - reaped: bool, - _lease: File, -} - -impl OwnedPreparationChild { - fn exited(&self) -> std::io::Result { - // SAFETY: initialized output storage; WNOWAIT retains our child's PID. - let mut status: libc::siginfo_t = unsafe { std::mem::zeroed() }; - if unsafe { - libc::waitid( - libc::P_PID, - self.child.id(), - &raw mut status, - libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, - ) - } != 0 - { - return Err(std::io::Error::last_os_error()); - } - Ok(matches!( - status.si_code, - libc::CLD_EXITED | libc::CLD_KILLED | libc::CLD_DUMPED - )) - } - - fn stop_and_reap(&mut self) -> std::io::Result { - let pid = i32::try_from(self.child.id()).map_err(std::io::Error::other)?; - let _ = nix::sys::signal::killpg( - nix::unistd::Pid::from_raw(pid), - nix::sys::signal::Signal::SIGKILL, - ); - let status = self.child.wait()?; - self.reaped = true; - Ok(status) - } -} - -impl Drop for OwnedPreparationChild { - fn drop(&mut self) { - if !self.reaped { - let _ = self.stop_and_reap(); - } - } -} - -fn spawn_overlay_fixture( - root: &std::path::Path, - id: &str, - number: u128, - controlled_copy: bool, -) -> OwnedPreparationChild { - let attempts = root.join("images/preparations"); - let name = format!("attempt-{number:032x}"); - let attempt = attempts.join(&name); - fs::create_dir_all(&attempt).unwrap(); - let lease_path = attempts.join(format!("{name}.lease")); - fs::write(&lease_path, b"openshell-image-preparation-v1\n").unwrap(); - let lease = File::open(&lease_path).unwrap(); - let fd = lease.as_raw_fd(); - // SAFETY: lease owns fd and stays alive in the returned process guard. - assert_eq!(unsafe { libc::flock(fd, libc::LOCK_EX) }, 0); - fs::create_dir_all(root.join("sandboxes").join(id)).unwrap(); - let config = VmDriverConfig { - state_dir: root.to_path_buf(), - sandbox_uid: Some(1000), - sandbox_gid: Some(1000), - overlay_disk_mib: 1, - ..VmDriverConfig::default() - }; - let request = attempt.join("request.json"); - fs::write( - &request, - serde_json::to_vec(&serde_json::json!({ - "config": config, "sandbox_id": id, "image_ref": "", "rootfs_tar": null, - "bootstrap_only": false, - "overlay": { "source_disk": root.join("images/test-image/rootfs.ext4"), - "preparation": "Fresh", "requested_identity": null }, - "lease_fd": fd, "parent_pid": std::process::id(), - })) - .unwrap(), - ) - .unwrap(); - let mut command = Command::new(env!("CARGO_BIN_EXE_openshell-driver-vm")); - command - .arg("--internal-prepare-image") - .arg(request) - .stdin(Stdio::null()) - .stdout(File::create(root.join(format!("{id}.stdout"))).unwrap()) - .stderr(File::create(root.join(format!("{id}.stderr"))).unwrap()) - .process_group(0); - if controlled_copy { - command - .env( - "PATH", - format!("{}:/usr/bin:/bin", root.join("tools").display()), - ) - .env("COPY_READY", root.join("copy-ready")); - } else { - command.env("PATH", "/usr/bin:/bin"); - } - // SAFETY: only fcntl runs between fork and exec; the guard keeps fd alive. - unsafe { - command.pre_exec(move || { - if libc::fcntl(fd, libc::F_SETFD, 0) == -1 { - return Err(std::io::Error::last_os_error()); - } - Ok(()) - }); - } - OwnedPreparationChild { - child: command.spawn().unwrap(), - reaped: false, - _lease: lease, - } -} - -#[test] -fn independent_overlay_finishes_while_another_copy_is_blocked() { - let root = tempfile::tempdir().unwrap(); - let template = root - .path() - .join("images/overlay-templates/sandbox-overlay-ext4-v1/1048576.ext4"); - fs::create_dir_all(template.parent().unwrap()).unwrap(); - let mut expected = vec![0_u8; 1024 * 1024]; - expected[..13].copy_from_slice(b"template-data"); - fs::write(&template, &expected).unwrap(); - let source = root.path().join("images/test-image/rootfs.ext4"); - fs::create_dir_all(source.parent().unwrap()).unwrap(); - fs::write(&source, b"configured owner fixture").unwrap(); - let tools = root.path().join("tools"); - fs::create_dir(&tools).unwrap(); - fs::write(tools.join("cp"), - "#!/bin/sh\nfor value in \"$@\"; do destination=\"$value\"; done\nprintf partial > \"$destination\"\n: > \"$COPY_READY\"\nexec sleep 300\n" - ).unwrap(); - fs::set_permissions(tools.join("cp"), fs::Permissions::from_mode(0o700)).unwrap(); - let mut slow = spawn_overlay_fixture(root.path(), "slow-a", 1, true); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while !root.path().join("copy-ready").exists() { - assert!( - !slow.exited().unwrap(), - "slow worker exited before controlled copy" - ); - assert!( - std::time::Instant::now() < deadline, - "controlled copy readiness timed out" - ); - std::thread::sleep(std::time::Duration::from_millis(10)); - } - let mut warm = spawn_overlay_fixture(root.path(), "warm-b", 2, false); - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); - while !warm.exited().unwrap() { - assert!( - std::time::Instant::now() < deadline, - "warm overlay waited for unrelated copy" - ); - std::thread::sleep(std::time::Duration::from_millis(10)); - } - let status = warm.stop_and_reap().unwrap(); - assert!( - status.success(), - "{}", - fs::read_to_string(root.path().join("warm-b.stderr")).unwrap() - ); - assert!( - !slow.exited().unwrap(), - "slow copy must remain blocked during the proof" - ); - assert_eq!( - fs::read(root.path().join("sandboxes/warm-b/overlay.ext4")).unwrap(), - expected - ); - assert_eq!(fs::read(&template).unwrap(), expected); - assert!(!root.path().join("sandboxes/slow-a/overlay.ext4").exists()); - let output = fs::read_to_string(root.path().join("warm-b.stdout")).unwrap(); - let completed = output.lines().any(|line| { - serde_json::from_str::(line) - .unwrap() - .get("Complete") - == Some(&serde_json::json!({"Ok": {"Overlay": {"uid": 1000, "gid": 1000}}})) - }); - assert!(completed, "actual worker did not report overlay completion"); - slow.stop_and_reap().unwrap(); -} diff --git a/crates/openshell-driver-vm/tests/serve_configure.rs b/crates/openshell-driver-vm/tests/serve_configure.rs deleted file mode 100644 index 268396f1cc..0000000000 --- a/crates/openshell-driver-vm/tests/serve_configure.rs +++ /dev/null @@ -1,266 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Runs the real `openshell-driver-vm` binary through `serve` and `preflight`. - -#![cfg(unix)] - -use std::io::Write as _; -use std::path::Path; -use std::process::{Child, Command, Output, Stdio}; -use std::time::{Duration, Instant}; - -use hyper_util::rt::TokioIo; -use openshell_core::proto::compute::v1::GetCapabilitiesRequest; -use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; -use openshell_driver_sdk::launch::proto::driver_launch_client::DriverLaunchClient; -use openshell_driver_sdk::launch::{ - ConfigureRequest, GetLaunchInfoRequest, PROTOCOL_VERSION, ShutdownRequest, -}; -use tonic::Code; -use tonic::transport::{Channel, Endpoint}; - -const BIN: &str = env!("CARGO_BIN_EXE_openshell-driver-vm"); - -fn driver(args: &[&str], table: &str) -> Command { - let mut command = Command::new(BIN); - command - .args(args) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()); - let _ = table; - command -} - -fn run_with_table(args: &[&str], table: &str) -> Output { - let mut child = driver(args, table).spawn().unwrap(); - child - .stdin - .take() - .unwrap() - .write_all(table.as_bytes()) - .unwrap(); - child.wait_with_output().unwrap() -} - -struct Serving { - child: Child, - channel: Channel, - _dir: tempfile::TempDir, -} - -impl Drop for Serving { - fn drop(&mut self) { - let _ = self.child.kill(); - let _ = self.child.wait(); - } -} - -async fn connect(path: &Path) -> Option { - let path = path.to_path_buf(); - Endpoint::try_from("http://localhost") - .unwrap() - .connect_with_connector(tower::service_fn(move |_| { - let path = path.clone(); - async move { - Ok::<_, std::io::Error>(TokioIo::new(tokio::net::UnixStream::connect(path).await?)) - } - })) - .await - .ok() -} - -async fn serve(table: &str) -> Serving { - let dir = tempfile::tempdir().unwrap(); - let socket = dir.path().join("run").join("driver.sock"); - let table = table.replace("@STATE@", &dir.path().join("state").display().to_string()); - let pid = std::process::id().to_string(); - let mut child = driver( - &[ - "serve", - "--bind-socket", - socket.to_str().unwrap(), - "--expected-peer-pid", - &pid, - ], - &table, - ) - .spawn() - .unwrap(); - child - .stdin - .take() - .unwrap() - .write_all(table.as_bytes()) - .unwrap(); - let deadline = Instant::now() + Duration::from_mins(1); - loop { - if let Some(status) = child.try_wait().unwrap() { - panic!("driver exited early: {status}"); - } - if let Some(channel) = connect(&socket).await { - return Serving { - child, - channel, - _dir: dir, - }; - } - assert!( - Instant::now() < deadline, - "driver never accepted a connection" - ); - tokio::time::sleep(Duration::from_millis(50)).await; - } -} - -const TABLE: &str = "state_dir = \"@STATE@\"\ndefault_image = \"example.test/sandbox:1\"\n"; - -fn configure(version: u32, port: u32) -> ConfigureRequest { - ConfigureRequest { - protocol_version: version, - gateway: Some(openshell_driver_sdk::launch::GatewayContext { - gateway_port: port, - ..Default::default() - }), - ..Default::default() - } -} - -#[tokio::test] -async fn launch_info_answers_and_compute_calls_wait_for_configure() { - let serving = serve(TABLE).await; - - let info = DriverLaunchClient::new(serving.channel.clone()) - .get_launch_info(GetLaunchInfoRequest {}) - .await - .unwrap() - .into_inner(); - assert_eq!(info.driver_name, "vm"); - assert_eq!(info.protocol_versions, [PROTOCOL_VERSION]); - - let status = ComputeDriverClient::new(serving.channel.clone()) - .get_capabilities(GetCapabilitiesRequest::default()) - .await - .unwrap_err(); - assert_eq!(status.code(), Code::Unavailable); -} - -#[tokio::test] -async fn a_failed_configure_leaves_the_driver_running_for_a_retry() { - let mut serving = serve(TABLE).await; - let mut client = DriverLaunchClient::new(serving.channel.clone()); - - let unsupported = client - .configure(configure(PROTOCOL_VERSION + 1, 8080)) - .await - .unwrap_err(); - assert_eq!(unsupported.code(), Code::FailedPrecondition); - - // No gateway port and no `grpc_endpoint` in the table. - let incomplete = client - .configure(configure(PROTOCOL_VERSION, 0)) - .await - .unwrap_err(); - assert_eq!(incomplete.code(), Code::InvalidArgument); - assert!(serving.child.try_wait().unwrap().is_none()); - - client - .configure(configure(PROTOCOL_VERSION, 8080)) - .await - .unwrap(); - // The driver now answers; it rejects this bare request only because the - // extension handshake metadata is missing. - let answered = ComputeDriverClient::new(serving.channel.clone()) - .get_capabilities(GetCapabilitiesRequest::default()) - .await; - assert_ne!( - answered.err().map(|status| status.code()), - Some(Code::Unavailable) - ); - let again = client - .configure(configure(PROTOCOL_VERSION, 8080)) - .await - .unwrap_err(); - assert_eq!(again.code(), Code::FailedPrecondition); -} - -#[test] -fn an_invalid_table_exits_with_the_config_code_and_one_json_line() { - let output = run_with_table( - &[ - "serve", - "--bind-socket", - "/nonexistent/driver.sock", - "--expected-peer-pid", - "1", - ], - "vcpu = 4", - ); - assert_eq!(output.status.code(), Some(78)); - let stdout = String::from_utf8_lossy(&output.stdout); - let report = openshell_driver_sdk::StartReport::from_output(&stdout) - .unwrap_or_else(|| panic!("no report line in: {stdout}")); - assert_eq!(report.kind, openshell_driver_sdk::StartKind::InvalidConfig); - assert!(report.reason.contains("vcpu"), "{}", report.reason); -} - -#[test] -fn preflight_accepts_a_valid_table_and_creates_no_state() { - let dir = tempfile::tempdir().unwrap(); - let state = dir.path().join("state"); - let table = format!("state_dir = \"{}\"\nvcpus = 4\n", state.display()); - - let output = run_with_table(&["preflight"], &table); - assert_eq!(output.status.code(), Some(0), "{:?}", output.stdout); - assert!(!state.exists(), "preflight must not create state"); - assert_eq!(run_with_table(&["preflight"], "").status.code(), Some(0)); -} - -#[test] -fn preflight_rejects_an_unknown_key() { - let output = run_with_table(&["preflight"], "vcpu = 4"); - assert_eq!(output.status.code(), Some(78)); - assert!( - openshell_driver_sdk::StartReport::from_output(&String::from_utf8_lossy(&output.stdout)) - .is_some() - ); -} - -#[tokio::test] -async fn a_stop_signal_waits_for_the_gateway_to_release_the_driver() { - let mut serving = serve("").await; - let signalled = Command::new("kill") - .args(["-TERM", &serving.child.id().to_string()]) - .status() - .unwrap(); - assert!(signalled.success()); - - // The driver defers the signal, so the gateway can still use it. - tokio::time::sleep(Duration::from_millis(500)).await; - assert!( - serving.child.try_wait().unwrap().is_none(), - "the driver stopped on SIGTERM before the gateway released it" - ); - DriverLaunchClient::new(serving.channel.clone()) - .get_launch_info(GetLaunchInfoRequest {}) - .await - .unwrap(); - - DriverLaunchClient::new(serving.channel.clone()) - .shutdown(ShutdownRequest {}) - .await - .unwrap(); - let deadline = Instant::now() + Duration::from_secs(10); - let status = loop { - if let Some(status) = serving.child.try_wait().unwrap() { - break status; - } - assert!( - Instant::now() < deadline, - "the driver did not stop after Shutdown" - ); - tokio::time::sleep(Duration::from_millis(50)).await; - }; - assert!(status.success(), "{status}"); -} diff --git a/deny.toml b/deny.toml index addeb081c4..f50980b926 100644 --- a/deny.toml +++ b/deny.toml @@ -15,7 +15,7 @@ unmaintained = "workspace" maximum-db-staleness = "P30D" ignore = [ # OpenShell uses Jiff for timestamps. oauth2 5.0.0 requires chrono ^0.4.31 - # in the root and test workspaces. cedar-policy-core, oci-client, russh-sftp + # in the root and test workspaces. cedar-policy-core, russh-sftp # and russh-util also depend on chrono. Tests use quick-junit 0.8.0, which # requires chrono ^0.4.45. # The resolved chrono 0.4.45 is unmaintained and has no patched release. @@ -164,14 +164,10 @@ wrappers = [ "jsonwebtoken", "lzma-rust2", "oauth2", - "oci-client", "openshell-core", - "openshell-driver-docker", "openshell-driver-kubernetes", "openshell-driver-kubernetes-secrets", - "openshell-driver-podman", "openshell-driver-vault", - "openshell-driver-vm", "openshell-gateway-interceptors", "openshell-isolation-interface", "openshell-server", diff --git a/docs/extensibility/drivers.mdx b/docs/extensibility/drivers.mdx index 5dc88b76d5..654da5899d 100644 --- a/docs/extensibility/drivers.mdx +++ b/docs/extensibility/drivers.mdx @@ -25,9 +25,9 @@ to each driver crate: | Driver | Crate | |---|---| -| Docker | [`openshell-driver-docker`](https://github.com/ai-openshell/openshell/blob/main/crates/openshell-driver-docker/README.md) | -| Podman | [`openshell-driver-podman`](https://github.com/ai-openshell/openshell/blob/main/crates/openshell-driver-podman/README.md) | -| MicroVM | [`openshell-driver-vm`](https://github.com/ai-openshell/openshell/blob/main/crates/openshell-driver-vm/README.md) | +| Docker | [`openshell-driver-docker`](https://github.com/ai-openshell/desktop/blob/main/crates/openshell-driver-docker/README.md) | +| Podman | [`openshell-driver-podman`](https://github.com/ai-openshell/desktop/blob/main/crates/openshell-driver-podman/README.md) | +| MicroVM | [`openshell-driver-vm`](https://github.com/ai-openshell/desktop/blob/main/crates/openshell-driver-vm/README.md) | | Kubernetes | [`openshell-driver-kubernetes`](https://github.com/ai-openshell/openshell/blob/main/crates/openshell-driver-kubernetes/README.md) | | Windows MXC | [`openshell-driver-mxc`](https://github.com/ai-openshell/openshell/blob/main/crates/openshell-driver-mxc/README.md) | diff --git a/docs/extensibility/overview.mdx b/docs/extensibility/overview.mdx index d252f62e34..f80775fde4 100644 --- a/docs/extensibility/overview.mdx +++ b/docs/extensibility/overview.mdx @@ -86,8 +86,8 @@ The [governance interceptor example](https://github.com/ai-openshell/openshell/t and [content guard middleware example](https://github.com/ai-openshell/openshell/tree/main/examples/supervisor-middleware-content-guard) include complete gRPC services, gateway configuration, and smoke tests. For runtime integrations, refer to the first-party -[Docker compute driver](https://github.com/ai-openshell/openshell/tree/main/crates/openshell-driver-docker) -and [VM compute driver](https://github.com/ai-openshell/openshell/tree/main/crates/openshell-driver-vm). +[Docker compute driver](https://github.com/ai-openshell/desktop/tree/main/crates/openshell-driver-docker) +and [VM compute driver](https://github.com/ai-openshell/desktop/tree/main/crates/openshell-driver-vm). ### Protocol Negotiation diff --git a/e2e/configs/gateway/docker.toml b/e2e/configs/gateway/docker.toml deleted file mode 100644 index e186004cd1..0000000000 --- a/e2e/configs/gateway/docker.toml +++ /dev/null @@ -1,28 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -[openshell] -version = 2 - -[openshell.gateway] -bind_address = "127.0.0.1:8080" -log_level = "info" -compute_driver = "docker" -disable_tls = true - -[openshell.gateway.auth] -allow_unauthenticated_users = true - -[openshell.gateway.gateway_jwt] -signing_key_path = ".cache/openshell-e2e/gateway-jwt/signing.pem" -public_key_path = ".cache/openshell-e2e/gateway-jwt/public.pem" -kid_path = ".cache/openshell-e2e/gateway-jwt/kid" -gateway_id = "openshell-e2e" - -[openshell.drivers.docker] -default_image = "nvcr.io/nvidia/base/ubuntu:24.04" -image_pull_policy = "if_not_present" -sandbox_label = "openshell-e2e" -sandbox_runtime_image = "localhost/openshell/sandbox:e2e-vm" -supervisor_image = "localhost/openshell/supervisor:e2e-vm" -app_armor_profile = "Unconfined" diff --git a/e2e/configs/gateway/podman.toml b/e2e/configs/gateway/podman.toml deleted file mode 100644 index 332accc982..0000000000 --- a/e2e/configs/gateway/podman.toml +++ /dev/null @@ -1,31 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -[openshell] -version = 2 - -[openshell.gateway] -bind_address = "127.0.0.1:8080" -log_level = "info" -compute_driver = "podman" -disable_tls = true - -[openshell.gateway.auth] -allow_unauthenticated_users = true - -[openshell.gateway.gateway_jwt] -signing_key_path = ".cache/openshell-e2e/gateway-jwt/signing.pem" -public_key_path = ".cache/openshell-e2e/gateway-jwt/public.pem" -kid_path = ".cache/openshell-e2e/gateway-jwt/kid" -gateway_id = "openshell-e2e" - -[openshell.drivers.podman] -default_image = "nvcr.io/nvidia/base/ubuntu:24.04" -image_pull_policy = "if_not_present" -health_check_interval_secs = 10 -network_name = "openshell-e2e" -grpc_endpoint = "http://host.containers.internal:8080" -ssh_socket_path = "/run/openshell/ssh.sock" -sandbox_runtime_image = "localhost/openshell/sandbox:e2e-vm" -supervisor_image = "localhost/openshell/supervisor:e2e-vm" -app_armor_profile = "Unconfined" diff --git a/tasks/scripts/vm/_lib.sh b/tasks/scripts/vm/_lib.sh deleted file mode 100755 index f6d12d3e6f..0000000000 --- a/tasks/scripts/vm/_lib.sh +++ /dev/null @@ -1,148 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Shared helpers for VM runtime build scripts. -# Source this file from other scripts: -# source "$(dirname "${BASH_SOURCE[0]}")/_lib.sh" - -# ── Root directory ────────────────────────────────────────────────────── - -vm_lib_root() { - cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd -} - -# ── Platform detection ────────────────────────────────────────────────── - -# Detect the current platform and echo one of: -# darwin-aarch64, linux-aarch64, linux-x86_64 -# Exits with error on unsupported platforms. -detect_platform() { - case "$(uname -s)-$(uname -m)" in - Darwin-arm64) echo "darwin-aarch64" ;; - Linux-aarch64) echo "linux-aarch64" ;; - Linux-x86_64) echo "linux-x86_64" ;; - *) - echo "Error: Unsupported platform: $(uname -s)-$(uname -m)" >&2 - echo "Supported: macOS ARM64, Linux ARM64, Linux x86_64" >&2 - return 1 - ;; - esac -} - -# ── Runtime dependency downloads ──────────────────────────────────────── - -# Download a Linux guest umoci binary for the requested architecture. -# Usage: download_umoci_binary -download_umoci_binary() { - local output="$1" - local version="$2" - local guest_arch="$3" - local suffix - - case "$guest_arch" in - arm64|aarch64) suffix="arm64" ;; - amd64|x86_64) suffix="amd64" ;; - *) - echo "Error: Unsupported guest architecture for umoci: ${guest_arch}" >&2 - return 1 - ;; - esac - - local base_url="https://github.com/opencontainers/umoci/releases/download/${version}" - local candidates=("umoci.linux.${suffix}" "umoci.${suffix}") - local error_log last_error asset - error_log="$(mktemp)" - last_error="" - - echo " Downloading umoci ${version} for linux/${suffix}..." - for asset in "${candidates[@]}"; do - if curl -fsSL -o "$output" "${base_url}/${asset}" 2>"$error_log"; then - chmod +x "$output" - rm -f "$error_log" - return 0 - fi - last_error="$(cat "$error_log")" - rm -f "$output" - done - - rm -f "$error_log" - echo "Error: failed to download umoci ${version} for linux/${suffix}" >&2 - if [ -n "$last_error" ]; then - echo "$last_error" >&2 - fi - return 1 -} - -# Map a VM runtime platform to the Linux guest umoci architecture. -# Usage: umoci_guest_arch_for_platform -umoci_guest_arch_for_platform() { - local platform="$1" - - case "$platform" in - linux-aarch64|darwin-aarch64) echo "arm64" ;; - linux-x86_64) echo "amd64" ;; - *) - echo "Error: Unsupported platform for umoci guest binary: ${platform}" >&2 - return 1 - ;; - esac -} - -# Ensure an extracted runtime directory contains the guest umoci binary. -# Usage: ensure_umoci_for_platform -ensure_umoci_for_platform() { - local runtime_dir="$1" - local platform="$2" - local version="$3" - - if [ -f "${runtime_dir}/umoci" ]; then - return 0 - fi - - local guest_arch - guest_arch="$(umoci_guest_arch_for_platform "$platform")" - echo " Runtime tarball has no umoci" - download_umoci_binary "${runtime_dir}/umoci" "$version" "$guest_arch" -} - -# ── Compression helpers ───────────────────────────────────────────────── - -# Compress a single file with zstd level 19, reporting sizes. -# Usage: compress_file -compress_file() { - local input="$1" - local output="$2" - local name - name="$(basename "$input")" - local original_size - original_size="$(du -h "$input" | cut -f1)" - - zstd -19 -f -q -T0 -o "$output" "$input" - chmod 644 "$output" - - local compressed_size - compressed_size="$(du -h "$output" | cut -f1)" - echo " ${name}: ${original_size} -> ${compressed_size}" -} - -# Compress all files in a directory (skipping provenance.json) into an -# output directory, appending .zst to each filename. -# Usage: compress_dir -compress_dir() { - local source_dir="$1" - local output_dir="$2" - - echo "==> Compressing with zstd (level 19)..." - for file in "$source_dir"/*; do - [ -f "$file" ] || continue - local name - name="$(basename "$file")" - # Skip metadata files — not embedded - if [ "$name" = "provenance.json" ]; then - cp "$file" "${output_dir}/" - continue - fi - compress_file "$file" "${output_dir}/${name}.zst" - done -} diff --git a/tasks/scripts/vm/build-libkrun-macos.sh b/tasks/scripts/vm/build-libkrun-macos.sh deleted file mode 100755 index 1afee1c937..0000000000 --- a/tasks/scripts/vm/build-libkrun-macos.sh +++ /dev/null @@ -1,286 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Build libkrun + libkrunfw from source on macOS with portable rpath. -# -# This script compiles a pre-built kernel.c (from the Linux ARM64 CI job) into -# libkrunfw.dylib, then builds libkrun.dylib (the VMM) WITHOUT GPU support. -# The resulting binaries are fully portable and self-contained. -# -# The kernel.c file contains the aarch64 Linux kernel as a byte array. It is -# architecture-specific but OS-agnostic — any C compiler can turn it into a -# shared library. This eliminates the need to build the kernel on macOS via -# krunvm, cutting the macOS CI job from ~45 minutes to ~5 minutes. -# -# Prerequisites: -# - macOS ARM64 (Apple Silicon) -# - Xcode Command Line Tools -# - Homebrew: brew install rust lld dtc xz -# - Pre-built kernel.c and ABI_VERSION from the Linux ARM64 build -# -# Usage: -# ./build-libkrun-macos.sh --kernel-dir -# -# --kernel-dir Directory containing kernel.c and ABI_VERSION (from Linux build) -# -# Output: -# target/libkrun-build/libkrun.dylib - portable dylib with @loader_path rpath -# target/libkrun-build/libkrunfw.dylib - portable dylib compiled from kernel.c - -set -euo pipefail - -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" - -# Source pinned dependency versions. -source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" - -BUILD_DIR="${ROOT}/target/libkrun-build" -OUTPUT_DIR="${BUILD_DIR}" -BREW_PREFIX="$(brew --prefix 2>/dev/null || echo /opt/homebrew)" -KERNEL_DIR="" - -# Parse arguments -while [[ $# -gt 0 ]]; do - case "$1" in - --kernel-dir) - KERNEL_DIR="$(cd "$2" && pwd)"; shift 2 ;; - --help|-h) - echo "Usage: $0 --kernel-dir " - echo "" - echo "Build libkrun + libkrunfw on macOS using a pre-built kernel.c." - echo "" - echo "Options:" - echo " --kernel-dir DIR Directory containing kernel.c and ABI_VERSION" - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2; exit 1 ;; - esac -done - -if [ "$(uname -s)" != "Darwin" ]; then - echo "Error: This script only runs on macOS" >&2 - exit 1 -fi - -if [ "$(uname -m)" != "arm64" ]; then - echo "Error: libkrun on macOS only supports ARM64 (Apple Silicon)" >&2 - exit 1 -fi - -if [ -z "$KERNEL_DIR" ]; then - echo "Error: --kernel-dir is required" >&2 - echo " This should point to the directory containing kernel.c and ABI_VERSION" >&2 - echo " from the Linux ARM64 build job." >&2 - exit 1 -fi - -if [ ! -f "${KERNEL_DIR}/kernel.c" ]; then - echo "Error: kernel.c not found in ${KERNEL_DIR}" >&2 - exit 1 -fi - -if [ ! -f "${KERNEL_DIR}/ABI_VERSION" ]; then - echo "Error: ABI_VERSION not found in ${KERNEL_DIR}" >&2 - exit 1 -fi - -ABI_VERSION="$(cat "${KERNEL_DIR}/ABI_VERSION")" - -ARCH="$(uname -m)" -echo "==> Building libkrun + libkrunfw for macOS ${ARCH} (no GPU support)" -echo " Build directory: ${BUILD_DIR}" -echo " Kernel source: ${KERNEL_DIR}/kernel.c ($(du -sh "${KERNEL_DIR}/kernel.c" | cut -f1))" -echo " ABI version: ${ABI_VERSION}" -echo "" - -# ── Check dependencies ────────────────────────────────────────────────── - -check_deps() { - echo "==> Checking build dependencies..." - - MISSING="" - - # Check for Rust - if ! command -v cargo &>/dev/null; then - MISSING="$MISSING rust" - fi - - # Check for lld (LLVM linker) - if ! command -v ld.lld &>/dev/null && ! [ -x "${BREW_PREFIX}/opt/llvm/bin/ld.lld" ]; then - MISSING="$MISSING lld" - fi - - # Check for dtc (device tree compiler) - if ! command -v dtc &>/dev/null; then - MISSING="$MISSING dtc" - fi - - if [ -n "$MISSING" ]; then - echo "Error: Missing dependencies:$MISSING" >&2 - echo "" >&2 - echo "Install with: brew install$MISSING" >&2 - exit 1 - fi - - echo " All dependencies found" -} - -check_deps - -# ── Setup build directory ─────────────────────────────────────────────── - -mkdir -p "$BUILD_DIR" -cd "$BUILD_DIR" - -# ── Compile libkrunfw.dylib from pre-built kernel.c ──────────────────── - -echo "" -echo "==> Compiling libkrunfw.dylib from pre-built kernel.c..." - -# kernel.c is a C source file containing the Linux kernel as a byte array. -# It was generated by the Linux ARM64 build job. We just need to compile it -# into a shared library with the correct ABI version. -cc -fPIC -DABI_VERSION="${ABI_VERSION}" -shared \ - -o "${OUTPUT_DIR}/libkrunfw.${ABI_VERSION}.dylib" \ - "${KERNEL_DIR}/kernel.c" - -# Create the unversioned symlink that libkrun links against -cp "${OUTPUT_DIR}/libkrunfw.${ABI_VERSION}.dylib" "${OUTPUT_DIR}/libkrunfw.dylib" - -echo " Built: libkrunfw.${ABI_VERSION}.dylib ($(du -sh "${OUTPUT_DIR}/libkrunfw.${ABI_VERSION}.dylib" | cut -f1))" - -# ── Clone libkrun ─────────────────────────────────────────────────────── - -if [ ! -d libkrun ]; then - echo "==> Cloning libkrun..." - git clone https://github.com/libkrun/libkrun.git -fi - -echo "==> Checking out ${LIBKRUN_REF}..." -cd libkrun -git fetch origin --tags -git checkout "${LIBKRUN_REF}" 2>/dev/null || git checkout "tags/${LIBKRUN_REF}" 2>/dev/null || { - echo "Error: Could not checkout ${LIBKRUN_REF}" >&2 - exit 1 -} -cd .. - -LIBKRUN_COMMIT=$(git -C libkrun rev-parse HEAD) -echo " Commit: ${LIBKRUN_COMMIT}" - -cd libkrun - -# ── Build libkrun ─────────────────────────────────────────────────────── - -echo "" -echo "==> Building libkrun with NET=1 BLK=1 (no GPU)..." - -# Point the linker at our freshly-compiled libkrunfw -export LIBRARY_PATH="${OUTPUT_DIR}:${BREW_PREFIX}/lib:${LIBRARY_PATH:-}" -export DYLD_LIBRARY_PATH="${OUTPUT_DIR}:${BREW_PREFIX}/lib:${DYLD_LIBRARY_PATH:-}" - -# Set up LLVM/clang for bindgen -LLVM_PREFIX="${BREW_PREFIX}/opt/llvm" -if [ -d "$LLVM_PREFIX" ]; then - export LIBCLANG_PATH="${LLVM_PREFIX}/lib" - export DYLD_LIBRARY_PATH="${LLVM_PREFIX}/lib:${DYLD_LIBRARY_PATH:-}" -fi - -# Build with BLK and NET features only (no GPU) -# This avoids the virglrenderer -> libepoxy -> MoltenVK dependency chain -make clean 2>/dev/null || true -make BLK=1 NET=1 -j"$(sysctl -n hw.ncpu)" - -# ── Rewrite dylib paths for portability ───────────────────────────────── - -echo "" -echo "==> Making dylibs portable with @loader_path..." - -DYLIB="target/release/libkrun.dylib" -if [ ! -f "$DYLIB" ]; then - echo "Error: Build did not produce $DYLIB" >&2 - exit 1 -fi - -# Copy to output -cp "$DYLIB" "${OUTPUT_DIR}/libkrun.dylib" -DYLIB="${OUTPUT_DIR}/libkrun.dylib" - -# Show current dependencies -echo " Original dependencies:" -otool -L "$DYLIB" | grep -v "^/" | sed 's/^/ /' - -# Rewrite the install name to use @loader_path (makes it relocatable) -install_name_tool -id "@loader_path/libkrun.dylib" "$DYLIB" - -# Rewrite libkrunfw path to @loader_path (will be bundled alongside) -KRUNFW_PATH=$(otool -L "$DYLIB" | grep libkrunfw | awk '{print $1}' || true) -if [ -n "$KRUNFW_PATH" ]; then - install_name_tool -change "$KRUNFW_PATH" "@loader_path/libkrunfw.dylib" "$DYLIB" - echo " Rewrote: $KRUNFW_PATH -> @loader_path/libkrunfw.dylib" -fi - -# Re-codesign after modifications (required on macOS) -codesign -f -s - "$DYLIB" - -# Make libkrunfw portable too -install_name_tool -id "@loader_path/libkrunfw.dylib" "${OUTPUT_DIR}/libkrunfw.dylib" -codesign -f -s - "${OUTPUT_DIR}/libkrunfw.dylib" - -if [ -f "${OUTPUT_DIR}/libkrunfw.${ABI_VERSION}.dylib" ]; then - install_name_tool -id "@loader_path/libkrunfw.${ABI_VERSION}.dylib" "${OUTPUT_DIR}/libkrunfw.${ABI_VERSION}.dylib" - codesign -f -s - "${OUTPUT_DIR}/libkrunfw.${ABI_VERSION}.dylib" -fi - -# Show final dependencies -echo "" -echo " Final dependencies:" -otool -L "$DYLIB" | grep -v "^/" | sed 's/^/ /' - -# Verify no hardcoded homebrew paths remain -if otool -L "$DYLIB" | grep -q "/opt/homebrew"; then - echo "" - echo "Warning: Homebrew paths still present in dylib!" >&2 - otool -L "$DYLIB" | grep "/opt/homebrew" | sed 's/^/ /' -else - echo "" - echo " No hardcoded Homebrew paths" -fi - -# ── Summary ───────────────────────────────────────────────────────────── - -cd "$BUILD_DIR" - -echo "" -echo "==> Build complete!" -echo " Output directory: ${OUTPUT_DIR}" -echo "" -echo " Artifacts:" -ls -lah "${OUTPUT_DIR}"/*.dylib - -# Verify portability -echo "" -echo "==> Verifying portability..." -ALL_GOOD=true - -for lib in "${OUTPUT_DIR}"/*.dylib; do - if otool -L "$lib" | grep -q "/opt/homebrew"; then - echo " x $(basename "$lib") has hardcoded paths" - ALL_GOOD=false - else - echo " ok $(basename "$lib") is portable" - fi -done - -if $ALL_GOOD; then - echo "" - echo "All libraries are portable!" - echo "" - echo "Next step: mise run vm:supervisor && cargo build -p openshell-driver-vm" -else - echo "" - echo "Warning: Some libraries have non-portable paths" - echo "They may not work on machines without Homebrew" -fi diff --git a/tasks/scripts/vm/build-libkrun.sh b/tasks/scripts/vm/build-libkrun.sh deleted file mode 100755 index 2e6f1d1138..0000000000 --- a/tasks/scripts/vm/build-libkrun.sh +++ /dev/null @@ -1,458 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Build libkrun and libkrunfw from source on Linux. -# -# This script builds libkrun (VMM) and libkrunfw (kernel firmware) from source -# with OpenShell's custom kernel configuration for sandbox enforcement. -# -# In addition to the platform's native .so artifacts, this script exports -# kernel.c, ABI_VERSION, and provenance.json (libkrunfw commit, kernel version, -# final kernel config hash) so that other platforms (e.g. macOS) can compile -# their own libkrunfw wrapper without rebuilding the kernel. -# -# Prerequisites: -# - Linux (aarch64 or x86_64) -# - Build tools: make, git, gcc, flex, bison, bc -# - Python 3 with pyelftools -# - Rust toolchain -# -# Usage: -# ./build-libkrun.sh -# -# The script will install missing dependencies on Debian/Ubuntu and Fedora. - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -source "${SCRIPT_DIR}/_lib.sh" -ROOT="$(vm_lib_root)" - -# Source pinned dependency versions. -source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" - -BUILD_DIR="${ROOT}/target/libkrun-build" -OUTPUT_DIR="${BUILD_DIR}" -KERNEL_CONFIG="${ROOT}/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig" - -if [ "$(uname -s)" != "Linux" ]; then - echo "Error: This script only runs on Linux" >&2 - exit 1 -fi - -HOST_ARCH="$(uname -m)" -echo "==> Building libkrun for Linux ${HOST_ARCH}" -echo " Build directory: ${BUILD_DIR}" -echo " Kernel config: ${KERNEL_CONFIG}" -echo "" - -# Map host arch to kernel ARCH value -case "$HOST_ARCH" in - aarch64) KARCH="arm64"; KERNEL_IMAGE_PATH="arch/arm64/boot/Image" ;; - x86_64) KARCH="x86"; KERNEL_IMAGE_PATH="arch/x86/boot/bzImage" ;; - *) echo "Error: Unsupported architecture: ${HOST_ARCH}" >&2; exit 1 ;; -esac - -# ── Install dependencies ──────────────────────────────────────────────── - -# Use sudo only when not already running as root (e.g. inside CI containers). -SUDO="" -if [ "$(id -u)" -ne 0 ]; then - SUDO="sudo" -fi - -install_deps() { - echo "==> Checking/installing build dependencies..." - - if command -v apt-get &>/dev/null; then - # Debian/Ubuntu - DEPS="build-essential git python3 python3-pip python3-pyelftools flex bison libelf-dev libssl-dev libcap-ng-dev bc curl libclang-dev cpio zstd jq" - MISSING="" - for dep in $DEPS; do - if ! dpkg -s "$dep" &>/dev/null; then - MISSING="$MISSING $dep" - fi - done - if [ -n "$MISSING" ]; then - echo " Installing:$MISSING" - $SUDO apt-get update - $SUDO apt-get install -y $MISSING - else - echo " All dependencies installed" - fi - - elif command -v dnf &>/dev/null; then - # Fedora/RHEL - DEPS="make git python3 python3-pyelftools gcc flex bison elfutils-libelf-devel openssl-devel libcap-ng-devel bc glibc-static curl clang-devel cpio zstd jq" - echo " Installing dependencies via dnf..." - $SUDO dnf install -y $DEPS - - else - echo "Warning: Unknown package manager. Please install manually:" >&2 - echo " build-essential git python3 python3-pyelftools flex bison" >&2 - echo " libelf-dev libssl-dev libcap-ng-dev bc curl cpio" >&2 - fi - -} - -install_deps - -# libkrunfw's Makefile invokes `python3` from PATH for bin2cbundle.py. A mise shim, -# project venv, or other early PATH entry often shadows /usr/bin/python3 and does -# not ship pyelftools even when python3-pyelftools is installed for the distro. -ensure_python3_with_pyelftools_for_libkrunfw() { - echo " Checking Python 3 + pyelftools (libkrunfw bin2cbundle.py)..." - if python3 -c 'from elftools.elf.elffile import ELFFile' 2>/dev/null; then - echo " OK ($(command -v python3))" - return 0 - fi - if [ -x /usr/bin/python3 ] && /usr/bin/python3 -c 'from elftools.elf.elffile import ELFFile' 2>/dev/null; then - export PATH="/usr/bin:${PATH}" - echo " Using /usr/bin/python3 (PATH python3 lacked pyelftools; system Python has it)." - return 0 - fi - echo "ERROR: Python 3 with pyelftools is required to build libkrunfw (kernel.c generation)." >&2 - echo " Install: Debian/Ubuntu: sudo apt-get install -y python3-pyelftools" >&2 - echo " Fedora/RHEL: sudo dnf install -y python3-pyelftools" >&2 - echo " pip: python3 -m pip install --user pyelftools" >&2 - echo " If the package is installed but this still fails, PATH may point at another python3 (mise, venv)." >&2 - echo " Try: PATH=/usr/bin:\$PATH mise run vm:setup" >&2 - exit 1 -} - -# ── Setup build directory ─────────────────────────────────────────────── - -mkdir -p "$BUILD_DIR" -cd "$BUILD_DIR" - -# ── Build libkrunfw (kernel firmware) ─────────────────────────────────── - -echo "" -echo "==> Building libkrunfw with custom kernel config..." - -ensure_python3_with_pyelftools_for_libkrunfw - -if [ ! -d libkrunfw ]; then - echo " Cloning libkrunfw (pinned: ${LIBKRUNFW_REF})..." - git clone https://github.com/libkrun/libkrunfw.git -fi - -cd libkrunfw - -# Ensure we're on the pinned commit for reproducible builds -echo " Checking out pinned ref: ${LIBKRUNFW_REF}" -git fetch origin -git checkout "${LIBKRUNFW_REF}" - -# Copy custom kernel config fragment -if [ -f "$KERNEL_CONFIG" ]; then - cp "$KERNEL_CONFIG" openshell.kconfig - echo " Applied custom kernel config fragment: openshell.kconfig" -else - echo "Warning: Custom kernel config not found at ${KERNEL_CONFIG}" >&2 - echo " Building with default config (sandbox networking may lack required kernel features)" >&2 -fi - -echo " Building kernel and libkrunfw (this may take 15-20 minutes)..." - -# The libkrunfw Makefile does not support a config fragment — it copies the -# base config and runs olddefconfig, then builds the kernel image in one -# make invocation. We cannot inject the fragment mid-build via make flags. -# -# Instead we drive the build in two phases: -# -# Phase 1: Run the Makefile's $(KERNEL_SOURCES) target, which: -# - downloads and extracts the kernel tarball (if needed) -# - applies patches -# - copies config-libkrunfw_{arch} to $(KERNEL_SOURCES)/.config -# - runs olddefconfig -# -# Phase 2: Merge our fragment on top of the .config produced by Phase 1 -# using the kernel's own merge_config.sh, then re-run olddefconfig -# to resolve new dependency chains (e.g. CONFIG_BRIDGE pulls in -# CONFIG_BRIDGE_NETFILTER which needs CONFIG_NETFILTER etc). -# -# Phase 3: Let the Makefile build everything (kernel + kernel.c + .so), -# skipping the $(KERNEL_SOURCES) target since it already exists. - -KERNEL_VERSION="$(grep '^KERNEL_VERSION' Makefile | head -1 | awk '{print $3}')" -KERNEL_SOURCES="${KERNEL_VERSION}" - -# Phase 1: prepare kernel source tree + base .config. -# Run the Makefile's $(KERNEL_SOURCES) target whenever the .config is absent -# (either because the tree was never extracted, or because it was cleaned). -# The target is idempotent: if the directory already exists make skips the -# tarball extraction but still copies the base config and runs olddefconfig. -if [ ! -f "${KERNEL_SOURCES}/.config" ]; then - echo " Phase 1: preparing kernel source tree and base .config..." - # Remove the directory so make re-runs the full $(KERNEL_SOURCES) recipe - # (extract + patch + config copy + olddefconfig). - rm -rf "${KERNEL_SOURCES}" - make "${KERNEL_SOURCES}" -else - echo " Phase 1: kernel source tree and .config already present, skipping" -fi - -# Phase 2: merge the openshell fragment on top -if [ -f openshell.kconfig ]; then - echo " Phase 2: merging openshell.kconfig fragment..." - - # merge_config.sh must be called with ARCH set so it finds the right Kconfig - # entry points. -m means "merge into existing .config" (vs starting fresh). - ARCH="${KARCH}" KCONFIG_CONFIG="${KERNEL_SOURCES}/.config" \ - "${KERNEL_SOURCES}/scripts/kconfig/merge_config.sh" \ - -m -O "${KERNEL_SOURCES}" \ - "${KERNEL_SOURCES}/.config" \ - openshell.kconfig - - # Re-run olddefconfig to fill in any new symbols introduced by the fragment. - make -C "${KERNEL_SOURCES}" ARCH="${KARCH}" olddefconfig - - # Verify that the key options were actually applied. - all_ok=true - for opt in \ - CONFIG_SECURITY \ - CONFIG_SECURITY_LANDLOCK \ - CONFIG_SECCOMP \ - CONFIG_SECCOMP_FILTER \ - CONFIG_HARDENED_USERCOPY \ - CONFIG_INIT_STACK_ALL_ZERO \ - CONFIG_INIT_ON_ALLOC_DEFAULT_ON \ - CONFIG_SLAB_FREELIST_RANDOM; do - val="$(grep -E "^(# )?${opt}(=| )" "${KERNEL_SOURCES}/.config" 2>/dev/null || true)" - if [ "$val" = "${opt}=y" ]; then - echo " ${opt}: y" - else - echo " WARNING: ${opt} is not enabled after merge: ${val:-unset}" >&2 - all_ok=false - fi - done - if grep -qx '# CONFIG_INIT_ON_FREE_DEFAULT_ON is not set' "${KERNEL_SOURCES}/.config"; then - echo " CONFIG_INIT_ON_FREE_DEFAULT_ON: disabled" - else - echo " WARNING: CONFIG_INIT_ON_FREE_DEFAULT_ON is not explicitly disabled after merge!" >&2 - all_ok=false - fi - lsm_order="$(grep '^CONFIG_LSM=' "${KERNEL_SOURCES}/.config" 2>/dev/null || true)" - if [[ "$lsm_order" == *landlock* ]]; then - echo " CONFIG_LSM: ${lsm_order#*=}" - else - echo " WARNING: CONFIG_LSM does not activate Landlock: ${lsm_order:-unset}" >&2 - all_ok=false - fi - if [ "$all_ok" = false ]; then - echo "ERROR: kernel config fragment merge failed — required options missing" >&2 - exit 1 - fi - - # The kernel binary and kernel.c from the previous (bad) build must be - # removed so make rebuilds them with the updated .config. - rm -f kernel.c "${KERNEL_SOURCES}/${KERNEL_IMAGE_PATH}" \ - "${KERNEL_SOURCES}/vmlinux" libkrunfw.so* -fi - -# Phase 3: build kernel image, kernel.c bundle, and the shared library -make -j"$(nproc)" - -# Copy output -cp libkrunfw.so* "$OUTPUT_DIR/" -if [ ! -f ABI_VERSION ]; then - ABI_VERSION_VALUE="$(awk '/^ABI_VERSION[[:space:]]*[:?+]?=/ { value=$0; sub(/^[^=]*=/, "", value); gsub(/[[:space:]]/, "", value); print value; exit }' Makefile)" - if [ -z "$ABI_VERSION_VALUE" ]; then - echo "ERROR: could not determine libkrunfw ABI_VERSION from Makefile" >&2 - exit 1 - fi - printf '%s\n' "$ABI_VERSION_VALUE" > ABI_VERSION -fi -for artifact in kernel.c ABI_VERSION; do - if [ ! -f "$artifact" ]; then - echo "ERROR: expected libkrunfw export missing: $artifact" >&2 - exit 1 - fi - cp "$artifact" "$OUTPUT_DIR/" -done -echo " Built: $(ls "$OUTPUT_DIR"/libkrunfw.so* | xargs -n1 basename | tr '\n' ' ')" - -# Record the kernel inputs for package-vm-runtime.sh. The macOS job reuses -# kernel.c without a libkrunfw checkout, so it reads this file instead. -kernel_config_sha256="$(sha256sum "${KERNEL_SOURCES}/.config" | awk '{print $1}')" -printf '{"libkrunfw_commit":"%s","kernel_version":"%s","kernel_config_sha256":"%s"}\n' \ - "$(git rev-parse HEAD)" "$KERNEL_VERSION" "$kernel_config_sha256" \ - > "$OUTPUT_DIR/provenance.json" -echo " Kernel config sha256: ${kernel_config_sha256}" - -cd "$BUILD_DIR" - -# ── Build libkrun (VMM) ───────────────────────────────────────────────── - -# libkrun's Makefile invokes plain `cargo`. Ubuntu/Debian often put /usr/bin/cargo -# (e.g. 1.75) ahead of mise/rustup; upstream requires edition 2024 (Cargo >= 1.85). -ensure_cargo_for_libkrun() { - local min_ver="${LIBKRUN_MIN_CARGO_VERSION:-1.85}" - local have ver_line bindir candidates_mise candidates_home - - cargo_meets_min() { - local bin="$1" - local v - [ -x "$bin" ] || return 1 - v="$("$bin" --version 2>/dev/null | awk '{print $2}')" - [ -n "$v" ] || return 1 - [ "$(printf '%s\n' "${min_ver}" "$v" | sort -V | head -n1)" = "${min_ver}" ] - } - - echo " Checking Cargo (libkrun needs >= ${min_ver}, edition 2024)..." - if cargo_meets_min "$(command -v cargo 2>/dev/null || true)"; then - echo " OK ($(command -v cargo) — $(cargo --version))" - return 0 - fi - - candidates_mise="" - if command -v mise &>/dev/null; then - if ver_line="$(mise which cargo 2>/dev/null)" && [ -n "${ver_line}" ]; then - candidates_mise="$(dirname "${ver_line}")" - fi - fi - candidates_home="${HOME}/.cargo/bin" - - for bindir in "${candidates_mise}" "${candidates_home}"; do - [ -n "${bindir}" ] || continue - if cargo_meets_min "${bindir}/cargo"; then - export PATH="${bindir}:${PATH}" - echo " Using ${bindir}/cargo ($("${bindir}/cargo" --version))" - return 0 - fi - done - - echo "ERROR: Cargo >= ${min_ver} is required to build libkrun (Rust edition 2024)." >&2 - echo " Current: $(command -v cargo 2>/dev/null || echo '(no cargo in PATH)') $(cargo --version 2>/dev/null || true)" >&2 - echo " Typical fix: run vm:setup via mise from the repo so Rust 1.95.0 is on PATH," >&2 - echo " or: rustup toolchain install 1.95.0 && rustup default 1.95.0 && export PATH=\"\$HOME/.cargo/bin:\$PATH\"" >&2 - echo " Override minimum: LIBKRUN_MIN_CARGO_VERSION=…" >&2 - exit 1 -} - -# Directory must contain libclang.so or libclang-.so (what clang-sys expects -# for linking; bare .so.N sonames alone are not enough). -_libclang_dir_usable() { - local d="$1" - [ -n "$d" ] && [ -d "$d" ] || return 1 - if [ -e "$d/libclang.so" ]; then - return 0 - fi - local f base - for f in "$d"/libclang-*.so; do - [ -e "$f" ] || continue - base="$(basename "$f")" - case "$base" in - *-cpp.so*) continue ;; - esac - if [[ "$base" == libclang-*.so ]] && [[ "$base" != *.so.[0-9]* ]]; then - return 0 - fi - done - return 1 -} - -ensure_libclang_for_libkrun() { - local user_libclang="${LIBCLANG_PATH:-}" - - if [ -n "$user_libclang" ] && _libclang_dir_usable "$user_libclang"; then - export LIBCLANG_PATH="$user_libclang" - echo " LIBCLANG_PATH=$LIBCLANG_PATH (from environment)" - return 0 - fi - - if [ -n "$user_libclang" ]; then - echo " Warning: LIBCLANG_PATH='$user_libclang' has no libclang.so or libclang-*.so symlink;" >&2 - echo " those are required for clang-sys. Searching other system locations..." >&2 - fi - unset LIBCLANG_PATH - - local llvm_lib - if command -v llvm-config &>/dev/null; then - llvm_lib="$(llvm-config --libdir 2>/dev/null)" || true - if [ -n "${llvm_lib}" ] && _libclang_dir_usable "$llvm_lib"; then - export LIBCLANG_PATH="$llvm_lib" - echo " LIBCLANG_PATH=$LIBCLANG_PATH (from llvm-config --libdir)" - return 0 - fi - fi - - shopt -s nullglob - local candidates=(/usr/lib/llvm-*/lib) - shopt -u nullglob - while IFS= read -r llvm_lib; do - [ -n "$llvm_lib" ] || continue - if _libclang_dir_usable "$llvm_lib"; then - export LIBCLANG_PATH="$llvm_lib" - echo " LIBCLANG_PATH=$LIBCLANG_PATH (from /usr/lib/llvm-*/lib)" - return 0 - fi - done < <(printf '%s\n' "${candidates[@]}" | sort -rV) - - local multi - multi="$(gcc -print-multiarch 2>/dev/null || true)" - if [ -n "$multi" ] && _libclang_dir_usable "/usr/lib/${multi}"; then - export LIBCLANG_PATH="/usr/lib/${multi}" - echo " LIBCLANG_PATH=$LIBCLANG_PATH (from gcc multiarch /usr/lib/${multi})" - return 0 - fi - - if _libclang_dir_usable "/usr/lib64"; then - export LIBCLANG_PATH="/usr/lib64" - echo " LIBCLANG_PATH=$LIBCLANG_PATH (from /usr/lib64)" - return 0 - fi - - echo "ERROR: libclang is required to build libkrun (Rust bindgen / clang-sys) but was not found." >&2 - if [ -n "$user_libclang" ]; then - echo " You had LIBCLANG_PATH='$user_libclang' (ignored after search failed)." >&2 - fi - echo " Install LLVM/Clang development packages, then re-run vm:setup:" >&2 - echo " Debian/Ubuntu: sudo apt-get install -y libclang-dev" >&2 - echo " Fedora/RHEL: sudo dnf install -y clang-devel" >&2 - echo " Then unset LIBCLANG_PATH or set it to a directory that contains libclang.so." >&2 - exit 1 -} - -echo "" -echo "==> Building libkrun..." - -ensure_cargo_for_libkrun -ensure_libclang_for_libkrun - -if [ ! -d libkrun ]; then - echo " Cloning libkrun..." - git clone https://github.com/libkrun/libkrun.git -fi - -cd libkrun - -echo " Checking out pinned ref: ${LIBKRUN_REF}" -git fetch origin "${LIBKRUN_REF}" 2>/dev/null || git fetch origin -git checkout "${LIBKRUN_REF}" 2>/dev/null || git checkout "origin/${LIBKRUN_REF}" 2>/dev/null || { - echo "Error: could not check out LIBKRUN_REF=${LIBKRUN_REF} in $(pwd) (dirty tree or unknown ref?)" >&2 - exit 1 -} - -echo " Building libkrun with NET=1 BLK=1..." -cargo build --release --features blk --features net --target-dir="$(pwd)/target" - -# Copy output -cp target/release/libkrun.so "$OUTPUT_DIR/" -echo " Built: libkrun.so" - -cd "$BUILD_DIR" - -# ── Summary ───────────────────────────────────────────────────────────── - -echo "" -echo "==> Build complete!" -echo " Output directory: ${OUTPUT_DIR}" -echo "" -echo " Artifacts:" -ls -lah "$OUTPUT_DIR"/*.so* - -echo "" -echo "Next step: mise run vm:supervisor && cargo build -p openshell-driver-vm" diff --git a/tasks/scripts/vm/build-supervisor-bundle.sh b/tasks/scripts/vm/build-supervisor-bundle.sh deleted file mode 100755 index ced808fff3..0000000000 --- a/tasks/scripts/vm/build-supervisor-bundle.sh +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -set -euo pipefail - -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" -OUTPUT_DIR="${OPENSHELL_VM_RUNTIME_COMPRESSED_DIR:-${ROOT}/target/vm-runtime-compressed}" - -# shellcheck source=tasks/scripts/build-env.sh -source "${ROOT}/tasks/scripts/build-env.sh" - -GUEST_ARCH="" -while [[ $# -gt 0 ]]; do - case "$1" in - --arch) - GUEST_ARCH="$2" - shift 2 - ;; - --arch=*) - GUEST_ARCH="${1#--arch=}" - shift - ;; - --help|-h) - echo "Usage: $0 [--arch aarch64|x86_64]" - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2 - exit 1 - ;; - esac -done - -if [ -z "${GUEST_ARCH}" ]; then - case "$(uname -m)" in - aarch64|arm64) GUEST_ARCH="aarch64" ;; - x86_64|amd64) GUEST_ARCH="x86_64" ;; - *) - echo "ERROR: Unsupported host architecture: $(uname -m)" >&2 - echo " Use --arch aarch64 or --arch x86_64 to override." >&2 - exit 1 - ;; - esac -fi - -case "${GUEST_ARCH}" in - aarch64|arm64) - SANDBOX_RUST_TARGET="aarch64-unknown-linux-musl" - ;; - x86_64|amd64) - SANDBOX_RUST_TARGET="x86_64-unknown-linux-musl" - ;; - *) - echo "ERROR: Unsupported guest architecture: ${GUEST_ARCH}" >&2 - echo " Supported: aarch64, x86_64" >&2 - exit 1 - ;; -esac - -SUPERVISOR_BIN="${ROOT}/target/${SANDBOX_RUST_TARGET}/release/openshell-sandbox" -SUPERVISOR_OUTPUT="${OUTPUT_DIR}/openshell-sandbox.zst" -VM_INIT_BIN="${ROOT}/target/${SANDBOX_RUST_TARGET}/release/openshell-vm-init" -VM_INIT_OUTPUT="${OUTPUT_DIR}/openshell-vm-init.zst" -HOST_SUPERVISOR_BIN="${ROOT}/target/release/openshell-supervisor" -HOST_SUPERVISOR_OUTPUT="${OUTPUT_DIR}/openshell-supervisor.zst" - -echo "==> Building openshell-sandbox supervisor bundle" -echo " Guest arch: ${GUEST_ARCH}" -echo " Sandbox target: ${SANDBOX_RUST_TARGET} (static musl)" -echo " Host supervisor target: native" -echo " Output: ${SUPERVISOR_OUTPUT}" - -mkdir -p "${OUTPUT_DIR}" -ensure_build_nofile_limit - -SUPERVISOR_BUILD_LOG="$(mktemp -t openshell-supervisor-build.XXXXXX.log)" -run_supervisor_build() { - local rustc_wrapper_mode="${1:-default}" - local cargo_prefix=() - - if [ "${rustc_wrapper_mode}" = "without-rustc-wrapper" ]; then - cargo_prefix=(env -u RUSTC_WRAPPER) - fi - - if command -v cargo-zigbuild >/dev/null 2>&1; then - ${cargo_prefix[@]+"${cargo_prefix[@]}"} cargo zigbuild --release -p openshell-sandbox --target "${SANDBOX_RUST_TARGET}" \ - --manifest-path "${ROOT}/Cargo.toml" - ${cargo_prefix[@]+"${cargo_prefix[@]}"} cargo zigbuild --release -p openshell-driver-vm --bin openshell-vm-init --no-default-features --target "${SANDBOX_RUST_TARGET}" \ - --manifest-path "${ROOT}/Cargo.toml" - else - echo " cargo-zigbuild not found, falling back to cargo build..." - ${cargo_prefix[@]+"${cargo_prefix[@]}"} cargo build --release -p openshell-sandbox --target "${SANDBOX_RUST_TARGET}" \ - --manifest-path "${ROOT}/Cargo.toml" - ${cargo_prefix[@]+"${cargo_prefix[@]}"} cargo build --release -p openshell-driver-vm --bin openshell-vm-init --no-default-features --target "${SANDBOX_RUST_TARGET}" \ - --manifest-path "${ROOT}/Cargo.toml" - fi - ${cargo_prefix[@]+"${cargo_prefix[@]}"} cargo build --release -p openshell-supervisor \ - --manifest-path "${ROOT}/Cargo.toml" -} - -print_build_failure() { - echo "ERROR: supervisor build failed. Full output:" >&2 - cat "${SUPERVISOR_BUILD_LOG}" >&2 - echo " (log saved at ${SUPERVISOR_BUILD_LOG})" >&2 -} - -if run_supervisor_build >"${SUPERVISOR_BUILD_LOG}" 2>&1; then - tail -5 "${SUPERVISOR_BUILD_LOG}" - rm -f "${SUPERVISOR_BUILD_LOG}" -else - status=$? - if [ -n "${RUSTC_WRAPPER:-}" ] && grep -Eq 'sccache: encountered fatal error|Too many open files|os error 24' "${SUPERVISOR_BUILD_LOG}"; then - echo "WARNING: supervisor build failed through RUSTC_WRAPPER=${RUSTC_WRAPPER}; retrying without RUSTC_WRAPPER." >&2 - : >"${SUPERVISOR_BUILD_LOG}" - if run_supervisor_build without-rustc-wrapper >"${SUPERVISOR_BUILD_LOG}" 2>&1; then - tail -5 "${SUPERVISOR_BUILD_LOG}" - rm -f "${SUPERVISOR_BUILD_LOG}" - else - status=$? - print_build_failure - exit "${status}" - fi - else - print_build_failure - exit "${status}" - fi -fi - -if [ ! -f "${SUPERVISOR_BIN}" ] || [ ! -f "${VM_INIT_BIN}" ] || [ ! -f "${HOST_SUPERVISOR_BIN}" ]; then - echo "ERROR: sandbox, VM init, or supervisor binary not found after build" >&2 - exit 1 -fi - -if readelf -l "${SUPERVISOR_BIN}" 2>/dev/null | grep -q 'Requesting program interpreter'; then - echo "ERROR: VM guest openshell-sandbox must be statically linked" >&2 - exit 1 -fi -if readelf -l "${VM_INIT_BIN}" 2>/dev/null | grep -q 'Requesting program interpreter'; then - echo "ERROR: openshell-vm-init must be statically linked" >&2 - exit 1 -fi - -zstd -19 -T0 -f "${SUPERVISOR_BIN}" -o "${SUPERVISOR_OUTPUT}" -zstd -19 -T0 -f "${VM_INIT_BIN}" -o "${VM_INIT_OUTPUT}" -zstd -19 -T0 -f "${HOST_SUPERVISOR_BIN}" -o "${HOST_SUPERVISOR_OUTPUT}" - -echo "==> Bundled supervisor ready" -echo " Binary: $(du -sh "${SUPERVISOR_BIN}" | cut -f1)" -echo " Compressed: $(du -sh "${SUPERVISOR_OUTPUT}" | cut -f1)" -echo " VM init: $(du -sh "${VM_INIT_OUTPUT}" | cut -f1)" diff --git a/tasks/scripts/vm/compress-vm-runtime.sh b/tasks/scripts/vm/compress-vm-runtime.sh deleted file mode 100755 index 2e5a76396d..0000000000 --- a/tasks/scripts/vm/compress-vm-runtime.sh +++ /dev/null @@ -1,298 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Gather VM runtime artifacts from local sources and compress for embedding. -# -# This script collects libkrun, libkrunfw, and the guest OCI unpacker -# from local sources or pinned releases and compresses them with zstd for -# embedding into the openshell-driver-vm binary. -# -# Usage: -# ./compress-vm-runtime.sh -# -# Environment: -# OPENSHELL_VM_RUNTIME_COMPRESSED_DIR - Output directory (default: target/vm-runtime-compressed) -# VM_RUNTIME_TARBALL - Path to a pre-built vm-runtime-*.tar.zst tarball. -# When set, the script extracts and re-compresses -# artifacts from this tarball instead of looking for -# local builds. Used by CI and download-kernel-runtime.sh. -# -# The script sets OPENSHELL_VM_RUNTIME_COMPRESSED_DIR for use by build.rs. - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -source "${SCRIPT_DIR}/_lib.sh" -ROOT="$(vm_lib_root)" - -# Source pins for runtime tool versions. -source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" - -# ── macOS dylib portability helpers ───────────────────────────────────── - -# Make a dylib portable by rewriting paths to use @loader_path -make_dylib_portable() { - local dylib="$1" - local dylib_name - dylib_name="$(basename "$dylib")" - - # Rewrite install name - install_name_tool -id "@loader_path/${dylib_name}" "$dylib" 2>/dev/null || true - - # Rewrite libkrunfw reference if present - local krunfw_path - krunfw_path=$(otool -L "$dylib" 2>/dev/null | grep libkrunfw | awk '{print $1}' || true) - if [ -n "$krunfw_path" ] && [[ "$krunfw_path" != @* ]]; then - install_name_tool -change "$krunfw_path" "@loader_path/libkrunfw.dylib" "$dylib" - fi - - # Re-codesign - codesign -f -s - "$dylib" 2>/dev/null || true -} - -WORK_DIR="${ROOT}/target/vm-runtime" -OUTPUT_DIR="${OPENSHELL_VM_RUNTIME_COMPRESSED_DIR:-${ROOT}/target/vm-runtime-compressed}" - -mkdir -p "$OUTPUT_DIR" - -download_umoci_for_guest() { - local output="$1" - local guest_arch="$2" - download_umoci_binary "$output" "${UMOCI_VERSION}" "$guest_arch" -} - -# ── Fast path: compressed artifacts already present (e.g. from vm:setup) ── - -_check_compressed_artifacts() { - local dir="$1" - local platform - platform="$(uname -s)-$(uname -m)" - case "$platform" in - Darwin-arm64) - for f in libkrun.dylib.zst libkrunfw.5.dylib.zst umoci.zst; do - [ -f "${dir}/${f}" ] || return 1 - done - ;; - Linux-*) - for f in libkrun.so.zst libkrunfw.so.5.zst umoci.zst; do - [ -f "${dir}/${f}" ] || return 1 - done - ;; - *) return 1 ;; - esac - return 0 -} - -if [ -z "${VM_RUNTIME_TARBALL:-}" ] && _check_compressed_artifacts "$OUTPUT_DIR"; then - echo "==> Compressed artifacts already present in ${OUTPUT_DIR} — skipping compression." - ls -lah "$OUTPUT_DIR" - - # Decompress artifacts into WORK_DIR for local inspection. - echo "" - echo "==> Decompressing artifacts into ${WORK_DIR} for runtime bundle..." - rm -rf "$WORK_DIR" - mkdir -p "$WORK_DIR" - for f in "${OUTPUT_DIR}"/*.zst; do - [ -f "$f" ] || continue - [ -s "$f" ] || continue - name="$(basename "${f%.zst}")" - [[ "$name" == rootfs*.tar ]] && continue - zstd -d "$f" -o "${WORK_DIR}/${name}" -f -q - chmod 0755 "${WORK_DIR}/${name}" - done - echo " Decompressed files:" - ls -lah "$WORK_DIR" - - echo "" - echo "Next step: mise run vm:supervisor && cargo build -p openshell-driver-vm" - exit 0 -fi - -rm -rf "$WORK_DIR" -mkdir -p "$WORK_DIR" - -# ── Fast path: pre-built tarball from CI or download-kernel-runtime.sh ── - -if [ -n "${VM_RUNTIME_TARBALL:-}" ]; then - echo "==> Using pre-built runtime tarball: ${VM_RUNTIME_TARBALL}" - - if [ ! -f "${VM_RUNTIME_TARBALL}" ]; then - echo "Error: VM_RUNTIME_TARBALL not found: ${VM_RUNTIME_TARBALL}" >&2 - exit 1 - fi - - # Extract tarball contents - zstd -d "${VM_RUNTIME_TARBALL}" --stdout | tar -xf - -C "$WORK_DIR" - - VM_RUNTIME_PLATFORM="${VM_RUNTIME_PLATFORM:-}" - if [ -z "$VM_RUNTIME_PLATFORM" ]; then - case "$(basename "$VM_RUNTIME_TARBALL")" in - vm-runtime-darwin-aarch64.tar.zst) VM_RUNTIME_PLATFORM="darwin-aarch64" ;; - vm-runtime-linux-aarch64.tar.zst) VM_RUNTIME_PLATFORM="linux-aarch64" ;; - vm-runtime-linux-x86_64.tar.zst) VM_RUNTIME_PLATFORM="linux-x86_64" ;; - esac - fi - if [ ! -f "${WORK_DIR}/umoci" ]; then - if [ -z "$VM_RUNTIME_PLATFORM" ]; then - echo "Error: VM_RUNTIME_TARBALL has no umoci and platform could not be inferred." >&2 - echo " Set VM_RUNTIME_PLATFORM to linux-aarch64, linux-x86_64, or darwin-aarch64." >&2 - exit 1 - fi - ensure_umoci_for_platform "$WORK_DIR" "$VM_RUNTIME_PLATFORM" "$UMOCI_VERSION" - fi - - echo " Extracted files:" - ls -lah "$WORK_DIR" - - echo "" - compress_dir "$WORK_DIR" "$OUTPUT_DIR" - - # Check for rootfs tarball (built separately) - ROOTFS_TARBALL="${OUTPUT_DIR}/rootfs.tar.zst" - if [ -f "$ROOTFS_TARBALL" ]; then - echo " rootfs.tar.zst: $(du -h "$ROOTFS_TARBALL" | cut -f1) (pre-built)" - else - echo "" - echo "Note: rootfs.tar.zst not found." - echo " openshell-driver-vm does not embed a standalone rootfs." - fi - - echo "" - echo "==> Compressed artifacts in ${OUTPUT_DIR}:" - ls -lah "$OUTPUT_DIR" - TOTAL=$(du -sh "$OUTPUT_DIR" | cut -f1) - echo "" - echo "==> Total compressed size: ${TOTAL}" - echo "" - echo "Next step: mise run vm:supervisor && cargo build -p openshell-driver-vm" - exit 0 -fi - -echo "==> Detecting platform..." - -case "$(uname -s)-$(uname -m)" in - Darwin-arm64) - PLATFORM="darwin-aarch64" - echo " Platform: macOS ARM64" - - # Source priority for libkrun: - # 1. Custom build from build-libkrun-macos.sh (portable, no GPU deps) - # 2. Custom runtime with custom libkrunfw - LIBKRUN_BUILD_DIR="${ROOT}/target/libkrun-build" - CUSTOM_DIR="${ROOT}/target/custom-runtime" - BREW_PREFIX="$(brew --prefix 2>/dev/null || echo /opt/homebrew)" - - if [ -f "${LIBKRUN_BUILD_DIR}/libkrun.dylib" ]; then - echo " Using portable libkrun from ${LIBKRUN_BUILD_DIR}" - cp "${LIBKRUN_BUILD_DIR}/libkrun.dylib" "$WORK_DIR/" - cp "${LIBKRUN_BUILD_DIR}/libkrunfw.dylib" "$WORK_DIR/" - - # Verify portability - if otool -L "${LIBKRUN_BUILD_DIR}/libkrun.dylib" | grep -q "/opt/homebrew"; then - echo " Warning: libkrun has hardcoded Homebrew paths - may not be portable" - else - echo " ✓ libkrun is portable (no hardcoded paths)" - fi - elif [ -f "${CUSTOM_DIR}/provenance.json" ]; then - echo " Using custom runtime from ${CUSTOM_DIR}" - - # libkrun from Homebrew (needs path rewriting for portability) - if [ -f "${CUSTOM_DIR}/libkrun.dylib" ]; then - cp "${CUSTOM_DIR}/libkrun.dylib" "$WORK_DIR/" - else - cp "${BREW_PREFIX}/lib/libkrun.dylib" "$WORK_DIR/" - make_dylib_portable "$WORK_DIR/libkrun.dylib" - fi - - # libkrunfw from custom build - cp "${CUSTOM_DIR}/libkrunfw.dylib" "$WORK_DIR/" - else - echo "Error: No portable libkrun build found." >&2 - echo " Run: FROM_SOURCE=1 mise run vm:setup" >&2 - exit 1 - fi - - # Normalize libkrunfw naming - ensure both names exist for build.rs - # build.rs expects libkrunfw.5.dylib.zst; some builds produce libkrunfw.dylib - if [ ! -f "$WORK_DIR/libkrunfw.dylib" ] && [ -f "$WORK_DIR/libkrunfw.5.dylib" ]; then - cp "$WORK_DIR/libkrunfw.5.dylib" "$WORK_DIR/libkrunfw.dylib" - fi - if [ ! -f "$WORK_DIR/libkrunfw.5.dylib" ] && [ -f "$WORK_DIR/libkrunfw.dylib" ]; then - cp "$WORK_DIR/libkrunfw.dylib" "$WORK_DIR/libkrunfw.5.dylib" - fi - - download_umoci_for_guest "$WORK_DIR/umoci" "arm64" - ;; - - Linux-*) - ARCH="$(uname -m)" - case "$ARCH" in - aarch64|x86_64) ;; - *) - echo "Error: Unsupported Linux architecture: ${ARCH}" >&2 - exit 1 - ;; - esac - PLATFORM="linux-${ARCH}" - echo " Platform: Linux ${ARCH}" - - BUILD_DIR="${ROOT}/target/libkrun-build" - if [ ! -f "${BUILD_DIR}/libkrun.so" ]; then - echo "Error: libkrun not found. Run: FROM_SOURCE=1 mise run vm:setup" >&2 - exit 1 - fi - - cp "${BUILD_DIR}/libkrun.so" "$WORK_DIR/" - - # Copy libkrunfw - find the versioned .so file - for krunfw in "${BUILD_DIR}"/libkrunfw.so*; do - [ -f "$krunfw" ] || continue - cp "$krunfw" "$WORK_DIR/" - done - - # Ensure the soname symlink (libkrunfw.so.5) exists alongside the fully - # versioned file (libkrunfw.so.5.x.y). libloading loads by soname. - if [ ! -f "$WORK_DIR/libkrunfw.so.5" ]; then - versioned=$(ls "$WORK_DIR"/libkrunfw.so.5.* 2>/dev/null | head -n1) - if [ -n "$versioned" ]; then - cp "$versioned" "$WORK_DIR/libkrunfw.so.5" - fi - fi - - download_umoci_for_guest "$WORK_DIR/umoci" "$ARCH" - ;; - - *) - echo "Error: Unsupported platform: $(uname -s)-$(uname -m)" >&2 - echo "Supported platforms: Darwin-arm64, Linux-aarch64, Linux-x86_64" >&2 - exit 1 - ;; -esac - -echo "" -echo "==> Collected artifacts:" -ls -lah "$WORK_DIR" - -echo "" -compress_dir "$WORK_DIR" "$OUTPUT_DIR" - -# Check for rootfs tarball (built separately by build-rootfs-tarball.sh) -ROOTFS_TARBALL="${OUTPUT_DIR}/rootfs.tar.zst" -if [ -f "$ROOTFS_TARBALL" ]; then - echo " rootfs.tar.zst: $(du -h "$ROOTFS_TARBALL" | cut -f1) (pre-built)" -else - echo "" - echo "Note: rootfs.tar.zst not found." - echo " openshell-driver-vm does not embed a standalone rootfs." -fi - -echo "" -echo "==> Compressed artifacts in ${OUTPUT_DIR}:" -ls -lah "$OUTPUT_DIR" - -TOTAL=$(du -sh "$OUTPUT_DIR" | cut -f1) -echo "" -echo "==> Total compressed size: ${TOTAL}" -echo "" -echo "Next step: mise run vm:supervisor && cargo build -p openshell-driver-vm" diff --git a/tasks/scripts/vm/download-kernel-runtime.sh b/tasks/scripts/vm/download-kernel-runtime.sh deleted file mode 100755 index 1b2b27b631..0000000000 --- a/tasks/scripts/vm/download-kernel-runtime.sh +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Download pre-built VM kernel runtime artifacts from the capability-free -# vm-runtime GitHub -# Release and stage them for the openshell-driver-vm cargo build. -# -# This script is used by driver release CI and can also be used locally -# to avoid building libkrun/libkrunfw from source. -# -# Usage: -# ./download-kernel-runtime.sh [--platform PLATFORM] -# -# Environment: -# VM_RUNTIME_RELEASE_TAG - GitHub Release tag (default: vm-runtime) -# GITHUB_REPOSITORY - owner/repo (default: ai-openshell/openshell) -# OPENSHELL_VM_RUNTIME_COMPRESSED_DIR - Output directory (default: target/vm-runtime-compressed) -# -# Platforms: linux-aarch64, linux-x86_64, darwin-aarch64 - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -source "${SCRIPT_DIR}/_lib.sh" -ROOT="$(vm_lib_root)" -source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" - -RELEASE_TAG="${VM_RUNTIME_RELEASE_TAG:-vm-runtime}" -REPO="${GITHUB_REPOSITORY:-ai-openshell/openshell}" -OUTPUT_DIR="${OPENSHELL_VM_RUNTIME_COMPRESSED_DIR:-${ROOT}/target/vm-runtime-compressed}" - -# ── Auto-detect platform (detect_platform from _lib.sh) ───────────────── - -PLATFORM="" -while [[ $# -gt 0 ]]; do - case "$1" in - --platform) - PLATFORM="$2"; shift 2 ;; - --help|-h) - echo "Usage: $0 [--platform PLATFORM]" - echo "" - echo "Download pre-built VM kernel runtime from the vm-runtime GitHub Release." - echo "" - echo "Platforms: linux-aarch64, linux-x86_64, darwin-aarch64" - echo "" - echo "Environment:" - echo " VM_RUNTIME_RELEASE_TAG Release tag (default: vm-runtime)" - echo " GITHUB_REPOSITORY owner/repo (default: ai-openshell/openshell)" - echo " OPENSHELL_VM_RUNTIME_COMPRESSED_DIR Output directory" - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2; exit 1 ;; - esac -done - -if [ -z "$PLATFORM" ]; then - PLATFORM="$(detect_platform)" -fi - -TARBALL_NAME="vm-runtime-${PLATFORM}.tar.zst" - -echo "==> Downloading VM kernel runtime" -echo " Repository: ${REPO}" -echo " Release: ${RELEASE_TAG}" -echo " Platform: ${PLATFORM}" -echo " Artifact: ${TARBALL_NAME}" -echo " Output: ${OUTPUT_DIR}" -echo "" - -# ── Check for gh CLI ──────────────────────────────────────────────────── - -if ! command -v gh &>/dev/null; then - echo "Error: GitHub CLI (gh) is required." >&2 - echo " Install: https://cli.github.com/" >&2 - exit 1 -fi - -# ── Download the runtime tarball ──────────────────────────────────────── - -DOWNLOAD_DIR="${ROOT}/target/vm-runtime-download" -mkdir -p "$DOWNLOAD_DIR" "$OUTPUT_DIR" - -echo "==> Downloading ${TARBALL_NAME} from ${RELEASE_TAG}..." -gh release download "${RELEASE_TAG}" \ - --repo "${REPO}" \ - --pattern "${TARBALL_NAME}" \ - --dir "${DOWNLOAD_DIR}" \ - --clobber - -if [ ! -f "${DOWNLOAD_DIR}/${TARBALL_NAME}" ]; then - echo "Error: Download failed — ${TARBALL_NAME} not found." >&2 - echo "" >&2 - echo "The vm-runtime release may not have kernel runtime artifacts yet." >&2 - echo "Run the 'Release VM Kernel' workflow first:" >&2 - echo " gh workflow run release-vm-kernel.yml" >&2 - exit 1 -fi - -echo " Downloaded: $(du -sh "${DOWNLOAD_DIR}/${TARBALL_NAME}" | cut -f1)" - -# ── Extract and stage for cargo build ─────────────────────────────────── - -echo "" -echo "==> Extracting runtime artifacts..." - -EXTRACT_DIR="${ROOT}/target/vm-runtime-extracted" -rm -rf "$EXTRACT_DIR" -mkdir -p "$EXTRACT_DIR" - -zstd -d "${DOWNLOAD_DIR}/${TARBALL_NAME}" --stdout | tar -xf - -C "$EXTRACT_DIR" - -ensure_umoci_for_platform "$EXTRACT_DIR" "$PLATFORM" "$UMOCI_VERSION" - -echo " Extracted files:" -ls -lah "$EXTRACT_DIR" - -# ── Compress individual files for embedding ───────────────────────────── -# The cargo build expects individual .zst files (libkrun.so.zst, etc.) -# in OPENSHELL_VM_RUNTIME_COMPRESSED_DIR. The downloaded tarball contains -# the raw libraries, so we re-compress each one. - -echo "" -compress_dir "$EXTRACT_DIR" "$OUTPUT_DIR" - -echo "" -echo "==> Staged artifacts in ${OUTPUT_DIR}:" -ls -lah "$OUTPUT_DIR" - -echo "" -echo "==> Done." -echo "" -echo "Next step: mise run vm:supervisor && cargo build -p openshell-driver-vm" diff --git a/tasks/scripts/vm/package-vm-runtime.sh b/tasks/scripts/vm/package-vm-runtime.sh deleted file mode 100755 index e3c8a10df6..0000000000 --- a/tasks/scripts/vm/package-vm-runtime.sh +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Package VM runtime artifacts into a release tarball. -# -# Used by CI (release-vm-kernel.yml) to bundle libkrun, libkrunfw, and the -# guest OCI unpacker into a platform-specific tarball for the -# vm-runtime GitHub Release. Handles tool downloads, provenance metadata -# generation, and tarball creation. -# -# Usage: -# ./package-vm-runtime.sh --platform --build-dir --output -# -# Arguments: -# --platform One of: linux-aarch64, linux-x86_64, darwin-aarch64 -# --build-dir Directory containing built libkrun and libkrunfw artifacts -# --output Path for the output .tar.zst file -# -# Environment (optional, for provenance): -# GITHUB_SHA - Git commit SHA -# GITHUB_RUN_ID - GitHub Actions run ID -# CUSTOM_PROVENANCE_DIR - Directory containing the provenance.json written by -# build-libkrun.sh, when it is not in --build-dir -# (macOS reuses the Linux ARM64 kernel build) - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -source "${SCRIPT_DIR}/_lib.sh" -ROOT="$(vm_lib_root)" - -# Source pins for runtime tool versions. -source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" - -PLATFORM="" -BUILD_DIR="" -OUTPUT="" -CUSTOM_PROVENANCE_DIR="${CUSTOM_PROVENANCE_DIR:-}" - -while [[ $# -gt 0 ]]; do - case "$1" in - --platform) PLATFORM="$2"; shift 2 ;; - --build-dir) BUILD_DIR="$2"; shift 2 ;; - --output) OUTPUT="$2"; shift 2 ;; - --help|-h) - echo "Usage: $0 --platform --build-dir --output " - echo "" - echo "Package VM runtime artifacts into a release tarball." - echo "" - echo "Platforms: linux-aarch64, linux-x86_64, darwin-aarch64" - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2; exit 1 ;; - esac -done - -if [ -z "$PLATFORM" ] || [ -z "$BUILD_DIR" ] || [ -z "$OUTPUT" ]; then - echo "Error: --platform, --build-dir, and --output are all required" >&2 - exit 1 -fi - -echo "==> Packaging VM runtime" -echo " Platform: ${PLATFORM}" -echo " Build dir: ${BUILD_DIR}" -echo " Output: ${OUTPUT}" -echo "" - -# ── Create staging directory ──────────────────────────────────────────── - -PACKAGE_DIR="$(mktemp -d)" -trap 'rm -rf "$PACKAGE_DIR"' EXIT - -# ── Copy runtime libraries ────────────────────────────────────────────── - -case "$PLATFORM" in - linux-*) - cp "${BUILD_DIR}/libkrun.so" "${PACKAGE_DIR}/" - # Copy libkrunfw — find versioned .so and create soname symlink - for f in "${BUILD_DIR}"/libkrunfw.so*; do - [ -f "$f" ] && cp "$f" "${PACKAGE_DIR}/" - done - if [ ! -f "${PACKAGE_DIR}/libkrunfw.so.5" ]; then - versioned="$(ls "${PACKAGE_DIR}"/libkrunfw.so.5.* 2>/dev/null | head -n1 || true)" - [ -n "$versioned" ] && cp "$versioned" "${PACKAGE_DIR}/libkrunfw.so.5" - fi - ;; - darwin-aarch64) - cp "${BUILD_DIR}/libkrun.dylib" "${PACKAGE_DIR}/" - # libkrunfw — prefer build dir, fall back to custom runtime dir - candidates=("${BUILD_DIR}/libkrunfw.dylib" "${BUILD_DIR}/libkrunfw.5.dylib") - if [ -n "$CUSTOM_PROVENANCE_DIR" ]; then - candidates+=("${CUSTOM_PROVENANCE_DIR}/libkrunfw.dylib" "${CUSTOM_PROVENANCE_DIR}/libkrunfw.5.dylib") - fi - for candidate in "${candidates[@]}"; do - if [ -f "$candidate" ]; then - cp "$candidate" "${PACKAGE_DIR}/" - fi - done - ;; - *) - echo "Error: Unknown platform: ${PLATFORM}" >&2 - exit 1 - ;; -esac - - -# ── Download umoci for the Linux guest ─────────────────────────────────── - -echo "==> Downloading umoci ${UMOCI_VERSION} for ${PLATFORM} guest..." -UMOCI_GUEST_ARCH="" -case "$PLATFORM" in - linux-aarch64|darwin-aarch64) UMOCI_GUEST_ARCH="arm64" ;; - linux-x86_64) UMOCI_GUEST_ARCH="amd64" ;; -esac - -download_umoci_binary "${PACKAGE_DIR}/umoci" "${UMOCI_VERSION}" "${UMOCI_GUEST_ARCH}" - -# ── Write provenance metadata ─────────────────────────────────────────── - -echo "==> Writing provenance metadata..." - -if ! command -v jq &>/dev/null; then - echo "Error: jq is required for provenance generation" >&2 - exit 1 -fi - -# Kernel inputs come from the provenance.json written by build-libkrun.sh, -# in the build dir or, for macOS, the directory holding the Linux kernel.c. -KERNEL_PROVENANCE="${CUSTOM_PROVENANCE_DIR:-${BUILD_DIR}}/provenance.json" -kernel_field() { - jq -r --arg k "$1" '.[$k] // "unknown"' "$KERNEL_PROVENANCE" 2>/dev/null || echo unknown -} - -jq -n \ - --arg artifact "vm-runtime" \ - --arg platform "$PLATFORM" \ - --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ - --arg kfw_commit "$(kernel_field libkrunfw_commit)" \ - --arg kver "$(kernel_field kernel_version)" \ - --arg kcfg "$(kernel_field kernel_config_sha256)" \ - --arg umoci "$UMOCI_VERSION" \ - --arg sha "${GITHUB_SHA:-unknown}" \ - --arg run "${GITHUB_RUN_ID:-unknown}" \ - '{artifact: $artifact, platform: $platform, build_timestamp: $ts, libkrunfw_commit: $kfw_commit, kernel_version: $kver, kernel_config_sha256: $kcfg, umoci_version: $umoci, github_sha: $sha, github_run_id: $run}' \ - > "${PACKAGE_DIR}/provenance.json" - -# ── Create tarball ────────────────────────────────────────────────────── - -echo "==> Creating tarball..." -mkdir -p "$(dirname "$OUTPUT")" -tar -C "${PACKAGE_DIR}" -cf - . | zstd -19 -T0 -o "$OUTPUT" - -echo "" -echo "==> Packaged ${OUTPUT} ($(du -sh "$OUTPUT" | cut -f1))" -echo " Contents:" -ls -lah "${PACKAGE_DIR}" diff --git a/tasks/scripts/vm/smoke-orphan-cleanup.sh b/tasks/scripts/vm/smoke-orphan-cleanup.sh deleted file mode 100755 index 2024ce375e..0000000000 --- a/tasks/scripts/vm/smoke-orphan-cleanup.sh +++ /dev/null @@ -1,207 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 -# -# Smoke test: start the gateway with the VM driver, create a sandbox, then -# signal the gateway (SIGTERM then SIGKILL) and verify that no driver, -# launcher or libkrun worker processes survive. -# -# Exit codes: -# 0 — both SIGTERM and SIGKILL cleanup passed -# 1 — one or more scenarios leaked survivors - -set -euo pipefail - -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" -cd "$ROOT" - -PORT="${OPENSHELL_SERVER_PORT:-8091}" -XDG="${TMPDIR:-/tmp}/vm-orphan-xdg-$$" -STATE_DIR="${TMPDIR:-/tmp}/openshell-vm-orphan-$$" -LOG="${TMPDIR:-/tmp}/vm-orphan-$$.log" - -cleanup_stray() { - # Best-effort: kill anything left over from our sandbox ids so repeated - # runs don't accumulate. - pkill -9 -f "openshell-vm-orphan-$$" 2>/dev/null || true - rm -rf "$XDG" "$STATE_DIR" 2>/dev/null || true - # Preserve the gateway log only on failure so operators can diagnose. - if [ "${EXIT_CODE:-0}" -ne 0 ]; then - echo "(log preserved at $LOG)" >&2 - else - rm -f "$LOG" "$LOG.create" 2>/dev/null || true - fi -} -trap cleanup_stray EXIT - -build_binaries() { - echo "==> Ensuring binaries are built" - if [ ! -x "$ROOT/target/debug/openshell-gateway" ] || [ ! -x "$ROOT/target/debug/openshell-driver-vm" ]; then - cargo build -p openshell-gateway -p openshell-driver-vm >&2 - fi - if [ "$(uname -s)" = "Darwin" ]; then - codesign \ - --entitlements "$ROOT/crates/openshell-driver-vm/entitlements.plist" \ - --force -s - \ - "$ROOT/target/debug/openshell-driver-vm" >/dev/null 2>&1 || true - fi -} - -start_gateway() { - local health_port=$((PORT + 1)) - local config="$STATE_DIR/gateway.toml" - echo "==> Starting gateway on port $PORT (state=$STATE_DIR, health=$health_port)" - mkdir -p "$STATE_DIR" - cat >"$config" < "$LOG" 2>&1 & - GATEWAY_PID=$! - echo "gateway pid=$GATEWAY_PID" - - for _ in $(seq 1 60); do - if curl -sf --connect-timeout 1 \ - "http://127.0.0.1:${health_port}/healthz" >/dev/null 2>&1; then - return 0 - fi - if ! kill -0 "$GATEWAY_PID" 2>/dev/null; then - echo "!! gateway died before ready" - tail -40 "$LOG" >&2 - return 1 - fi - sleep 1 - done - echo "!! gateway health endpoint never became healthy" - tail -40 "$LOG" >&2 - return 1 -} - -create_sandbox() { - echo "==> Creating sandbox (long-running)" - mkdir -p "$XDG" - XDG_CONFIG_HOME="$XDG" "$ROOT/scripts/bin/openshell" gateway add \ - --name vm-orphan http://127.0.0.1:"$PORT" >/dev/null - XDG_CONFIG_HOME="$XDG" "$ROOT/scripts/bin/openshell" gateway select vm-orphan >/dev/null - - # Run the CLI in the background; it blocks waiting for sleep to finish. - XDG_CONFIG_HOME="$XDG" "$ROOT/scripts/bin/openshell" sandbox create \ - --name "orphan-$$" -- sleep 99999 \ - > "$LOG.create" 2>&1 & - CLI_PID=$! - - for _ in $(seq 1 60); do - if pgrep -f "openshell-vm-orphan-$$|$STATE_DIR/sandboxes/" >/dev/null 2>&1; then - echo "sandbox came up (cli pid=$CLI_PID)" - return 0 - fi - sleep 2 - done - echo "!! sandbox never came up" - tail -40 "$LOG" "$LOG.create" >&2 2>/dev/null || true - return 1 -} - -snapshot_kids() { - # Return all PIDs whose --state-dir or --vm-rootfs references our - # per-run directory. - pgrep -fl "state-dir $STATE_DIR|$STATE_DIR/sandboxes" 2>/dev/null || true -} - -count_alive() { - local alive - alive=$(pgrep -f "state-dir $STATE_DIR|$STATE_DIR/sandboxes" 2>/dev/null | wc -l | tr -d ' ') - echo "$alive" -} - -verify_cleanup() { - local label="$1" - local deadline="$2" - local waited=0 - while [ "$waited" -lt "$deadline" ]; do - local n - n=$(count_alive) - if [ "$n" = "0" ]; then - echo " PASS ($label): all descendants gone after ${waited}s" - return 0 - fi - sleep 1 - waited=$((waited + 1)) - done - echo " FAIL ($label): $(count_alive) descendants still alive after ${deadline}s:" - snapshot_kids | sed 's/^/ /' - return 1 -} - -run_scenario() { - local signal="$1" - local label="$2" - echo "======================================================" - echo "Scenario: $label (signal $signal)" - echo "======================================================" - - start_gateway || return 1 - create_sandbox || { kill -9 "$GATEWAY_PID" 2>/dev/null; return 1; } - - echo "-- process tree before signal --" - snapshot_kids | sed 's/^/ /' - echo - - echo "-> kill -$signal $GATEWAY_PID" - kill "-$signal" "$GATEWAY_PID" 2>/dev/null || true - - verify_cleanup "$label" 15 - local rc=$? - - # Belt-and-braces teardown between scenarios. - pkill -9 -f "$STATE_DIR/sandboxes|$STATE_DIR " 2>/dev/null || true - rm -rf "$STATE_DIR" "$XDG" 2>/dev/null || true - # CLI may still be running; reap it. - kill "${CLI_PID:-0}" 2>/dev/null || true - sleep 1 - - return $rc -} - -main() { - build_binaries - local overall=0 - - # Clean starting state. - pkill -9 -f 'openshell-gateway|openshell-driver-vm' 2>/dev/null || true - sleep 1 - - if ! run_scenario TERM "graceful SIGTERM"; then - overall=1 - fi - - if ! run_scenario KILL "abrupt SIGKILL"; then - overall=1 - fi - - if [ "$overall" -eq 0 ]; then - echo "ALL SCENARIOS PASSED" - else - echo "ONE OR MORE SCENARIOS FAILED" - fi - EXIT_CODE=$overall - return $overall -} - -main "$@" diff --git a/tasks/scripts/vm/vm-setup.sh b/tasks/scripts/vm/vm-setup.sh deleted file mode 100755 index 4b6bb297b3..0000000000 --- a/tasks/scripts/vm/vm-setup.sh +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env bash -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# One-time setup for the openshell-driver-vm runtime. -# -# Downloads pre-built runtime artifacts (libkrun, libkrunfw, umoci) -# from the vm-runtime GitHub Release, or builds them from source when -# --from-source is set. -# After obtaining the runtime, compresses the artifacts for embedding into the -# openshell-driver-vm binary. -# -# Usage: -# ./vm-setup.sh # download pre-built (default, ~30s) -# ./vm-setup.sh --from-source # build from source (~15-45min) -# -# Environment: -# FROM_SOURCE=1 - Equivalent to --from-source - -set -euo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -source "${SCRIPT_DIR}/_lib.sh" -ROOT="$(vm_lib_root)" -CLI_BIN="${ROOT}/scripts/bin/openshell" - -FROM_SOURCE="${FROM_SOURCE:-0}" - -while [[ $# -gt 0 ]]; do - case "$1" in - --from-source) - FROM_SOURCE=1 - shift - ;; - --help|-h) - echo "Usage: $0 [--from-source]" - echo "" - echo "Set up the openshell-driver-vm runtime (libkrun, libkrunfw, umoci)." - echo "" - echo "Options:" - echo " --from-source Build runtime from source instead of downloading (~15-45min)" - echo "" - echo "Environment:" - echo " FROM_SOURCE=1 Equivalent to --from-source" - exit 0 - ;; - *) - echo "Unknown argument: $1" >&2 - echo "Use --help for usage information" >&2 - exit 1 - ;; - esac -done - -PLATFORM="$(detect_platform)" -echo "==> openshell-driver-vm setup" -echo " Platform: ${PLATFORM}" -echo " Mode: $([ "$FROM_SOURCE" = "1" ] && echo "build from source" || echo "download pre-built")" -echo "" - -# ── Obtain runtime artifacts ──────────────────────────────────────────── - -if [ "$FROM_SOURCE" = "1" ]; then - echo "==> Building runtime from source..." - echo "" - - case "$PLATFORM" in - darwin-aarch64) - # macOS: compile pre-built kernel.c into libkrunfw.dylib, then build libkrun.dylib. - # The kernel.c file must be obtained from a Linux ARM64 build first. - KERNEL_DIR="${ROOT}/target/libkrun-build" - if [ ! -f "${KERNEL_DIR}/kernel.c" ]; then - echo "Error: kernel.c not found at ${KERNEL_DIR}/kernel.c" >&2 - echo "" >&2 - echo "On macOS, the Linux kernel must be cross-compiled on a Linux host first." >&2 - echo "Either:" >&2 - echo " 1. Download pre-built runtime (default): mise run vm:setup" >&2 - echo " 2. Build kernel.c on Linux, copy to ${KERNEL_DIR}/, then re-run." >&2 - exit 1 - fi - "${ROOT}/tasks/scripts/vm/build-libkrun-macos.sh" --kernel-dir "${KERNEL_DIR}" - ;; - linux-*) - # Linux: build both libkrunfw and libkrun in one go - "${ROOT}/tasks/scripts/vm/build-libkrun.sh" - ;; - esac - echo "" - echo "==> Compressing runtime artifacts for embedding..." - "${ROOT}/tasks/scripts/vm/compress-vm-runtime.sh" -else - echo "==> Downloading pre-built runtime..." - "${ROOT}/tasks/scripts/vm/download-kernel-runtime.sh" -fi - -# ── Validate ──────────────────────────────────────────────────────────── - -OUTPUT_DIR="${OPENSHELL_VM_RUNTIME_COMPRESSED_DIR:-${ROOT}/target/vm-runtime-compressed}" - -# Check that we have the essential compressed artifacts -missing=0 -case "$PLATFORM" in - darwin-aarch64) - for f in libkrun.dylib.zst libkrunfw.5.dylib.zst umoci.zst; do - if [ ! -f "${OUTPUT_DIR}/${f}" ]; then - echo "ERROR: Missing ${OUTPUT_DIR}/${f}" >&2 - missing=1 - fi - done - ;; - linux-aarch64|linux-x86_64) - for f in libkrun.so.zst libkrunfw.so.5.zst umoci.zst; do - if [ ! -f "${OUTPUT_DIR}/${f}" ]; then - echo "ERROR: Missing ${OUTPUT_DIR}/${f}" >&2 - missing=1 - fi - done - ;; -esac - -if [ "$missing" -eq 1 ]; then - echo "" >&2 - echo "Setup failed: some runtime artifacts are missing." >&2 - exit 1 -fi - -echo "" -echo "==> Setup complete!" -echo " Compressed artifacts in: ${OUTPUT_DIR}" -echo "" -echo "After starting the gateway:" -echo " ${CLI_BIN} status" -echo " ${CLI_BIN} sandbox create --name vm-test --from ubuntu:24.04" diff --git a/tasks/vm.toml b/tasks/vm.toml deleted file mode 100644 index 538168c14a..0000000000 --- a/tasks/vm.toml +++ /dev/null @@ -1,29 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# VM driver development tasks -# -# Workflow: -# mise run vm:setup # one-time: download pre-built runtime (~30s) -# mise run vm:supervisor # build the bundled sandbox supervisor -# mise run gateway:vm # start openshell-gateway with the VM driver -# # (defined in tasks/gateway.toml) -# -# See tasks/gateway.toml for `gateway:vm`, -# crates/openshell-driver-vm/README.md for the VM driver workflow. - -# ═══════════════════════════════════════════════════════════════════════════ -# Main Commands -# ═══════════════════════════════════════════════════════════════════════════ - -["vm:setup"] -description = "One-time setup: download (or build) the VM driver runtime" -run = "tasks/scripts/vm/vm-setup.sh" - -["vm:supervisor"] -description = "Build the bundled openshell-sandbox supervisor for openshell-driver-vm" -run = "tasks/scripts/vm/build-supervisor-bundle.sh" - -["vm:smoke:orphan-cleanup"] -description = "Smoke test: start gateway+driver, create a sandbox, signal the gateway, assert no orphaned processes survive" -run = "tasks/scripts/vm/smoke-orphan-cleanup.sh" From ef5b416ac2995e13fde1bcf9086275f4cba52478 Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Fri, 4 Dec 2026 14:02:33 +0100 Subject: [PATCH 2/2] chore: remove the Docker and Podman driver suites migrated to desktop Delete tests/suites/drivers/{docker,podman}, now in ai-openshell/desktop (tests/suites/drivers), and everything in core that names them: the fmt and clippy steps and tasks, the lockfile alignment entries, the drivers rows of e2e-suites.yml, the driver suite bundles and the driver-specific-integration job of Branch E2E, and the references in CI.md and the conformance suite's comments. Signed-off-by: Evan Lezar --- .github/workflows/branch-checks.yml | 4 - .github/workflows/branch-e2e.yml | 32 +- .github/workflows/e2e-suites.yml | 14 +- .github/workflows/rust-cache.yml | 2 +- CI.md | 10 +- e2e/rust/tests/local_driver_token_restart.rs | 3 +- tasks/rust.toml | 6 - .../scripts/check_cargo_lockfile_alignment.py | 2 - tests/suites/conformance/README.md | 4 +- tests/suites/conformance/src/lifecycle.rs | 2 +- tests/suites/drivers/docker/Cargo.lock | 4973 ---------------- tests/suites/drivers/docker/Cargo.toml | 24 - .../suites/drivers/docker/tests/lifecycle.rs | 117 - tests/suites/drivers/podman/Cargo.lock | 4984 ----------------- tests/suites/drivers/podman/Cargo.toml | 37 - .../suites/drivers/podman/tests/lifecycle.rs | 152 - .../drivers/podman/tests/oci_identity.rs | 98 - tests/suites/drivers/podman/tests/userns.rs | 68 - 18 files changed, 13 insertions(+), 10519 deletions(-) delete mode 100644 tests/suites/drivers/docker/Cargo.lock delete mode 100644 tests/suites/drivers/docker/Cargo.toml delete mode 100644 tests/suites/drivers/docker/tests/lifecycle.rs delete mode 100644 tests/suites/drivers/podman/Cargo.lock delete mode 100644 tests/suites/drivers/podman/Cargo.toml delete mode 100644 tests/suites/drivers/podman/tests/lifecycle.rs delete mode 100644 tests/suites/drivers/podman/tests/oci_identity.rs delete mode 100644 tests/suites/drivers/podman/tests/userns.rs diff --git a/.github/workflows/branch-checks.yml b/.github/workflows/branch-checks.yml index 411572ee33..a41cd8ed48 100644 --- a/.github/workflows/branch-checks.yml +++ b/.github/workflows/branch-checks.yml @@ -279,8 +279,6 @@ jobs: cargo fmt --manifest-path tests/runner/Cargo.toml --all -- --check cargo fmt --manifest-path tests/suites/conformance/Cargo.toml --all -- --check cargo fmt --manifest-path tests/suites/continuity/Cargo.toml --all -- --check - cargo fmt --manifest-path tests/suites/drivers/docker/Cargo.toml --all -- --check - cargo fmt --manifest-path tests/suites/drivers/podman/Cargo.toml --all -- --check cargo fmt --manifest-path tests/suites/features/Cargo.toml --all -- --check cargo fmt --manifest-path tests/support/Cargo.toml --all -- --check @@ -342,8 +340,6 @@ jobs: cargo clippy --locked --manifest-path tests/runner/Cargo.toml --all-targets -- -D warnings cargo clippy --locked --manifest-path tests/suites/conformance/Cargo.toml --workspace --all-targets -- -D warnings cargo clippy --locked --manifest-path tests/suites/continuity/Cargo.toml --workspace --all-targets -- -D warnings - cargo clippy --locked --manifest-path tests/suites/drivers/docker/Cargo.toml --workspace --all-targets -- -D warnings - cargo clippy --locked --manifest-path tests/suites/drivers/podman/Cargo.toml --workspace --all-targets -- -D warnings cargo clippy --locked --manifest-path tests/suites/features/Cargo.toml --workspace --all-targets -- -D warnings cargo clippy --locked --manifest-path tests/support/Cargo.toml --all-targets -- -D warnings diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 87d9a38db7..edfd553ad7 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -269,7 +269,7 @@ jobs: set -euo pipefail # Retry dependency preparation, then build once. nix build --no-link .#openshell-test-runner || nix build --no-link .#openshell-test-runner - for family in features drivers/docker drivers/podman; do + for family in features; do nix run .#openshell-test-runner -- build \ --family "$family" --out "artifacts/e2e-bundles/${family//\//-}" done @@ -279,18 +279,6 @@ jobs: path: artifacts/e2e-bundles/features retention-days: 5 if-no-files-found: error - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: openshell-e2e-bundle-drivers-docker-x86_64-unknown-linux-musl - path: artifacts/e2e-bundles/drivers-docker - retention-days: 5 - if-no-files-found: error - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: openshell-e2e-bundle-drivers-podman-x86_64-unknown-linux-musl - path: artifacts/e2e-bundles/drivers-podman - retention-days: 5 - if-no-files-found: error build-external-drivers: name: ${{ matrix.binary }} (${{ matrix.triple }}) @@ -487,23 +475,6 @@ jobs: secrets: CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }} - # Run the testkit driver suites (tests/suites/drivers) on tmachine. The - # environments and suites are listed in e2e-suites.yml. - driver-specific-integration: - needs: [prepare-integration, build-e2e-bundles] - permissions: - actions: read - contents: read - packages: read - uses: ./.github/workflows/e2e-suites.yml - with: - family: drivers - prebuilt: true - source-sha: ${{ needs.prepare-integration.outputs.source_sha }} - integration-inputs-artifact-id: ${{ needs.prepare-integration.outputs.integration_inputs_artifact_id }} - secrets: - CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }} - # Run the continuity suites (tests/suites/continuity) on tmachine: state # seeded before a disruption, such as a gateway restart or an upgrade from the # latest release, must survive it. The label adds to test:e2e, whose builds it @@ -822,7 +793,6 @@ jobs: - build-vm-driver-macos - conformance-integration - feature-specific-integration - - driver-specific-integration - podman-e2e-integration - docker-e2e - podman-e2e diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index 3b97f9c03c..5d6f5b050b 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -3,15 +3,14 @@ # Runs testkit suites in tmachine environments on CI. Each row of `ROWS` below # names a tmachine environment and installer, the family (the path of a -# workspace under tests/suites/, such as conformance or drivers/podman) and, +# workspace under tests/suites/, such as conformance or features) and, # optionally, the package in it, the gateway name the installer registers, and # the runner label for the environment's architecture. `openshell-test-runner` # builds the tests, boots the environment, runs them inside it and checks the # results. With `prebuilt`, the rows run what the caller built once for the # run instead: conformance rows the static `openshell-conformance`, the other # rows their family's test bundle. The `family` input selects the rows of one -# family, including the workspaces under it (drivers selects drivers/docker -# and drivers/podman); leave it empty to run every row. +# family, including the workspaces under it; leave it empty to run every row. name: E2E Suites @@ -144,15 +143,6 @@ jobs: {"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"service-exposure","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-keycloak","installer":"rpm","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless-keycloak","installer":"rpm","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"ubuntu-docker-rootful","installer":"deb","family":"drivers/docker","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootful-userns-default","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootful-userns-auto","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootful-userns-keep-id","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootful-userns-private","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootless-userns-default","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootless-userns-auto","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootless-userns-keep-id","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, - {"environment":"fedora-podman-rootless-userns-private","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"continuity","disruption":"gateway-restart","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb-upgrade-source","family":"continuity","disruption":"upgrade","gateway":"openshell","runner":"ubuntu-24.04","upgrade_source":true,"upgrade_package":"deb"}, {"environment":"fedora-podman-rootless","installer":"rpm-upgrade-source","family":"continuity","disruption":"upgrade","gateway":"openshell","runner":"ubuntu-24.04","upgrade_source":true,"upgrade_package":"rpm"}, diff --git a/.github/workflows/rust-cache.yml b/.github/workflows/rust-cache.yml index 0a66b04309..6a4c869edb 100644 --- a/.github/workflows/rust-cache.yml +++ b/.github/workflows/rust-cache.yml @@ -110,7 +110,7 @@ jobs: run: | set -euo pipefail nix build --no-link .#openshell-test-runner || nix build --no-link .#openshell-test-runner - for family in features drivers/docker drivers/podman; do + for family in features; do nix run .#openshell-test-runner -- build \ --family "$family" --out "$RUNNER_TEMP/e2e-bundles/${family//\//-}" done diff --git a/CI.md b/CI.md index 8eaf6b1787..02379b513a 100644 --- a/CI.md +++ b/CI.md @@ -217,12 +217,10 @@ selected. DEB and RPM packages build only when integration qualification is sele the DEB on Ubuntu with Docker and installs the CLI and gateway RPMs on Fedora with rootful and rootless Podman. These lanes run conformance using the matching runtime images. Release Dev, Release, and Pre-release use the same package installers. -The feature suites (`tests/suites/features`) and the Docker and Podman driver -suites (`tests/suites/drivers/{docker,podman}`) run the same way, on the package -installers; the Podman driver suite's environments merge their Podman settings -into the packaged gateway's configuration (see `TESTING.md`). The `e2e-podman` -lane runs on the RPM installer as well. The driver suites and `e2e-podman` run -only in `Branch E2E Checks`. The manual Integration Tests workflow runs the +The feature suites (`tests/suites/features`) run the same way, on the package +installers. The `e2e-podman` lane runs on the RPM installer as well. The +Docker and Podman driver suites now live in `ai-openshell/desktop` +(`tests/suites/drivers`). `e2e-podman` runs only in `Branch E2E Checks`. The manual Integration Tests workflow runs the remaining tmachine testsuites, such as `e2e-podman`, and downloads the packages selected by its matrix. diff --git a/e2e/rust/tests/local_driver_token_restart.rs b/e2e/rust/tests/local_driver_token_restart.rs index 976bd217fd..a8182bc50e 100644 --- a/e2e/rust/tests/local_driver_token_restart.rs +++ b/e2e/rust/tests/local_driver_token_restart.rs @@ -6,7 +6,8 @@ //! VM-driver E2E regression for sandbox bootstrap JWT material. Launch-scoped //! bootstrap tokens must remain valid long enough for driver recovery, so //! restarting the VM gateway reconnects the running sandbox. The Docker and -//! Podman stop-is-terminal checks live in `tests/suites/drivers`. +//! Podman stop-is-terminal checks live in `tests/suites/drivers` of +//! `ai-openshell/desktop`. use std::fs; use std::path::PathBuf; diff --git a/tasks/rust.toml b/tasks/rust.toml index 18a2b7c77a..38f919a681 100644 --- a/tasks/rust.toml +++ b/tasks/rust.toml @@ -41,8 +41,6 @@ run = [ "cargo clippy --manifest-path tests/runner/Cargo.toml --all-targets -- -D warnings", "cargo clippy --manifest-path tests/suites/conformance/Cargo.toml --workspace --all-targets -- -D warnings", "cargo clippy --manifest-path tests/suites/continuity/Cargo.toml --workspace --all-targets -- -D warnings", - "cargo clippy --manifest-path tests/suites/drivers/docker/Cargo.toml --workspace --all-targets -- -D warnings", - "cargo clippy --manifest-path tests/suites/drivers/podman/Cargo.toml --workspace --all-targets -- -D warnings", "cargo clippy --manifest-path tests/suites/features/Cargo.toml --workspace --all-targets -- -D warnings", "cargo clippy --manifest-path tests/support/Cargo.toml --all-targets -- -D warnings", ] @@ -62,8 +60,6 @@ run = [ "cargo fmt --manifest-path tests/runner/Cargo.toml --all", "cargo fmt --manifest-path tests/suites/conformance/Cargo.toml --all", "cargo fmt --manifest-path tests/suites/continuity/Cargo.toml --all", - "cargo fmt --manifest-path tests/suites/drivers/docker/Cargo.toml --all", - "cargo fmt --manifest-path tests/suites/drivers/podman/Cargo.toml --all", "cargo fmt --manifest-path tests/suites/features/Cargo.toml --all", "cargo fmt --manifest-path tests/support/Cargo.toml --all", ] @@ -82,8 +78,6 @@ run = [ "cargo fmt --manifest-path tests/runner/Cargo.toml --all -- --check", "cargo fmt --manifest-path tests/suites/conformance/Cargo.toml --all -- --check", "cargo fmt --manifest-path tests/suites/continuity/Cargo.toml --all -- --check", - "cargo fmt --manifest-path tests/suites/drivers/docker/Cargo.toml --all -- --check", - "cargo fmt --manifest-path tests/suites/drivers/podman/Cargo.toml --all -- --check", "cargo fmt --manifest-path tests/suites/features/Cargo.toml --all -- --check", "cargo fmt --manifest-path tests/support/Cargo.toml --all -- --check", ] diff --git a/tasks/scripts/check_cargo_lockfile_alignment.py b/tasks/scripts/check_cargo_lockfile_alignment.py index 073a98dfdc..be9c56daab 100644 --- a/tasks/scripts/check_cargo_lockfile_alignment.py +++ b/tasks/scripts/check_cargo_lockfile_alignment.py @@ -39,8 +39,6 @@ "tests/testkit", "tests/suites/conformance", "tests/suites/continuity", - "tests/suites/drivers/docker", - "tests/suites/drivers/podman", "tests/suites/features", ) diff --git a/tests/suites/conformance/README.md b/tests/suites/conformance/README.md index ec7111d27d..937df55f4e 100644 --- a/tests/suites/conformance/README.md +++ b/tests/suites/conformance/README.md @@ -101,8 +101,8 @@ leave driver behavior alone. - Assert `phase` and `exit_code`. Don't assert condition reasons. - Check that something did not happen by reading state, not by sleeping. - Don't test behavior that only some drivers have. A test that can't pass on - every environment isn't conformance; put it in `tests/suites/features` or - `tests/suites/drivers`. + every environment isn't conformance; put it in `tests/suites/features`, or for one driver in + `tests/suites/drivers` of `ai-openshell/desktop`. - Use the CLI for upload, download, connect and forward. Rely on its exit code and `--output json`. - Add a testkit helper instead of calling raw gRPC from a test. diff --git a/tests/suites/conformance/src/lifecycle.rs b/tests/suites/conformance/src/lifecycle.rs index 1e66e1e3fb..b3e410b52b 100644 --- a/tests/suites/conformance/src/lifecycle.rs +++ b/tests/suites/conformance/src/lifecycle.rs @@ -486,7 +486,7 @@ const EPHEMERAL_CLEANUP_TIMEOUT: Duration = Duration::from_secs(60); /// /// This checks only what the gateway shows: get and list stop returning the /// sandbox. Conformance can't see driver resources: the Docker and Podman -/// driver suites (`tests/suites/drivers/{docker,podman}`) check that the +/// driver suites (`tests/suites/drivers` in `ai-openshell/desktop`) check that the /// driver removed its containers, and the legacy /// `e2e/rust/tests/ephemeral_cleanup.rs` still checks Kubernetes pods and VM /// state. diff --git a/tests/suites/drivers/docker/Cargo.lock b/tests/suites/drivers/docker/Cargo.lock deleted file mode 100644 index c9e06d3753..0000000000 --- a/tests/suites/drivers/docker/Cargo.lock +++ /dev/null @@ -1,4973 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "getrandom 0.3.4", - "once_cell", - "version_check", - "zerocopy", -] - -[[package]] -name = "aho-corasick" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" -dependencies = [ - "memchr", -] - -[[package]] -name = "allocator-api2" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" - -[[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 = "annotate-snippets" -version = "0.12.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564" -dependencies = [ - "anstyle", - "memchr", - "unicode-width 0.2.2", -] - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - -[[package]] -name = "arraydeque" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" - -[[package]] -name = "asn1-rs" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" -dependencies = [ - "asn1-rs-derive", - "asn1-rs-impl", - "displaydoc", - "nom", - "num-traits", - "rusticata-macros", - "thiserror 2.0.20", - "time", -] - -[[package]] -name = "asn1-rs-derive" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", - "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.117", -] - -[[package]] -name = "async-broadcast" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" -dependencies = [ - "event-listener", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "async-trait" -version = "0.1.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "atoi" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" -dependencies = [ - "num-traits", -] - -[[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.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" - -[[package]] -name = "aws-lc-rs" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2b2dcc879c3bae0d371e77c99f2238400ef24ec001394befa67b6e543add9e" -dependencies = [ - "aws-lc-sys", - "untrusted 0.7.1", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.44.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f09fae7be8bb3174e05c6afdb34199e6dc0c7c04ba9fa237b1967adfbde27483" -dependencies = [ - "cc", - "cmake", - "dunce", - "fs_extra", - "pkg-config", -] - -[[package]] -name = "axum" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" -dependencies = [ - "axum-core", - "bytes", - "futures-util", - "http", - "http-body", - "http-body-util", - "itoa", - "matchit", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "serde_core", - "sync_wrapper", - "tower", - "tower-layer", - "tower-service", -] - -[[package]] -name = "axum-core" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "mime", - "pin-project-lite", - "sync_wrapper", - "tower-layer", - "tower-service", -] - -[[package]] -name = "backon" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" -dependencies = [ - "fastrand", - "gloo-timers", - "tokio", -] - -[[package]] -name = "backtrace" -version = "0.3.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-link", -] - -[[package]] -name = "backtrace-ext" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "537beee3be4a18fb023b570f80e3ae28003db9167a751266b259926e25539d50" -dependencies = [ - "backtrace", -] - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "base64" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" - -[[package]] -name = "bit-vec" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" -dependencies = [ - "serde", -] - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -dependencies = [ - "serde_core", -] - -[[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 = "block-buffer" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "bumpalo" -version = "3.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" - -[[package]] -name = "cc" -version = "1.2.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - -[[package]] -name = "chacha20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "rand_core 0.10.1", -] - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - -[[package]] -name = "cmov" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "combine" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" -dependencies = [ - "bytes", - "memchr", -] - -[[package]] -name = "container-engine-support" -version = "0.0.0" -dependencies = [ - "openshell-testkit", - "tempfile", - "tokio", -] - -[[package]] -name = "core-foundation" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" -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 = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" -dependencies = [ - "libc", -] - -[[package]] -name = "crc" -version = "3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" -dependencies = [ - "crc-catalog", -] - -[[package]] -name = "crc-catalog" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" - -[[package]] -name = "critical-section" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" - -[[package]] -name = "crossbeam-queue" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "crypto-common" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "ctutils" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" -dependencies = [ - "cmov", -] - -[[package]] -name = "darling" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 3.0.5", -] - -[[package]] -name = "darling_macro" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" -dependencies = [ - "darling_core", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "data-encoding" -version = "2.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" - -[[package]] -name = "defmt" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" -dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "defmt-parser" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" -dependencies = [ - "thiserror 2.0.20", -] - -[[package]] -name = "der-parser" -version = "10.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" -dependencies = [ - "asn1-rs", - "displaydoc", - "nom", - "num-bigint", - "num-traits", - "rusticata-macros", -] - -[[package]] -name = "deranged" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -dependencies = [ - "powerfmt", -] - -[[package]] -name = "derive_more" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" -dependencies = [ - "derive_more-impl", -] - -[[package]] -name = "derive_more-impl" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "syn 2.0.117", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", -] - -[[package]] -name = "digest" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4850db49bf08e663084f7fb5c87d202ef91a3907271aff24a94eb97ff039153c" -dependencies = [ - "block-buffer 0.12.0", - "crypto-common 0.2.2", - "ctutils", -] - -[[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.117", -] - -[[package]] -name = "docker" -version = "0.0.0" -dependencies = [ - "container-engine-support", - "openshell-testkit", -] - -[[package]] -name = "dotenvy" -version = "0.15.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "dyn-clone" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" - -[[package]] -name = "educe" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00371d2607edea062396ef1ce6ade65c8e915ac7a1277daa198208420f682c6" -dependencies = [ - "enum-ordinalize", - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" -dependencies = [ - "serde", -] - -[[package]] -name = "encoding_rs" -version = "0.8.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" -dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", -] - -[[package]] -name = "encoding_rs_io" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fba3fe847045ecff794b9c138293a80db914678c453ad63fbf0c6a9eb6e00b22" -dependencies = [ - "encoding_rs", -] - -[[package]] -name = "enum-ordinalize" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89dd01549b09589510cf0647475075d12071456586d70f5c75c98ae2a5537677" -dependencies = [ - "enum-ordinalize-derive", -] - -[[package]] -name = "enum-ordinalize-derive" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a65863d15a4ce2888bd2f0f543cc963d3879c3a022c8ee43f6141d479a3ac815" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "escape8259" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f0d310082fd5de539d4f41601182241147498444a7695c520288a0cdbead6" - -[[package]] -name = "etcetera" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" -dependencies = [ - "cfg-if", - "windows-sys 0.61.2", -] - -[[package]] -name = "event-listener" -version = "5.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" -dependencies = [ - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener", - "pin-project-lite", -] - -[[package]] -name = "fastrand" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" - -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - -[[package]] -name = "fixedbitset" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" - -[[package]] -name = "flume" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" -dependencies = [ - "futures-core", - "futures-sink", - "spin", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "form_urlencoded" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - -[[package]] -name = "futures" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-executor" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-intrusive" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" -dependencies = [ - "futures-core", - "lock_api 0.4.14", - "parking_lot 0.12.5", -] - -[[package]] -name = "futures-io" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" - -[[package]] -name = "futures-macro" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "futures-sink" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" - -[[package]] -name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-util" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[package]] -name = "getrandom" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", - "rand_core 0.10.1", - "wasip2", - "wasip3", -] - -[[package]] -name = "gimli" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" - -[[package]] -name = "glob" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" - -[[package]] -name = "gloo-timers" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" -dependencies = [ - "futures-channel", - "futures-core", - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "granit-parser" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f05586d4d4df3d47123207826c40b252728b438a1a07bad3c01ee6bea401df" -dependencies = [ - "arraydeque", - "smallvec", -] - -[[package]] -name = "h2" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "hashbrown" -version = "0.15.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" -dependencies = [ - "foldhash 0.1.5", -] - -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash 0.2.0", -] - -[[package]] -name = "hashbrown" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" - -[[package]] -name = "hashlink" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" -dependencies = [ - "hashbrown 0.16.1", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hickory-proto" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e2da0694c15b44c6f68a6b05e0233617008c54080e31d6eb848d858a9c5b38d" -dependencies = [ - "data-encoding", - "idna", - "ipnet", - "jni", - "once_cell", - "rand 0.10.2", - "ring", - "thiserror 2.0.20", - "tinyvec", - "tracing", - "url", -] - -[[package]] -name = "hkdf" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" -dependencies = [ - "hmac", -] - -[[package]] -name = "hmac" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" -dependencies = [ - "digest 0.11.2", -] - -[[package]] -name = "hostname" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" -dependencies = [ - "cfg-if", - "libc", - "windows-link", -] - -[[package]] -name = "http" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "http-body" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hybrid-array" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" -dependencies = [ - "typenum", -] - -[[package]] -name = "hyper" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "h2", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" -dependencies = [ - "http", - "hyper", - "hyper-util", - "log", - "rustls", - "rustls-native-certs", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-timeout" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" -dependencies = [ - "hyper", - "hyper-util", - "pin-project-lite", - "tokio", - "tower-service", -] - -[[package]] -name = "hyper-util" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" -dependencies = [ - "base64 0.23.1", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "httparse", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[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 = "icu_collections" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" - -[[package]] -name = "icu_properties" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" - -[[package]] -name = "icu_provider" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "2.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" -dependencies = [ - "equivalent", - "hashbrown 0.17.0", - "serde", - "serde_core", -] - -[[package]] -name = "ipnet" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" - -[[package]] -name = "iri-string" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" -dependencies = [ - "memchr", - "serde", -] - -[[package]] -name = "is_ci" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "jiff" -version = "0.2.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" -dependencies = [ - "defmt", - "jiff-core 0.1.8", - "jiff-static 0.2.38", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", -] - -[[package]] -name = "jiff" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e77cbfb9fff4798e283c2d69dff39fc2c45e7da017e5ce95b654e46ea41236" -dependencies = [ - "jiff-core 1.0.1", - "jiff-static 1.0.2", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", -] - -[[package]] -name = "jiff-core" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" -dependencies = [ - "log", -] - -[[package]] -name = "jiff-core" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" -dependencies = [ - "log", -] - -[[package]] -name = "jiff-static" -version = "0.2.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" -dependencies = [ - "jiff-core 0.1.8", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "jiff-static" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9067a0b23e5be3147d56b2dcf652b18e6b1364caca93fb157653b6fbcab23a9" -dependencies = [ - "jiff-core 1.0.1", - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "jni" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" -dependencies = [ - "cfg-if", - "combine", - "jni-macros", - "jni-sys", - "log", - "simd_cesu8", - "thiserror 2.0.20", - "walkdir", - "windows-link", -] - -[[package]] -name = "jni-macros" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "simd_cesu8", - "syn 2.0.117", -] - -[[package]] -name = "jni-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" -dependencies = [ - "jni-sys-macros", -] - -[[package]] -name = "jni-sys-macros" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" -dependencies = [ - "quote", - "syn 2.0.117", -] - -[[package]] -name = "jobserver" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" -dependencies = [ - "getrandom 0.3.4", - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "json-patch" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" -dependencies = [ - "jsonptr", - "serde", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "jsonpath-rust" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c83bc96c838e7a3de9dc89ea291363ac073371959637e3b2207556e9320547b8" -dependencies = [ - "pest", - "pest_derive", - "regex", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "jsonptr" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "jsonwebtoken" -version = "10.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1" -dependencies = [ - "aws-lc-rs", - "base64 0.22.1", - "getrandom 0.2.17", - "js-sys", - "pem 3.0.6", - "serde", - "serde_json", - "signature", - "simple_asn1", -] - -[[package]] -name = "k8s-openapi" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab0d13801242174b1f3966907c3f32039f2d6b36c7ce82c61225d66ed5d1eb70" -dependencies = [ - "base64 0.22.1", - "jiff 0.2.38", - "serde", - "serde_json", -] - -[[package]] -name = "kube" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f95e1a9107878bef32cfbe2e5e084584db832c9616df9981adc4673f9fb1c853" -dependencies = [ - "k8s-openapi", - "kube-client", - "kube-core", - "kube-derive", - "kube-runtime", -] - -[[package]] -name = "kube-client" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703ee17477c86501627e83492895c06ab6fc2c55a319bb2fbc582ccae739ba67" -dependencies = [ - "base64 0.23.1", - "bytes", - "either", - "futures", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-timeout", - "hyper-util", - "jiff 0.2.38", - "jsonpath-rust", - "k8s-openapi", - "kube-core", - "pem 4.0.0", - "percent-encoding", - "rustls", - "rustls-platform-verifier", - "secrecy", - "serde", - "serde-saphyr", - "serde_json", - "thiserror 2.0.20", - "tokio", - "tokio-util", - "tower", - "tower-http 0.7.1", - "tracing", -] - -[[package]] -name = "kube-core" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e9a9aa533b2f4106ac1ac45e168bb452325eb9e918d57335444f60bef34ffc" -dependencies = [ - "derive_more", - "form_urlencoded", - "http", - "jiff 0.2.38", - "json-patch", - "k8s-openapi", - "schemars", - "serde", - "serde-value", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "kube-derive" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cedc991dbe7757a646098dead35e070e13ce66e2996b02162ac7f97eb97f4d6e" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn 3.0.5", -] - -[[package]] -name = "kube-runtime" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca78d9eeb4674eb75e381e6a956e8a5005942928dec87de4db9ef9701af8a637" -dependencies = [ - "ahash", - "async-broadcast", - "async-stream", - "backon", - "educe", - "futures", - "hashbrown 0.16.1", - "hostname", - "json-patch", - "k8s-openapi", - "kube-client", - "parking_lot 0.13.0", - "pin-project", - "serde", - "serde_json", - "thiserror 2.0.20", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "libredox" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f02ab6bace2054fb888a3c16f990117b579d14a3088e472d63c6011fa185c9d3" -dependencies = [ - "libc", -] - -[[package]] -name = "libsqlite3-sys" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0e7f1cd558a82cc3af091ed13f0f03846f89851c60a10713ce5cfd484195494" -dependencies = [ - "cc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "libtest-mimic" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14e6ba06f0ade6e504aff834d7c34298e5155c6baca353cc6a4aaff2f9fd7f33" -dependencies = [ - "anstream", - "anstyle", - "clap", - "escape8259", -] - -[[package]] -name = "linkme" -version = "0.3.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a4e12fd3f6b22d5bc28beccac0f53bb35db4a897c6ddb709c4a0161f72eb6e" -dependencies = [ - "linkme-impl", -] - -[[package]] -name = "linkme-impl" -version = "0.3.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cd04c256b1cd686a45898c8fd150c79b801d96a3eb7bae1075f9eb3b4b85c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "litemap" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "lock_api" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" - -[[package]] -name = "matchit" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" - -[[package]] -name = "md-5" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" -dependencies = [ - "cfg-if", - "digest 0.11.2", -] - -[[package]] -name = "memchr" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" - -[[package]] -name = "miette" -version = "7.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" -dependencies = [ - "backtrace", - "backtrace-ext", - "cfg-if", - "miette-derive", - "owo-colors", - "supports-color", - "supports-hyperlinks", - "supports-unicode", - "terminal_size", - "textwrap", - "unicode-width 0.1.14", -] - -[[package]] -name = "miette-derive" -version = "7.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[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.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", -] - -[[package]] -name = "mio" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "multimap" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" - -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - -[[package]] -name = "newtype-uuid" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa56da58097c7ae893c4097bb6d91bb5f7fa330053e07e033349db4d5f83ba8" -dependencies = [ - "uuid", -] - -[[package]] -name = "nix" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" -dependencies = [ - "bitflags 2.13.2", - "cfg-if", - "cfg_aliases", - "libc", -] - -[[package]] -name = "nohash-hasher" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" - -[[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 = "noyalib" -version = "0.0.53" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "962838abbd8dd2cd3844d2208dc502458bba6985f8bf1dc21761b30260fcbd7f" -dependencies = [ - "hashbrown 0.17.0", - "indexmap", - "libm", - "memchr", - "rustc-hash", - "serde_core", - "smallvec", -] - -[[package]] -name = "num-bigint" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" - -[[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-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "oauth2" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" -dependencies = [ - "base64 0.22.1", - "chrono", - "getrandom 0.2.17", - "http", - "rand 0.8.6", - "reqwest", - "serde", - "serde_json", - "serde_path_to_error", - "sha2 0.10.9", - "thiserror 1.0.69", - "url", -] - -[[package]] -name = "objc2-core-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "objc2-system-configuration" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" -dependencies = [ - "objc2-core-foundation", -] - -[[package]] -name = "object" -version = "0.37.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" -dependencies = [ - "memchr", -] - -[[package]] -name = "oid-registry" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" -dependencies = [ - "asn1-rs", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -dependencies = [ - "critical-section", - "portable-atomic", -] - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "openshell-bootstrap" -version = "0.0.0" -dependencies = [ - "bytes", - "miette", - "openshell-core", - "openshell-crypto", - "rcgen", - "serde", - "serde_json", - "tempfile", - "tokio", - "tracing", -] - -[[package]] -name = "openshell-core" -version = "0.0.0" -dependencies = [ - "async-trait", - "base64 0.22.1", - "glob", - "ipnet", - "jiff 1.0.2", - "libc", - "miette", - "nix", - "openshell-crypto", - "openshell-extension-core", - "openshell-policy-schema", - "openshell-spiffe", - "prost", - "prost-types", - "protoc-bin-vendored", - "reqwest", - "rustix", - "rustls", - "serde", - "serde_json", - "sha2 0.10.9", - "thiserror 2.0.20", - "tokio", - "tokio-stream", - "tokio-util", - "tonic", - "tonic-prost", - "tonic-prost-build", - "tonic-types", - "tracing", - "url", - "uuid", - "windows-sys 0.61.2", -] - -[[package]] -name = "openshell-crypto" -version = "0.0.0" -dependencies = [ - "aws-lc-rs", - "jsonwebtoken", - "kube", - "pem 3.0.6", - "rcgen", - "rustls", - "serde", - "sqlx", - "thiserror 2.0.20", - "tonic", - "x509-parser", -] - -[[package]] -name = "openshell-extension-core" -version = "0.0.0" -dependencies = [ - "h2", - "hyper", - "hyper-util", - "serde", - "thiserror 2.0.20", - "tokio", - "tonic", - "tower", -] - -[[package]] -name = "openshell-policy" -version = "0.0.0" -dependencies = [ - "hickory-proto", - "miette", - "openshell-core", - "openshell-policy-schema", - "prost", - "prost-types", - "serde", - "serde_json", -] - -[[package]] -name = "openshell-policy-schema" -version = "0.0.0" -dependencies = [ - "miette", - "noyalib", - "serde", - "serde_json", - "serde_path_to_error", - "thiserror 2.0.20", -] - -[[package]] -name = "openshell-providers" -version = "0.0.0" -dependencies = [ - "glob", - "noyalib", - "openshell-core", - "openshell-policy", - "prost-types", - "serde", - "serde_json", - "thiserror 2.0.20", - "url", -] - -[[package]] -name = "openshell-sdk" -version = "0.0.0" -dependencies = [ - "async-stream", - "async-trait", - "futures", - "hyper", - "hyper-util", - "miette", - "oauth2", - "openshell-core", - "openshell-crypto", - "reqwest", - "rustls", - "serde", - "thiserror 2.0.20", - "tokio", - "tokio-rustls", - "tokio-tungstenite", - "tonic", - "tower", - "tracing", -] - -[[package]] -name = "openshell-spiffe" -version = "0.0.0" -dependencies = [ - "async-trait", - "base64 0.22.1", - "serde", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "openshell-testkit" -version = "0.0.0" -dependencies = [ - "clap", - "futures", - "libc", - "libtest-mimic", - "linkme", - "noyalib", - "openshell-bootstrap", - "openshell-core", - "openshell-crypto", - "openshell-policy", - "openshell-providers", - "openshell-sdk", - "openshell-testkit-macros", - "prost-types", - "quick-junit", - "rand 0.9.4", - "reqwest", - "rustls", - "rustls-native-certs", - "serde", - "serde_json", - "tempfile", - "tokio", - "tonic", -] - -[[package]] -name = "openshell-testkit-macros" -version = "0.0.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "openssl-probe" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" - -[[package]] -name = "ordered-float" -version = "2.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" -dependencies = [ - "num-traits", -] - -[[package]] -name = "owo-colors" -version = "4.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d211803b9b6b570f68772237e415a029d5a50c65d382910b879fb19d3271f94d" - -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api 0.4.14", - "parking_lot_core 0.9.12", -] - -[[package]] -name = "parking_lot" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226" -dependencies = [ - "lock_api 0.5.0", - "parking_lot_core 0.10.0", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall 0.5.18", - "smallvec", - "windows-link", -] - -[[package]] -name = "parking_lot_core" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826" -dependencies = [ - "libc", - "redox_syscall 0.9.5", - "smallvec", - "windows-link", -] - -[[package]] -name = "pem" -version = "3.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" -dependencies = [ - "base64 0.22.1", - "serde_core", -] - -[[package]] -name = "pem" -version = "4.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" -dependencies = [ - "base64 0.23.1", - "serde_core", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pest" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0848c601009d37dfa3430c4666e147e49cdcf1b92ecd3e63657d8a5f19da662" -dependencies = [ - "memchr", - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11f486f1ea21e6c10ed15d5a7c77165d0ee443402f0780849d1768e7d9d6fe77" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8040c4647b13b210a963c1ed407c1ff4fdfa01c31d6d2a098218702e6664f94f" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "pest_meta" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220" -dependencies = [ - "pest", - "sha2 0.10.9", -] - -[[package]] -name = "petgraph" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" -dependencies = [ - "fixedbitset", - "hashbrown 0.15.5", - "indexmap", -] - -[[package]] -name = "pin-project" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "pkg-config" -version = "0.3.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" - -[[package]] -name = "portable-atomic" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" - -[[package]] -name = "portable-atomic-util" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" -dependencies = [ - "portable-atomic", -] - -[[package]] -name = "potential_utf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" -dependencies = [ - "zerovec", -] - -[[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.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.117", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "prost" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568" -dependencies = [ - "bytes", - "prost-derive", -] - -[[package]] -name = "prost-build" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" -dependencies = [ - "heck", - "itertools", - "log", - "multimap", - "petgraph", - "prettyplease", - "prost", - "prost-types", - "pulldown-cmark", - "pulldown-cmark-to-cmark", - "regex", - "syn 2.0.117", - "tempfile", -] - -[[package]] -name = "prost-derive" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" -dependencies = [ - "anyhow", - "itertools", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "prost-types" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" -dependencies = [ - "prost", -] - -[[package]] -name = "protoc-bin-vendored" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa" -dependencies = [ - "protoc-bin-vendored-linux-aarch_64", - "protoc-bin-vendored-linux-ppcle_64", - "protoc-bin-vendored-linux-s390_64", - "protoc-bin-vendored-linux-x86_32", - "protoc-bin-vendored-linux-x86_64", - "protoc-bin-vendored-macos-aarch_64", - "protoc-bin-vendored-macos-x86_64", - "protoc-bin-vendored-win32", -] - -[[package]] -name = "protoc-bin-vendored-linux-aarch_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c" - -[[package]] -name = "protoc-bin-vendored-linux-ppcle_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c" - -[[package]] -name = "protoc-bin-vendored-linux-s390_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0" - -[[package]] -name = "protoc-bin-vendored-linux-x86_32" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5" - -[[package]] -name = "protoc-bin-vendored-linux-x86_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78" - -[[package]] -name = "protoc-bin-vendored-macos-aarch_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092" - -[[package]] -name = "protoc-bin-vendored-macos-x86_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756" - -[[package]] -name = "protoc-bin-vendored-win32" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" - -[[package]] -name = "pulldown-cmark" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" -dependencies = [ - "bitflags 2.13.2", - "memchr", - "unicase", -] - -[[package]] -name = "pulldown-cmark-to-cmark" -version = "22.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50793def1b900256624a709439404384204a5dc3a6ec580281bfaac35e882e90" -dependencies = [ - "pulldown-cmark", -] - -[[package]] -name = "quick-junit" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bae23b8e1a59a90f7bf98caa2f4c8c2eedf6df011c6c88ed633e85a87c84526e" -dependencies = [ - "chrono", - "indexmap", - "newtype-uuid", - "quick-xml", - "strip-ansi-escapes", - "thiserror 2.0.20", - "uuid", -] - -[[package]] -name = "quick-xml" -version = "0.41.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" -dependencies = [ - "memchr", -] - -[[package]] -name = "quote" -version = "1.0.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rand" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", -] - -[[package]] -name = "rand" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" -dependencies = [ - "chacha20", - "getrandom 0.4.2", - "rand_core 0.10.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_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - -[[package]] -name = "rcgen" -version = "0.14.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" -dependencies = [ - "aws-lc-rs", - "pem 4.0.0", - "rustls-pki-types", - "time", - "x509-parser", - "yasna", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "redox_syscall" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "ref-cast" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "regex" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" - -[[package]] -name = "reqwest" -version = "0.12.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "rustls", - "rustls-native-certs", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tower", - "tower-http 0.6.8", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted 0.9.0", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" - -[[package]] -name = "rustc-hash" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" - -[[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 = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" -dependencies = [ - "aws-lc-rs", - "log", - "once_cell", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-native-certs" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" -dependencies = [ - "openssl-probe", - "rustls-pki-types", - "schannel", - "security-framework", -] - -[[package]] -name = "rustls-pki-types" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" -dependencies = [ - "zeroize", -] - -[[package]] -name = "rustls-platform-verifier" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" -dependencies = [ - "core-foundation", - "core-foundation-sys", - "jni", - "log", - "once_cell", - "rustls", - "rustls-native-certs", - "rustls-platform-verifier-android", - "rustls-webpki", - "security-framework", - "security-framework-sys", - "webpki-root-certs", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls-platform-verifier-android" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" - -[[package]] -name = "rustls-webpki" -version = "0.103.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" -dependencies = [ - "aws-lc-rs", - "ring", - "rustls-pki-types", - "untrusted 0.9.0", -] - -[[package]] -name = "rustversion" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" - -[[package]] -name = "ryu" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" - -[[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 = "schannel" -version = "0.1.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "schemars" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" -dependencies = [ - "dyn-clone", - "ref-cast", - "schemars_derive", - "serde", - "serde_json", -] - -[[package]] -name = "schemars_derive" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals", - "syn 3.0.5", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "secrecy" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" -dependencies = [ - "zeroize", -] - -[[package]] -name = "security-framework" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" -dependencies = [ - "bitflags 2.13.2", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde-saphyr" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe" -dependencies = [ - "annotate-snippets", - "base64 0.23.1", - "encoding_rs_io", - "granit-parser", - "nohash-hasher", - "num-traits", - "serde_core", - "smallvec", - "zmij", -] - -[[package]] -name = "serde-value" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" -dependencies = [ - "ordered-float", - "serde", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "serde_derive_internals" -version = "0.30.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_path_to_error" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" -dependencies = [ - "itoa", - "serde", - "serde_core", -] - -[[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 = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha1" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "digest 0.11.2", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "digest 0.11.2", -] - -[[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.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "signature" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" -dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "simd_cesu8" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" -dependencies = [ - "rustc_version", - "simdutf8", -] - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "simple_asn1" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" -dependencies = [ - "num-bigint", - "num-traits", - "thiserror 2.0.20", - "time", -] - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" -dependencies = [ - "serde", -] - -[[package]] -name = "socket2" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "spin" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" -dependencies = [ - "lock_api 0.4.14", -] - -[[package]] -name = "sqlx" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edb1dddfbdfe5fb99dba0541a87b2edb8adbd59e45815db22d32d4fbbb8813dd" -dependencies = [ - "sqlx-core", - "sqlx-macros", - "sqlx-mysql", - "sqlx-postgres", - "sqlx-sqlite", -] - -[[package]] -name = "sqlx-core" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08f9787cc5aff062567dea2205f8ae37a617b04342633ab4f74944858ea6072" -dependencies = [ - "base64 0.22.1", - "bytes", - "cfg-if", - "crc", - "crossbeam-queue", - "either", - "event-listener", - "futures-core", - "futures-intrusive", - "futures-io", - "futures-util", - "hashbrown 0.16.1", - "hashlink", - "indexmap", - "log", - "memchr", - "percent-encoding", - "rustls", - "serde", - "serde_json", - "sha2 0.11.0", - "smallvec", - "thiserror 2.0.20", - "tokio", - "tokio-stream", - "tracing", - "url", - "webpki-roots", -] - -[[package]] -name = "sqlx-macros" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf62c58a1e7fd6031ee684eee21d07572f5aebe71c273a01ae4f04eeeba47c47" -dependencies = [ - "proc-macro2", - "quote", - "sqlx-core", - "sqlx-macros-core", - "syn 2.0.117", -] - -[[package]] -name = "sqlx-macros-core" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1ff75c9d609ac84aa8a3e0d92b5c0c54bf541a7f70db492fb40c9a4bea792c8" -dependencies = [ - "cfg-if", - "dotenvy", - "either", - "heck", - "hex", - "proc-macro2", - "quote", - "serde", - "serde_json", - "sha2 0.11.0", - "sqlx-core", - "sqlx-postgres", - "sqlx-sqlite", - "syn 2.0.117", - "thiserror 2.0.20", - "tokio", - "url", -] - -[[package]] -name = "sqlx-mysql" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19eeb93b96eb10a3a59dfb436f3daf87d2fc41168ed9e9dc153ec8257dd6a761" -dependencies = [ - "bitflags 2.13.2", - "byteorder", - "bytes", - "crc", - "digest 0.11.2", - "dotenvy", - "either", - "futures-core", - "futures-util", - "generic-array", - "log", - "percent-encoding", - "serde", - "sha1 0.11.0", - "sha2 0.11.0", - "sqlx-core", - "thiserror 2.0.20", - "tracing", -] - -[[package]] -name = "sqlx-postgres" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0e9e02f764a1fe640eeefc8eb33eeddd274204654ec9f2db8ff851a1dee2364" -dependencies = [ - "atoi", - "base64 0.22.1", - "bitflags 2.13.2", - "byteorder", - "crc", - "dotenvy", - "etcetera", - "futures-channel", - "futures-core", - "futures-util", - "hex", - "hkdf", - "hmac", - "itoa", - "log", - "md-5", - "memchr", - "rand 0.10.2", - "serde", - "serde_json", - "sha2 0.11.0", - "smallvec", - "sqlx-core", - "stringprep", - "thiserror 2.0.20", - "tracing", - "whoami", -] - -[[package]] -name = "sqlx-sqlite" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88b6b78a34ddcb1db4046d462db8f79cee811019d7297b99fca8fac5de26672e" -dependencies = [ - "atoi", - "flume", - "form_urlencoded", - "futures-channel", - "futures-core", - "futures-executor", - "futures-intrusive", - "futures-util", - "libsqlite3-sys", - "log", - "percent-encoding", - "serde", - "sqlx-core", - "thiserror 2.0.20", - "tracing", - "url", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "stringprep" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" -dependencies = [ - "unicode-bidi", - "unicode-normalization", - "unicode-properties", -] - -[[package]] -name = "strip-ansi-escapes" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025" -dependencies = [ - "vte", -] - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "supports-color" -version = "3.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c64fc7232dd8d2e4ac5ce4ef302b1d81e0b80d055b9d77c7c4f51f6aa4c867d6" -dependencies = [ - "is_ci", -] - -[[package]] -name = "supports-hyperlinks" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e396b6523b11ccb83120b115a0b7366de372751aa6edf19844dfb13a6af97e91" - -[[package]] -name = "supports-unicode" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7401a30af6cb5818bb64852270bb722533397edcfc7344954a38f420819ece2" - -[[package]] -name = "syn" -version = "2.0.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.2", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "terminal_size" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" -dependencies = [ - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "textwrap" -version = "0.16.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" -dependencies = [ - "unicode-linebreak", - "unicode-width 0.2.2", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" -dependencies = [ - "thiserror-impl 2.0.20", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "time" -version = "0.3.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" -dependencies = [ - "deranged", - "itoa", - "num-conv", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" - -[[package]] -name = "time-macros" -version = "0.2.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "tinystr" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -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.53.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" -dependencies = [ - "bytes", - "libc", - "mio", - "parking_lot 0.12.5", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-stream" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-tungstenite" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" -dependencies = [ - "futures-util", - "log", - "rustls", - "rustls-native-certs", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tungstenite", -] - -[[package]] -name = "tokio-util" -version = "0.7.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "futures-util", - "libc", - "pin-project-lite", - "slab", - "tokio", -] - -[[package]] -name = "tonic" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" -dependencies = [ - "async-trait", - "axum", - "base64 0.22.1", - "bytes", - "h2", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-timeout", - "hyper-util", - "percent-encoding", - "pin-project", - "rustls-native-certs", - "socket2", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tokio-stream", - "tower", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tonic-build" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" -dependencies = [ - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "tonic-prost" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" -dependencies = [ - "bytes", - "prost", - "tonic", -] - -[[package]] -name = "tonic-prost-build" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27" -dependencies = [ - "prettyplease", - "proc-macro2", - "prost-build", - "prost-types", - "quote", - "syn 2.0.117", - "tempfile", - "tonic-build", -] - -[[package]] -name = "tonic-types" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8" -dependencies = [ - "prost", - "prost-types", - "tonic", -] - -[[package]] -name = "tower" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" -dependencies = [ - "futures-core", - "futures-util", - "indexmap", - "pin-project-lite", - "slab", - "sync_wrapper", - "tokio", - "tokio-util", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower-http" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" -dependencies = [ - "bitflags 2.13.2", - "bytes", - "futures-util", - "http", - "http-body", - "iri-string", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-http" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" -dependencies = [ - "base64 0.22.1", - "bitflags 2.13.2", - "bytes", - "http", - "http-body", - "mime", - "percent-encoding", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "tungstenite" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13" -dependencies = [ - "bytes", - "data-encoding", - "http", - "httparse", - "log", - "rand 0.9.4", - "rustls", - "rustls-pki-types", - "sha1 0.10.6", - "thiserror 2.0.20", - "utf-8", -] - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "ucd-trie" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" - -[[package]] -name = "unicase" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-linebreak" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" - -[[package]] -name = "unicode-normalization" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-properties" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - -[[package]] -name = "unicode-width" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - -[[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.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", - "serde_derive", -] - -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "uuid" -version = "1.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" -dependencies = [ - "getrandom 0.4.2", - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "vte" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "231fdcd7ef3037e8330d8e17e61011a2c244126acc0a982f4040ac3f9f0bc077" -dependencies = [ - "memchr", -] - -[[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.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.3+wasi-0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" -dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.5", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.13.2", - "hashbrown 0.15.5", - "indexmap", - "semver", -] - -[[package]] -name = "web-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-root-certs" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "webpki-roots" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "whoami" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" -dependencies = [ - "libc", - "libredox", - "objc2-system-configuration", - "web-sys", -] - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[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.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[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.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[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.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck", - "indexmap", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.13.2", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - -[[package]] -name = "writeable" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" - -[[package]] -name = "x509-parser" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" -dependencies = [ - "asn1-rs", - "aws-lc-rs", - "data-encoding", - "der-parser", - "lazy_static", - "nom", - "oid-registry", - "rusticata-macros", - "thiserror 2.0.20", - "time", -] - -[[package]] -name = "yasna" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" -dependencies = [ - "bit-vec", - "time", -] - -[[package]] -name = "yoke" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", - "synstructure", -] - -[[package]] -name = "zerocopy" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "zerofrom" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" - -[[package]] -name = "zerotrie" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/suites/drivers/docker/Cargo.toml b/tests/suites/drivers/docker/Cargo.toml deleted file mode 100644 index 418983946f..0000000000 --- a/tests/suites/drivers/docker/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Each driver suite is its own workspace, with its own lockfile. -[package] -name = "docker" -description = "Drivers suite: Docker driver behavior, such as container lifecycle" -version = "0.0.0" -edition = "2024" -rust-version = "1.94" -license = "Apache-2.0" -repository = "https://github.com/ai-openshell/openshell" -publish = false - -[[test]] -name = "docker-lifecycle" -path = "tests/lifecycle.rs" -harness = false - -[dependencies] -container-engine-support = { path = "../../../support/container-engine" } -openshell-testkit = { path = "../../../testkit/testkit" } - -[workspace] diff --git a/tests/suites/drivers/docker/tests/lifecycle.rs b/tests/suites/drivers/docker/tests/lifecycle.rs deleted file mode 100644 index 83050bde16..0000000000 --- a/tests/suites/drivers/docker/tests/lifecycle.rs +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Docker driver sandbox lifecycle: what the driver does with its containers -//! when a sandbox's main process stops or an ephemeral sandbox finishes. - -use std::time::Duration; - -use container_engine_support::Engine; -use testkit::sdk::SandboxPhase; -use testkit::{Context, ResultExt as _}; - -fn main() -> std::process::ExitCode { - testkit::main() -} - -/// Where the driver mounts the sandbox's bootstrap JWT. -const TOKEN_PATH: &str = "/etc/openshell/auth/sandbox.jwt"; -/// How long the gateway may take to report a stopped workload as Error. -const ERROR_TIMEOUT: Duration = Duration::from_secs(30); -/// How long the driver may take to remove an ephemeral sandbox's containers. -const CLEANUP_TIMEOUT: Duration = Duration::from_secs(90); - -/// Stopping a sandbox's workload container is terminal: the driver doesn't -/// relaunch the main process and the sandbox ends in Error. Before the stop, -/// the workload can't read its bootstrap JWT. -#[testkit::test] -async fn stopped_workload_container_is_terminal(cx: &mut Context) -> testkit::Result { - cx.expect_compute_driver("docker").await?; - let engine = Engine::from_env()?; - let sandbox = cx - .sandbox("st") - .command(["sleep", "infinity"]) - .create_ready() - .await?; - - let workload = engine.container_for_role(sandbox.name(), "sandbox").await?; - engine - .output([ - "exec", - &workload, - "/bin/sh", - "-c", - &format!("test ! -r {TOKEN_PATH}"), - ]) - .await - .context("the sandbox workload must not be able to read its bootstrap JWT")?; - - engine.output(["stop", &workload]).await?; - engine - .wait_running(&workload, false, Duration::from_mins(1)) - .await?; - sandbox - .wait_phase(SandboxPhase::Error, ERROR_TIMEOUT) - .await - .context("a stopped main process makes the sandbox terminal")?; - Ok(()) -} - -/// A detached `--no-keep` sandbox's containers are removed once its main -/// command exits, whether it succeeds or fails. Conformance checks that the -/// gateway forgets the sandbox; this checks the driver's containers. -#[testkit::test] -async fn ephemeral_sandbox_containers_are_removed_after_main_exits( - cx: &mut Context, -) -> testkit::Result { - cx.expect_compute_driver("docker").await?; - let engine = Engine::from_env()?; - let mut sandboxes = Vec::new(); - for (suffix, code) in [("ez", 0), ("ef", 17)] { - let builder = cx.cli_sandbox(suffix); - let release_path = format!("/sandbox/.ephemeral-release-{}", builder.name()); - let script = - format!("while [ ! -e '{release_path}' ]; do sleep 0.1; done; sleep 1; exit {code}"); - let sandbox = builder - .args(["--no-keep"]) - .command(["sh", "-c", &script]) - .create() - .await?; - sandboxes.push((sandbox, release_path, code)); - } - - for (sandbox, release_path, _) in &sandboxes { - sandbox.wait_ready().await?; - testkit::ensure!( - !engine - .containers_for_sandbox_id(sandbox.id()) - .await? - .is_empty(), - "no containers found for sandbox {} ({})", - sandbox.name(), - sandbox.id() - ); - sandbox - .exec(["touch", release_path.as_str()]) - .await? - .success()?; - } - for (sandbox, _, code) in &sandboxes { - testkit::poll_until( - &format!("containers of sandbox {} to be removed", sandbox.name()), - CLEANUP_TIMEOUT, - Duration::from_millis(500), - async || { - let left = engine.containers_for_sandbox_id(sandbox.id()).await?; - Ok(if left.is_empty() { - testkit::Poll::Ready(()) - } else { - testkit::Poll::Pending(format!("containers {left:?}")) - }) - }, - ) - .await - .context(format!("ephemeral sandbox exited {code}"))?; - } - Ok(()) -} diff --git a/tests/suites/drivers/podman/Cargo.lock b/tests/suites/drivers/podman/Cargo.lock deleted file mode 100644 index 1187155f9c..0000000000 --- a/tests/suites/drivers/podman/Cargo.lock +++ /dev/null @@ -1,4984 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "ahash" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" -dependencies = [ - "cfg-if", - "getrandom 0.3.4", - "once_cell", - "version_check", - "zerocopy", -] - -[[package]] -name = "aho-corasick" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" -dependencies = [ - "memchr", -] - -[[package]] -name = "allocator-api2" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" - -[[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 = "annotate-snippets" -version = "0.12.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564" -dependencies = [ - "anstyle", - "memchr", - "unicode-width 0.2.2", -] - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - -[[package]] -name = "anyhow" -version = "1.0.104" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" - -[[package]] -name = "arraydeque" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236" - -[[package]] -name = "asn1-rs" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" -dependencies = [ - "asn1-rs-derive", - "asn1-rs-impl", - "displaydoc", - "nom", - "num-traits", - "rusticata-macros", - "thiserror 2.0.20", - "time", -] - -[[package]] -name = "asn1-rs-derive" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", - "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.117", -] - -[[package]] -name = "async-broadcast" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" -dependencies = [ - "event-listener", - "event-listener-strategy", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "async-trait" -version = "0.1.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "atoi" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" -dependencies = [ - "num-traits", -] - -[[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.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" - -[[package]] -name = "aws-lc-rs" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2b2dcc879c3bae0d371e77c99f2238400ef24ec001394befa67b6e543add9e" -dependencies = [ - "aws-lc-sys", - "untrusted 0.7.1", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.44.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f09fae7be8bb3174e05c6afdb34199e6dc0c7c04ba9fa237b1967adfbde27483" -dependencies = [ - "cc", - "cmake", - "dunce", - "fs_extra", - "pkg-config", -] - -[[package]] -name = "axum" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" -dependencies = [ - "axum-core", - "bytes", - "futures-util", - "http", - "http-body", - "http-body-util", - "itoa", - "matchit", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "serde_core", - "sync_wrapper", - "tower", - "tower-layer", - "tower-service", -] - -[[package]] -name = "axum-core" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "http-body-util", - "mime", - "pin-project-lite", - "sync_wrapper", - "tower-layer", - "tower-service", -] - -[[package]] -name = "backon" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" -dependencies = [ - "fastrand", - "gloo-timers", - "tokio", -] - -[[package]] -name = "backtrace" -version = "0.3.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-link", -] - -[[package]] -name = "backtrace-ext" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "537beee3be4a18fb023b570f80e3ae28003db9167a751266b259926e25539d50" -dependencies = [ - "backtrace", -] - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "base64" -version = "0.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" - -[[package]] -name = "bit-vec" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" -dependencies = [ - "serde", -] - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" -dependencies = [ - "serde_core", -] - -[[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 = "block-buffer" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "bumpalo" -version = "3.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" - -[[package]] -name = "cc" -version = "1.2.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43c5703da9466b66a946814e1adf53ea2c90f10063b86290cc9eb67ce3478a20" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - -[[package]] -name = "chacha20" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "rand_core 0.10.1", -] - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - -[[package]] -name = "cmov" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "combine" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" -dependencies = [ - "bytes", - "memchr", -] - -[[package]] -name = "container-engine-support" -version = "0.0.0" -dependencies = [ - "openshell-testkit", - "tempfile", - "tokio", -] - -[[package]] -name = "core-foundation" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" -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 = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" -dependencies = [ - "libc", -] - -[[package]] -name = "crc" -version = "3.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" -dependencies = [ - "crc-catalog", -] - -[[package]] -name = "crc-catalog" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" - -[[package]] -name = "critical-section" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" - -[[package]] -name = "crossbeam-queue" -version = "0.3.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "crypto-common" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "ctutils" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" -dependencies = [ - "cmov", -] - -[[package]] -name = "darling" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" -dependencies = [ - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 3.0.5", -] - -[[package]] -name = "darling_macro" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" -dependencies = [ - "darling_core", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "data-encoding" -version = "2.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea" - -[[package]] -name = "defmt" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" -dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "defmt-parser" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" -dependencies = [ - "thiserror 2.0.20", -] - -[[package]] -name = "der-parser" -version = "10.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" -dependencies = [ - "asn1-rs", - "displaydoc", - "nom", - "num-bigint", - "num-traits", - "rusticata-macros", -] - -[[package]] -name = "deranged" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -dependencies = [ - "powerfmt", -] - -[[package]] -name = "derive_more" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" -dependencies = [ - "derive_more-impl", -] - -[[package]] -name = "derive_more-impl" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "syn 2.0.117", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", -] - -[[package]] -name = "digest" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4850db49bf08e663084f7fb5c87d202ef91a3907271aff24a94eb97ff039153c" -dependencies = [ - "block-buffer 0.12.0", - "crypto-common 0.2.2", - "ctutils", -] - -[[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.117", -] - -[[package]] -name = "dotenvy" -version = "0.15.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "dyn-clone" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" - -[[package]] -name = "educe" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00371d2607edea062396ef1ce6ade65c8e915ac7a1277daa198208420f682c6" -dependencies = [ - "enum-ordinalize", - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" -dependencies = [ - "serde", -] - -[[package]] -name = "encoding_rs" -version = "0.8.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" -dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", -] - -[[package]] -name = "encoding_rs_io" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fba3fe847045ecff794b9c138293a80db914678c453ad63fbf0c6a9eb6e00b22" -dependencies = [ - "encoding_rs", -] - -[[package]] -name = "enum-ordinalize" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89dd01549b09589510cf0647475075d12071456586d70f5c75c98ae2a5537677" -dependencies = [ - "enum-ordinalize-derive", -] - -[[package]] -name = "enum-ordinalize-derive" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a65863d15a4ce2888bd2f0f543cc963d3879c3a022c8ee43f6141d479a3ac815" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "escape8259" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f0d310082fd5de539d4f41601182241147498444a7695c520288a0cdbead6" - -[[package]] -name = "etcetera" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" -dependencies = [ - "cfg-if", - "windows-sys 0.61.2", -] - -[[package]] -name = "event-listener" -version = "5.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" -dependencies = [ - "parking", - "pin-project-lite", -] - -[[package]] -name = "event-listener-strategy" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" -dependencies = [ - "event-listener", - "pin-project-lite", -] - -[[package]] -name = "fastrand" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" - -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - -[[package]] -name = "fixedbitset" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" - -[[package]] -name = "flume" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" -dependencies = [ - "futures-core", - "futures-sink", - "spin", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "foldhash" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" - -[[package]] -name = "foldhash" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" - -[[package]] -name = "form_urlencoded" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - -[[package]] -name = "futures" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-executor" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-intrusive" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" -dependencies = [ - "futures-core", - "lock_api 0.4.14", - "parking_lot 0.12.5", -] - -[[package]] -name = "futures-io" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" - -[[package]] -name = "futures-macro" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "futures-sink" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" - -[[package]] -name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-util" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if", - "libc", - "r-efi 5.3.0", - "wasip2", -] - -[[package]] -name = "getrandom" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" -dependencies = [ - "cfg-if", - "libc", - "r-efi 6.0.0", - "rand_core 0.10.1", - "wasip2", - "wasip3", -] - -[[package]] -name = "gimli" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" - -[[package]] -name = "glob" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" - -[[package]] -name = "gloo-timers" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" -dependencies = [ - "futures-channel", - "futures-core", - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "granit-parser" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f05586d4d4df3d47123207826c40b252728b438a1a07bad3c01ee6bea401df" -dependencies = [ - "arraydeque", - "smallvec", -] - -[[package]] -name = "h2" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "hashbrown" -version = "0.15.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" -dependencies = [ - "foldhash 0.1.5", -] - -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash 0.2.0", -] - -[[package]] -name = "hashbrown" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" - -[[package]] -name = "hashlink" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" -dependencies = [ - "hashbrown 0.16.1", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hickory-proto" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e2da0694c15b44c6f68a6b05e0233617008c54080e31d6eb848d858a9c5b38d" -dependencies = [ - "data-encoding", - "idna", - "ipnet", - "jni", - "once_cell", - "rand 0.10.2", - "ring", - "thiserror 2.0.20", - "tinyvec", - "tracing", - "url", -] - -[[package]] -name = "hkdf" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" -dependencies = [ - "hmac", -] - -[[package]] -name = "hmac" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" -dependencies = [ - "digest 0.11.2", -] - -[[package]] -name = "hostname" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" -dependencies = [ - "cfg-if", - "libc", - "windows-link", -] - -[[package]] -name = "http" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "http-body" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "hybrid-array" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" -dependencies = [ - "typenum", -] - -[[package]] -name = "hyper" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "h2", - "http", - "http-body", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" -dependencies = [ - "http", - "hyper", - "hyper-util", - "log", - "rustls", - "rustls-native-certs", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-timeout" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" -dependencies = [ - "hyper", - "hyper-util", - "pin-project-lite", - "tokio", - "tower-service", -] - -[[package]] -name = "hyper-util" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" -dependencies = [ - "base64 0.23.1", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "httparse", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[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 = "icu_collections" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" - -[[package]] -name = "icu_properties" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" - -[[package]] -name = "icu_provider" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "id-arena" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "2.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" -dependencies = [ - "equivalent", - "hashbrown 0.17.0", - "serde", - "serde_core", -] - -[[package]] -name = "ipnet" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" - -[[package]] -name = "iri-string" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20" -dependencies = [ - "memchr", - "serde", -] - -[[package]] -name = "is_ci" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itertools" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "jiff" -version = "0.2.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" -dependencies = [ - "defmt", - "jiff-core 0.1.8", - "jiff-static 0.2.38", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", -] - -[[package]] -name = "jiff" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5e77cbfb9fff4798e283c2d69dff39fc2c45e7da017e5ce95b654e46ea41236" -dependencies = [ - "jiff-core 1.0.1", - "jiff-static 1.0.2", - "log", - "portable-atomic", - "portable-atomic-util", - "serde_core", -] - -[[package]] -name = "jiff-core" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e599b80292e597019b8b3e392de3f4bea2959ddfb8c7dff60e035e9e311a2c1b" -dependencies = [ - "log", -] - -[[package]] -name = "jiff-core" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6b46a105a9874634dd96231021526bf24ca04955a5998c59a9c7666e634b7b8" -dependencies = [ - "log", -] - -[[package]] -name = "jiff-static" -version = "0.2.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" -dependencies = [ - "jiff-core 0.1.8", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "jiff-static" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9067a0b23e5be3147d56b2dcf652b18e6b1364caca93fb157653b6fbcab23a9" -dependencies = [ - "jiff-core 1.0.1", - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "jni" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" -dependencies = [ - "cfg-if", - "combine", - "jni-macros", - "jni-sys", - "log", - "simd_cesu8", - "thiserror 2.0.20", - "walkdir", - "windows-link", -] - -[[package]] -name = "jni-macros" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "simd_cesu8", - "syn 2.0.117", -] - -[[package]] -name = "jni-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" -dependencies = [ - "jni-sys-macros", -] - -[[package]] -name = "jni-sys-macros" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" -dependencies = [ - "quote", - "syn 2.0.117", -] - -[[package]] -name = "jobserver" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" -dependencies = [ - "getrandom 0.3.4", - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce57d20d1ea864ce2ac172ab472d409214f4fd359f0b2a2775abdf522e2af99e" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "json-patch" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72" -dependencies = [ - "jsonptr", - "serde", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "jsonpath-rust" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c83bc96c838e7a3de9dc89ea291363ac073371959637e3b2207556e9320547b8" -dependencies = [ - "pest", - "pest_derive", - "regex", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "jsonptr" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "jsonwebtoken" -version = "10.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0529410abe238729a60b108898784df8984c87f6054c9c4fcacc47e4803c1ce1" -dependencies = [ - "aws-lc-rs", - "base64 0.22.1", - "getrandom 0.2.17", - "js-sys", - "pem 3.0.6", - "serde", - "serde_json", - "signature", - "simple_asn1", -] - -[[package]] -name = "k8s-openapi" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab0d13801242174b1f3966907c3f32039f2d6b36c7ce82c61225d66ed5d1eb70" -dependencies = [ - "base64 0.22.1", - "jiff 0.2.38", - "serde", - "serde_json", -] - -[[package]] -name = "kube" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f95e1a9107878bef32cfbe2e5e084584db832c9616df9981adc4673f9fb1c853" -dependencies = [ - "k8s-openapi", - "kube-client", - "kube-core", - "kube-derive", - "kube-runtime", -] - -[[package]] -name = "kube-client" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703ee17477c86501627e83492895c06ab6fc2c55a319bb2fbc582ccae739ba67" -dependencies = [ - "base64 0.23.1", - "bytes", - "either", - "futures", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-timeout", - "hyper-util", - "jiff 0.2.38", - "jsonpath-rust", - "k8s-openapi", - "kube-core", - "pem 4.0.0", - "percent-encoding", - "rustls", - "rustls-platform-verifier", - "secrecy", - "serde", - "serde-saphyr", - "serde_json", - "thiserror 2.0.20", - "tokio", - "tokio-util", - "tower", - "tower-http 0.7.1", - "tracing", -] - -[[package]] -name = "kube-core" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e9a9aa533b2f4106ac1ac45e168bb452325eb9e918d57335444f60bef34ffc" -dependencies = [ - "derive_more", - "form_urlencoded", - "http", - "jiff 0.2.38", - "json-patch", - "k8s-openapi", - "schemars", - "serde", - "serde-value", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "kube-derive" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cedc991dbe7757a646098dead35e070e13ce66e2996b02162ac7f97eb97f4d6e" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "serde", - "serde_json", - "syn 3.0.5", -] - -[[package]] -name = "kube-runtime" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca78d9eeb4674eb75e381e6a956e8a5005942928dec87de4db9ef9701af8a637" -dependencies = [ - "ahash", - "async-broadcast", - "async-stream", - "backon", - "educe", - "futures", - "hashbrown 0.16.1", - "hostname", - "json-patch", - "k8s-openapi", - "kube-client", - "parking_lot 0.13.0", - "pin-project", - "serde", - "serde_json", - "thiserror 2.0.20", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "leb128fmt" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "libredox" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f02ab6bace2054fb888a3c16f990117b579d14a3088e472d63c6011fa185c9d3" -dependencies = [ - "libc", -] - -[[package]] -name = "libsqlite3-sys" -version = "0.39.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0e7f1cd558a82cc3af091ed13f0f03846f89851c60a10713ce5cfd484195494" -dependencies = [ - "cc", - "pkg-config", - "vcpkg", -] - -[[package]] -name = "libtest-mimic" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14e6ba06f0ade6e504aff834d7c34298e5155c6baca353cc6a4aaff2f9fd7f33" -dependencies = [ - "anstream", - "anstyle", - "clap", - "escape8259", -] - -[[package]] -name = "linkme" -version = "0.3.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a4e12fd3f6b22d5bc28beccac0f53bb35db4a897c6ddb709c4a0161f72eb6e" -dependencies = [ - "linkme-impl", -] - -[[package]] -name = "linkme-impl" -version = "0.3.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cd04c256b1cd686a45898c8fd150c79b801d96a3eb7bae1075f9eb3b4b85c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - -[[package]] -name = "litemap" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "lock_api" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" - -[[package]] -name = "matchit" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" - -[[package]] -name = "md-5" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" -dependencies = [ - "cfg-if", - "digest 0.11.2", -] - -[[package]] -name = "memchr" -version = "2.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" - -[[package]] -name = "miette" -version = "7.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" -dependencies = [ - "backtrace", - "backtrace-ext", - "cfg-if", - "miette-derive", - "owo-colors", - "supports-color", - "supports-hyperlinks", - "supports-unicode", - "terminal_size", - "textwrap", - "unicode-width 0.1.14", -] - -[[package]] -name = "miette-derive" -version = "7.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[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.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", -] - -[[package]] -name = "mio" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "multimap" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" - -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - -[[package]] -name = "newtype-uuid" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa56da58097c7ae893c4097bb6d91bb5f7fa330053e07e033349db4d5f83ba8" -dependencies = [ - "uuid", -] - -[[package]] -name = "nix" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" -dependencies = [ - "bitflags 2.13.2", - "cfg-if", - "cfg_aliases", - "libc", -] - -[[package]] -name = "nohash-hasher" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" - -[[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 = "noyalib" -version = "0.0.53" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "962838abbd8dd2cd3844d2208dc502458bba6985f8bf1dc21761b30260fcbd7f" -dependencies = [ - "hashbrown 0.17.0", - "indexmap", - "libm", - "memchr", - "rustc-hash", - "serde_core", - "smallvec", -] - -[[package]] -name = "num-bigint" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967" - -[[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-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "oauth2" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d" -dependencies = [ - "base64 0.22.1", - "chrono", - "getrandom 0.2.17", - "http", - "rand 0.8.6", - "reqwest", - "serde", - "serde_json", - "serde_path_to_error", - "sha2 0.10.9", - "thiserror 1.0.69", - "url", -] - -[[package]] -name = "objc2-core-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "objc2-system-configuration" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" -dependencies = [ - "objc2-core-foundation", -] - -[[package]] -name = "object" -version = "0.37.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" -dependencies = [ - "memchr", -] - -[[package]] -name = "oid-registry" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" -dependencies = [ - "asn1-rs", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -dependencies = [ - "critical-section", - "portable-atomic", -] - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "openshell-bootstrap" -version = "0.0.0" -dependencies = [ - "bytes", - "miette", - "openshell-core", - "openshell-crypto", - "rcgen", - "serde", - "serde_json", - "tempfile", - "tokio", - "tracing", -] - -[[package]] -name = "openshell-core" -version = "0.0.0" -dependencies = [ - "async-trait", - "base64 0.22.1", - "glob", - "ipnet", - "jiff 1.0.2", - "libc", - "miette", - "nix", - "openshell-crypto", - "openshell-extension-core", - "openshell-policy-schema", - "openshell-spiffe", - "prost", - "prost-types", - "protoc-bin-vendored", - "reqwest", - "rustix", - "rustls", - "serde", - "serde_json", - "sha2 0.10.9", - "thiserror 2.0.20", - "tokio", - "tokio-stream", - "tokio-util", - "tonic", - "tonic-prost", - "tonic-prost-build", - "tonic-types", - "tracing", - "url", - "uuid", - "windows-sys 0.61.2", -] - -[[package]] -name = "openshell-crypto" -version = "0.0.0" -dependencies = [ - "aws-lc-rs", - "jsonwebtoken", - "kube", - "pem 3.0.6", - "rcgen", - "rustls", - "serde", - "sqlx", - "thiserror 2.0.20", - "tonic", - "x509-parser", -] - -[[package]] -name = "openshell-extension-core" -version = "0.0.0" -dependencies = [ - "h2", - "hyper", - "hyper-util", - "serde", - "thiserror 2.0.20", - "tokio", - "tonic", - "tower", -] - -[[package]] -name = "openshell-policy" -version = "0.0.0" -dependencies = [ - "hickory-proto", - "miette", - "openshell-core", - "openshell-policy-schema", - "prost", - "prost-types", - "serde", - "serde_json", -] - -[[package]] -name = "openshell-policy-schema" -version = "0.0.0" -dependencies = [ - "miette", - "noyalib", - "serde", - "serde_json", - "serde_path_to_error", - "thiserror 2.0.20", -] - -[[package]] -name = "openshell-providers" -version = "0.0.0" -dependencies = [ - "glob", - "noyalib", - "openshell-core", - "openshell-policy", - "prost-types", - "serde", - "serde_json", - "thiserror 2.0.20", - "url", -] - -[[package]] -name = "openshell-sdk" -version = "0.0.0" -dependencies = [ - "async-stream", - "async-trait", - "futures", - "hyper", - "hyper-util", - "miette", - "oauth2", - "openshell-core", - "openshell-crypto", - "reqwest", - "rustls", - "serde", - "thiserror 2.0.20", - "tokio", - "tokio-rustls", - "tokio-tungstenite", - "tonic", - "tower", - "tracing", -] - -[[package]] -name = "openshell-spiffe" -version = "0.0.0" -dependencies = [ - "async-trait", - "base64 0.22.1", - "serde", - "serde_json", - "thiserror 2.0.20", -] - -[[package]] -name = "openshell-testkit" -version = "0.0.0" -dependencies = [ - "clap", - "futures", - "libc", - "libtest-mimic", - "linkme", - "noyalib", - "openshell-bootstrap", - "openshell-core", - "openshell-crypto", - "openshell-policy", - "openshell-providers", - "openshell-sdk", - "openshell-testkit-macros", - "prost-types", - "quick-junit", - "rand 0.9.4", - "reqwest", - "rustls", - "rustls-native-certs", - "serde", - "serde_json", - "tempfile", - "tokio", - "tonic", -] - -[[package]] -name = "openshell-testkit-macros" -version = "0.0.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "openssl-probe" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" - -[[package]] -name = "ordered-float" -version = "2.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" -dependencies = [ - "num-traits", -] - -[[package]] -name = "owo-colors" -version = "4.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d211803b9b6b570f68772237e415a029d5a50c65d382910b879fb19d3271f94d" - -[[package]] -name = "parking" -version = "2.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api 0.4.14", - "parking_lot_core 0.9.12", -] - -[[package]] -name = "parking_lot" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226" -dependencies = [ - "lock_api 0.5.0", - "parking_lot_core 0.10.0", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall 0.5.18", - "smallvec", - "windows-link", -] - -[[package]] -name = "parking_lot_core" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826" -dependencies = [ - "libc", - "redox_syscall 0.9.5", - "smallvec", - "windows-link", -] - -[[package]] -name = "pem" -version = "3.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" -dependencies = [ - "base64 0.22.1", - "serde_core", -] - -[[package]] -name = "pem" -version = "4.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120" -dependencies = [ - "base64 0.23.1", - "serde_core", -] - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pest" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0848c601009d37dfa3430c4666e147e49cdcf1b92ecd3e63657d8a5f19da662" -dependencies = [ - "memchr", - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11f486f1ea21e6c10ed15d5a7c77165d0ee443402f0780849d1768e7d9d6fe77" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8040c4647b13b210a963c1ed407c1ff4fdfa01c31d6d2a098218702e6664f94f" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "pest_meta" -version = "2.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220" -dependencies = [ - "pest", - "sha2 0.10.9", -] - -[[package]] -name = "petgraph" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" -dependencies = [ - "fixedbitset", - "hashbrown 0.15.5", - "indexmap", -] - -[[package]] -name = "pin-project" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "pkg-config" -version = "0.3.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" - -[[package]] -name = "podman" -version = "0.0.0" -dependencies = [ - "base64 0.22.1", - "container-engine-support", - "openshell-testkit", - "podman-support", - "serde_json", -] - -[[package]] -name = "podman-support" -version = "0.0.0" -dependencies = [ - "container-engine-support", - "openshell-testkit", -] - -[[package]] -name = "portable-atomic" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" - -[[package]] -name = "portable-atomic-util" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" -dependencies = [ - "portable-atomic", -] - -[[package]] -name = "potential_utf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" -dependencies = [ - "zerovec", -] - -[[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.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.117", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "prost" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568" -dependencies = [ - "bytes", - "prost-derive", -] - -[[package]] -name = "prost-build" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" -dependencies = [ - "heck", - "itertools", - "log", - "multimap", - "petgraph", - "prettyplease", - "prost", - "prost-types", - "pulldown-cmark", - "pulldown-cmark-to-cmark", - "regex", - "syn 2.0.117", - "tempfile", -] - -[[package]] -name = "prost-derive" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" -dependencies = [ - "anyhow", - "itertools", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "prost-types" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8991c4cbdb8bc5b11f0b074ffe286c30e523de90fee5ba8132f1399f23cb3dd7" -dependencies = [ - "prost", -] - -[[package]] -name = "protoc-bin-vendored" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa" -dependencies = [ - "protoc-bin-vendored-linux-aarch_64", - "protoc-bin-vendored-linux-ppcle_64", - "protoc-bin-vendored-linux-s390_64", - "protoc-bin-vendored-linux-x86_32", - "protoc-bin-vendored-linux-x86_64", - "protoc-bin-vendored-macos-aarch_64", - "protoc-bin-vendored-macos-x86_64", - "protoc-bin-vendored-win32", -] - -[[package]] -name = "protoc-bin-vendored-linux-aarch_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c" - -[[package]] -name = "protoc-bin-vendored-linux-ppcle_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c" - -[[package]] -name = "protoc-bin-vendored-linux-s390_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0" - -[[package]] -name = "protoc-bin-vendored-linux-x86_32" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5" - -[[package]] -name = "protoc-bin-vendored-linux-x86_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78" - -[[package]] -name = "protoc-bin-vendored-macos-aarch_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092" - -[[package]] -name = "protoc-bin-vendored-macos-x86_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756" - -[[package]] -name = "protoc-bin-vendored-win32" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" - -[[package]] -name = "pulldown-cmark" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" -dependencies = [ - "bitflags 2.13.2", - "memchr", - "unicase", -] - -[[package]] -name = "pulldown-cmark-to-cmark" -version = "22.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50793def1b900256624a709439404384204a5dc3a6ec580281bfaac35e882e90" -dependencies = [ - "pulldown-cmark", -] - -[[package]] -name = "quick-junit" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bae23b8e1a59a90f7bf98caa2f4c8c2eedf6df011c6c88ed633e85a87c84526e" -dependencies = [ - "chrono", - "indexmap", - "newtype-uuid", - "quick-xml", - "strip-ansi-escapes", - "thiserror 2.0.20", - "uuid", -] - -[[package]] -name = "quick-xml" -version = "0.41.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" -dependencies = [ - "memchr", -] - -[[package]] -name = "quote" -version = "1.0.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rand" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", -] - -[[package]] -name = "rand" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" -dependencies = [ - "chacha20", - "getrandom 0.4.2", - "rand_core 0.10.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_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - -[[package]] -name = "rcgen" -version = "0.14.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8" -dependencies = [ - "aws-lc-rs", - "pem 4.0.0", - "rustls-pki-types", - "time", - "x509-parser", - "yasna", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "redox_syscall" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" -dependencies = [ - "bitflags 2.13.2", -] - -[[package]] -name = "ref-cast" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "regex" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" - -[[package]] -name = "reqwest" -version = "0.12.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "rustls", - "rustls-native-certs", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tower", - "tower-http 0.6.8", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted 0.9.0", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" - -[[package]] -name = "rustc-hash" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" - -[[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 = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" -dependencies = [ - "bitflags 2.13.2", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" -dependencies = [ - "aws-lc-rs", - "log", - "once_cell", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-native-certs" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63" -dependencies = [ - "openssl-probe", - "rustls-pki-types", - "schannel", - "security-framework", -] - -[[package]] -name = "rustls-pki-types" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" -dependencies = [ - "zeroize", -] - -[[package]] -name = "rustls-platform-verifier" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" -dependencies = [ - "core-foundation", - "core-foundation-sys", - "jni", - "log", - "once_cell", - "rustls", - "rustls-native-certs", - "rustls-platform-verifier-android", - "rustls-webpki", - "security-framework", - "security-framework-sys", - "webpki-root-certs", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls-platform-verifier-android" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" - -[[package]] -name = "rustls-webpki" -version = "0.103.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" -dependencies = [ - "aws-lc-rs", - "ring", - "rustls-pki-types", - "untrusted 0.9.0", -] - -[[package]] -name = "rustversion" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" - -[[package]] -name = "ryu" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" - -[[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 = "schannel" -version = "0.1.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "schemars" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" -dependencies = [ - "dyn-clone", - "ref-cast", - "schemars_derive", - "serde", - "serde_json", -] - -[[package]] -name = "schemars_derive" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals", - "syn 3.0.5", -] - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "secrecy" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" -dependencies = [ - "zeroize", -] - -[[package]] -name = "security-framework" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" -dependencies = [ - "bitflags 2.13.2", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde-saphyr" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe" -dependencies = [ - "annotate-snippets", - "base64 0.23.1", - "encoding_rs_io", - "granit-parser", - "nohash-hasher", - "num-traits", - "serde_core", - "smallvec", - "zmij", -] - -[[package]] -name = "serde-value" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" -dependencies = [ - "ordered-float", - "serde", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "serde_derive_internals" -version = "0.30.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_path_to_error" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" -dependencies = [ - "itoa", - "serde", - "serde_core", -] - -[[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 = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha1" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "digest 0.11.2", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "digest 0.11.2", -] - -[[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.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "signature" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" -dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "simd_cesu8" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" -dependencies = [ - "rustc_version", - "simdutf8", -] - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "simple_asn1" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" -dependencies = [ - "num-bigint", - "num-traits", - "thiserror 2.0.20", - "time", -] - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" -dependencies = [ - "serde", -] - -[[package]] -name = "socket2" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "spin" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" -dependencies = [ - "lock_api 0.4.14", -] - -[[package]] -name = "sqlx" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edb1dddfbdfe5fb99dba0541a87b2edb8adbd59e45815db22d32d4fbbb8813dd" -dependencies = [ - "sqlx-core", - "sqlx-macros", - "sqlx-mysql", - "sqlx-postgres", - "sqlx-sqlite", -] - -[[package]] -name = "sqlx-core" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08f9787cc5aff062567dea2205f8ae37a617b04342633ab4f74944858ea6072" -dependencies = [ - "base64 0.22.1", - "bytes", - "cfg-if", - "crc", - "crossbeam-queue", - "either", - "event-listener", - "futures-core", - "futures-intrusive", - "futures-io", - "futures-util", - "hashbrown 0.16.1", - "hashlink", - "indexmap", - "log", - "memchr", - "percent-encoding", - "rustls", - "serde", - "serde_json", - "sha2 0.11.0", - "smallvec", - "thiserror 2.0.20", - "tokio", - "tokio-stream", - "tracing", - "url", - "webpki-roots", -] - -[[package]] -name = "sqlx-macros" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf62c58a1e7fd6031ee684eee21d07572f5aebe71c273a01ae4f04eeeba47c47" -dependencies = [ - "proc-macro2", - "quote", - "sqlx-core", - "sqlx-macros-core", - "syn 2.0.117", -] - -[[package]] -name = "sqlx-macros-core" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1ff75c9d609ac84aa8a3e0d92b5c0c54bf541a7f70db492fb40c9a4bea792c8" -dependencies = [ - "cfg-if", - "dotenvy", - "either", - "heck", - "hex", - "proc-macro2", - "quote", - "serde", - "serde_json", - "sha2 0.11.0", - "sqlx-core", - "sqlx-postgres", - "sqlx-sqlite", - "syn 2.0.117", - "thiserror 2.0.20", - "tokio", - "url", -] - -[[package]] -name = "sqlx-mysql" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19eeb93b96eb10a3a59dfb436f3daf87d2fc41168ed9e9dc153ec8257dd6a761" -dependencies = [ - "bitflags 2.13.2", - "byteorder", - "bytes", - "crc", - "digest 0.11.2", - "dotenvy", - "either", - "futures-core", - "futures-util", - "generic-array", - "log", - "percent-encoding", - "serde", - "sha1 0.11.0", - "sha2 0.11.0", - "sqlx-core", - "thiserror 2.0.20", - "tracing", -] - -[[package]] -name = "sqlx-postgres" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0e9e02f764a1fe640eeefc8eb33eeddd274204654ec9f2db8ff851a1dee2364" -dependencies = [ - "atoi", - "base64 0.22.1", - "bitflags 2.13.2", - "byteorder", - "crc", - "dotenvy", - "etcetera", - "futures-channel", - "futures-core", - "futures-util", - "hex", - "hkdf", - "hmac", - "itoa", - "log", - "md-5", - "memchr", - "rand 0.10.2", - "serde", - "serde_json", - "sha2 0.11.0", - "smallvec", - "sqlx-core", - "stringprep", - "thiserror 2.0.20", - "tracing", - "whoami", -] - -[[package]] -name = "sqlx-sqlite" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88b6b78a34ddcb1db4046d462db8f79cee811019d7297b99fca8fac5de26672e" -dependencies = [ - "atoi", - "flume", - "form_urlencoded", - "futures-channel", - "futures-core", - "futures-executor", - "futures-intrusive", - "futures-util", - "libsqlite3-sys", - "log", - "percent-encoding", - "serde", - "sqlx-core", - "thiserror 2.0.20", - "tracing", - "url", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "stringprep" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" -dependencies = [ - "unicode-bidi", - "unicode-normalization", - "unicode-properties", -] - -[[package]] -name = "strip-ansi-escapes" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a8f8038e7e7969abb3f1b7c2a811225e9296da208539e0f79c5251d6cac0025" -dependencies = [ - "vte", -] - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "supports-color" -version = "3.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c64fc7232dd8d2e4ac5ce4ef302b1d81e0b80d055b9d77c7c4f51f6aa4c867d6" -dependencies = [ - "is_ci", -] - -[[package]] -name = "supports-hyperlinks" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e396b6523b11ccb83120b115a0b7366de372751aa6edf19844dfb13a6af97e91" - -[[package]] -name = "supports-unicode" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7401a30af6cb5818bb64852270bb722533397edcfc7344954a38f420819ece2" - -[[package]] -name = "syn" -version = "2.0.117" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.2", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "terminal_size" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "230a1b821ccbd75b185820a1f1ff7b14d21da1e442e22c0863ea5f08771a8874" -dependencies = [ - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "textwrap" -version = "0.16.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" -dependencies = [ - "unicode-linebreak", - "unicode-width 0.2.2", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" -dependencies = [ - "thiserror-impl 2.0.20", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "time" -version = "0.3.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" -dependencies = [ - "deranged", - "itoa", - "num-conv", - "powerfmt", - "serde_core", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" - -[[package]] -name = "time-macros" -version = "0.2.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "tinystr" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -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.53.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" -dependencies = [ - "bytes", - "libc", - "mio", - "parking_lot 0.12.5", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-stream" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-tungstenite" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" -dependencies = [ - "futures-util", - "log", - "rustls", - "rustls-native-certs", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tungstenite", -] - -[[package]] -name = "tokio-util" -version = "0.7.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "futures-util", - "libc", - "pin-project-lite", - "slab", - "tokio", -] - -[[package]] -name = "tonic" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" -dependencies = [ - "async-trait", - "axum", - "base64 0.22.1", - "bytes", - "h2", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-timeout", - "hyper-util", - "percent-encoding", - "pin-project", - "rustls-native-certs", - "socket2", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tokio-stream", - "tower", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tonic-build" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322" -dependencies = [ - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "tonic-prost" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" -dependencies = [ - "bytes", - "prost", - "tonic", -] - -[[package]] -name = "tonic-prost-build" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27" -dependencies = [ - "prettyplease", - "proc-macro2", - "prost-build", - "prost-types", - "quote", - "syn 2.0.117", - "tempfile", - "tonic-build", -] - -[[package]] -name = "tonic-types" -version = "0.14.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8" -dependencies = [ - "prost", - "prost-types", - "tonic", -] - -[[package]] -name = "tower" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" -dependencies = [ - "futures-core", - "futures-util", - "indexmap", - "pin-project-lite", - "slab", - "sync_wrapper", - "tokio", - "tokio-util", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower-http" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" -dependencies = [ - "bitflags 2.13.2", - "bytes", - "futures-util", - "http", - "http-body", - "iri-string", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-http" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c" -dependencies = [ - "base64 0.22.1", - "bitflags 2.13.2", - "bytes", - "http", - "http-body", - "mime", - "percent-encoding", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", - "tracing", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "tungstenite" -version = "0.26.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13" -dependencies = [ - "bytes", - "data-encoding", - "http", - "httparse", - "log", - "rand 0.9.4", - "rustls", - "rustls-pki-types", - "sha1 0.10.6", - "thiserror 2.0.20", - "utf-8", -] - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "ucd-trie" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" - -[[package]] -name = "unicase" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" - -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-linebreak" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" - -[[package]] -name = "unicode-normalization" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-properties" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - -[[package]] -name = "unicode-width" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - -[[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.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", - "serde_derive", -] - -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "uuid" -version = "1.23.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76" -dependencies = [ - "getrandom 0.4.2", - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "vcpkg" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "vte" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "231fdcd7ef3037e8330d8e17e61011a2c244126acc0a982f4040ac3f9f0bc077" -dependencies = [ - "memchr", -] - -[[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.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.3+wasi-0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6" -dependencies = [ - "wit-bindgen 0.57.1", -] - -[[package]] -name = "wasip3" -version = "0.4.0+wasi-0.3.0-rc-2026-01-06" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" -dependencies = [ - "wit-bindgen 0.51.0", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aecb87a33d3b0c5e3b7aa46336eaf486cffafbd281b195e4c8b80d50df2351bf" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.78" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ef4c5d3d2cdf5c54f4231181768f5510842e350db025faf1f7163b1030ed928" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a690d511e3c1a8b3a55e33511e3c2c00c78415cd23650f32b808627f5696b9ed" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "411e4887f0071ef2d2164a9d5fdf2d20efbef78fccd3a78b0c10a1dc5295e48a" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 3.0.5", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.128" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81941cd78d0c92026c33e5e01312845a4cb1e9af3407f9134b100dd03144103e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-encoder" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" -dependencies = [ - "leb128fmt", - "wasmparser", -] - -[[package]] -name = "wasm-metadata" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" -dependencies = [ - "anyhow", - "indexmap", - "wasm-encoder", - "wasmparser", -] - -[[package]] -name = "wasmparser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" -dependencies = [ - "bitflags 2.13.2", - "hashbrown 0.15.5", - "indexmap", - "semver", -] - -[[package]] -name = "web-sys" -version = "0.3.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbddc4a036f00ec4f18c83445bd3115cb306a91da554919a099d9222fe4a7f8" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-root-certs" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "webpki-roots" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "whoami" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" -dependencies = [ - "libc", - "libredox", - "objc2-system-configuration", - "web-sys", -] - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[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.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[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.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[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.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "wit-bindgen" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" -dependencies = [ - "wit-bindgen-rust-macro", -] - -[[package]] -name = "wit-bindgen" -version = "0.57.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" - -[[package]] -name = "wit-bindgen-core" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" -dependencies = [ - "anyhow", - "heck", - "wit-parser", -] - -[[package]] -name = "wit-bindgen-rust" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" -dependencies = [ - "anyhow", - "heck", - "indexmap", - "prettyplease", - "syn 2.0.117", - "wasm-metadata", - "wit-bindgen-core", - "wit-component", -] - -[[package]] -name = "wit-bindgen-rust-macro" -version = "0.51.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" -dependencies = [ - "anyhow", - "prettyplease", - "proc-macro2", - "quote", - "syn 2.0.117", - "wit-bindgen-core", - "wit-bindgen-rust", -] - -[[package]] -name = "wit-component" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" -dependencies = [ - "anyhow", - "bitflags 2.13.2", - "indexmap", - "log", - "serde", - "serde_derive", - "serde_json", - "wasm-encoder", - "wasm-metadata", - "wasmparser", - "wit-parser", -] - -[[package]] -name = "wit-parser" -version = "0.244.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" -dependencies = [ - "anyhow", - "id-arena", - "indexmap", - "log", - "semver", - "serde", - "serde_derive", - "serde_json", - "unicode-xid", - "wasmparser", -] - -[[package]] -name = "writeable" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" - -[[package]] -name = "x509-parser" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" -dependencies = [ - "asn1-rs", - "aws-lc-rs", - "data-encoding", - "der-parser", - "lazy_static", - "nom", - "oid-registry", - "rusticata-macros", - "thiserror 2.0.20", - "time", -] - -[[package]] -name = "yasna" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282" -dependencies = [ - "bit-vec", - "time", -] - -[[package]] -name = "yoke" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", - "synstructure", -] - -[[package]] -name = "zerocopy" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.48" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "zerofrom" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" - -[[package]] -name = "zerotrie" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/tests/suites/drivers/podman/Cargo.toml b/tests/suites/drivers/podman/Cargo.toml deleted file mode 100644 index f45178df31..0000000000 --- a/tests/suites/drivers/podman/Cargo.toml +++ /dev/null @@ -1,37 +0,0 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - -# Each driver suite is its own workspace, with its own lockfile. -[package] -name = "podman" -description = "Drivers suite: Podman driver behavior, such as user namespaces and container lifecycle" -version = "0.0.0" -edition = "2024" -rust-version = "1.95" -license = "Apache-2.0" -repository = "https://github.com/ai-openshell/openshell" -publish = false - -[[test]] -name = "podman-lifecycle" -path = "tests/lifecycle.rs" -harness = false - -[[test]] -name = "podman-oci-identity" -path = "tests/oci_identity.rs" -harness = false - -[[test]] -name = "podman-userns" -path = "tests/userns.rs" -harness = false - -[dependencies] -base64 = "0.22" -container-engine-support = { path = "../../../support/container-engine" } -openshell-testkit = { path = "../../../testkit/testkit" } -podman-support = { path = "../../../support/podman" } -serde_json = "1" - -[workspace] diff --git a/tests/suites/drivers/podman/tests/lifecycle.rs b/tests/suites/drivers/podman/tests/lifecycle.rs deleted file mode 100644 index 92a311ddce..0000000000 --- a/tests/suites/drivers/podman/tests/lifecycle.rs +++ /dev/null @@ -1,152 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Podman driver sandbox lifecycle: what the driver does with its containers -//! when a sandbox's main process stops or an ephemeral sandbox finishes. - -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use base64::Engine as _; -use container_engine_support::Engine; -use testkit::sdk::SandboxPhase; -use testkit::{Context, Error, ResultExt as _}; - -fn main() -> std::process::ExitCode { - testkit::main() -} - -/// Where the driver mounts the sandbox's bootstrap JWT. -const TOKEN_PATH: &str = "/etc/openshell/auth/sandbox.jwt"; -/// How long the gateway may take to report a stopped workload as Error. -const ERROR_TIMEOUT: Duration = Duration::from_secs(30); -/// How long the driver may take to remove an ephemeral sandbox's containers. -const CLEANUP_TIMEOUT: Duration = Duration::from_secs(90); - -/// Stopping a sandbox's workload container is terminal: the driver doesn't -/// relaunch the main process and the sandbox ends in Error. Before the stop, -/// the workload can't read its bootstrap JWT, and the supervisor's copy is -/// unexpired. -#[testkit::test] -async fn stopped_workload_container_is_terminal(cx: &mut Context) -> testkit::Result { - cx.expect_compute_driver("podman").await?; - let engine = Engine::from_env()?; - let sandbox = cx - .sandbox("st") - .command(["sleep", "infinity"]) - .create_ready() - .await?; - - let workload = engine.container_for_role(sandbox.name(), "sandbox").await?; - engine - .output([ - "exec", - &workload, - "/bin/sh", - "-c", - &format!("test ! -r {TOKEN_PATH}"), - ]) - .await - .context("the sandbox workload must not be able to read its bootstrap JWT")?; - - let supervisor = engine - .container_for_role(sandbox.name(), "supervisor") - .await?; - let token = engine.copy_from(&supervisor, TOKEN_PATH).await?; - require_unexpired(&String::from_utf8_lossy(&token))?; - - engine.output(["stop", &workload]).await?; - engine - .wait_running(&workload, false, Duration::from_mins(1)) - .await?; - sandbox - .wait_phase(SandboxPhase::Error, ERROR_TIMEOUT) - .await - .context("a stopped main process makes the sandbox terminal")?; - Ok(()) -} - -/// A detached `--no-keep` sandbox's containers are removed once its main -/// command exits, whether it succeeds or fails. Conformance checks that the -/// gateway forgets the sandbox; this checks the driver's containers. -#[testkit::test] -async fn ephemeral_sandbox_containers_are_removed_after_main_exits( - cx: &mut Context, -) -> testkit::Result { - cx.expect_compute_driver("podman").await?; - let engine = Engine::from_env()?; - let mut sandboxes = Vec::new(); - for (suffix, code) in [("ez", 0), ("ef", 17)] { - let builder = cx.cli_sandbox(suffix); - let release_path = format!("/sandbox/.ephemeral-release-{}", builder.name()); - let script = - format!("while [ ! -e '{release_path}' ]; do sleep 0.1; done; sleep 1; exit {code}"); - let sandbox = builder - .args(["--no-keep"]) - .command(["sh", "-c", &script]) - .create() - .await?; - sandboxes.push((sandbox, release_path, code)); - } - - for (sandbox, release_path, _) in &sandboxes { - sandbox.wait_ready().await?; - testkit::ensure!( - !engine - .containers_for_sandbox_id(sandbox.id()) - .await? - .is_empty(), - "no containers found for sandbox {} ({})", - sandbox.name(), - sandbox.id() - ); - sandbox - .exec(["touch", release_path.as_str()]) - .await? - .success()?; - } - for (sandbox, _, code) in &sandboxes { - testkit::poll_until( - &format!("containers of sandbox {} to be removed", sandbox.name()), - CLEANUP_TIMEOUT, - Duration::from_millis(500), - async || { - let left = engine.containers_for_sandbox_id(sandbox.id()).await?; - Ok(if left.is_empty() { - testkit::Poll::Ready(()) - } else { - testkit::Poll::Pending(format!("containers {left:?}")) - }) - }, - ) - .await - .context(format!("ephemeral sandbox exited {code}"))?; - } - Ok(()) -} - -/// Fail unless `token`'s `exp` claim is in the future. Sandbox tokens use -/// `exp = 0` when no TTL is configured. -fn require_unexpired(token: &str) -> testkit::Result { - let payload = token - .trim() - .split('.') - .nth(1) - .ok_or_else(|| Error::msg("the sandbox JWT has no payload segment"))?; - let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(payload) - .map_err(|err| Error::msg(format!("decode the sandbox JWT payload: {err}")))?; - let claims: serde_json::Value = - serde_json::from_slice(&payload).context("parse the sandbox JWT claims")?; - let exp = claims["exp"] - .as_u64() - .ok_or_else(|| Error::msg(format!("the sandbox JWT has no integer exp: {claims}")))?; - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|err| Error::msg(format!("read the clock: {err}")))? - .as_secs(); - testkit::ensure!( - exp == 0 || exp > now, - "the supervisor's bootstrap JWT expired: exp={exp}, now={now}" - ); - Ok(()) -} diff --git a/tests/suites/drivers/podman/tests/oci_identity.rs b/tests/suites/drivers/podman/tests/oci_identity.rs deleted file mode 100644 index f7ab66daf4..0000000000 --- a/tests/suites/drivers/podman/tests/oci_identity.rs +++ /dev/null @@ -1,98 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Podman driver supervisor identity. -//! -//! Podman runs a sandbox's supervisor container as the workload's resolved -//! OCI identity with no effective capabilities; Docker runs it as a fixed -//! unprivileged user. The workload side of the same image is covered by the -//! `oci-image` feature suite in `tests/suites/features`. - -use container_engine_support::Engine; -use testkit::{Context, ResultExt as _}; - -fn main() -> std::process::ExitCode { - testkit::main() -} - -const OCI_IDENTITY: &str = "2345:2346"; -/// A complete policy without a `process` section, so the sandbox identity -/// falls back to the image `USER`. -const IMAGE_IDENTITY_POLICY: &str = "version: 1 - -filesystem_policy: - include_workdir: true - read_only: [/usr, /lib, /lib64, /proc, /dev/urandom, /etc] - read_write: [/sandbox, /tmp, /dev/null] -landlock: - compatibility: best_effort - -network_policies: {} -"; - -/// The supervisor container runs as the image's numeric `USER`, not root or a -/// fixed user, and has no effective capabilities. -#[testkit::test] -async fn supervisor_runs_as_oci_identity_without_capabilities(cx: &mut Context) -> testkit::Result { - cx.expect_compute_driver("podman").await?; - let engine = Engine::from_env()?; - - let image = engine - .build_test_image( - cx, - "oci-identity", - &format!( - "FROM {} -USER 0:0 -RUN mkdir -p /home/app/project && \\ - chown {OCI_IDENTITY} /home/app /home/app/project && \\ - chmod 0700 /home/app /home/app/project -WORKDIR /home/app/project -USER {OCI_IDENTITY} -", - testkit::base_image() - ), - ) - .await?; - let image_user = engine - .output([ - "image", - "inspect", - "--format", - "{{.Config.User}}", - &image.tag, - ]) - .await?; - testkit::ensure!( - image_user == OCI_IDENTITY, - "the test image has USER {image_user:?}; expected {OCI_IDENTITY}" - ); - - let sandbox = cx - .cli_sandbox("oi") - .image(&image.tag) - .policy_yaml(IMAGE_IDENTITY_POLICY) - .command(["sleep", "infinity"]) - .create_ready() - .await - .context("sandbox starts from the OCI identity image")?; - - let supervisor = engine - .container_for_role(sandbox.name(), "supervisor") - .await?; - let user = engine - .inspect_container(&supervisor, "{{.Config.User}}") - .await?; - testkit::ensure!( - user == OCI_IDENTITY, - "the supervisor container runs as {user:?}; expected the image identity {OCI_IDENTITY}" - ); - let caps = engine - .inspect_container(&supervisor, "{{.EffectiveCaps}}") - .await?; - testkit::ensure!( - caps == "[]", - "the supervisor container has effective capabilities {caps}; expected none" - ); - Ok(()) -} diff --git a/tests/suites/drivers/podman/tests/userns.rs b/tests/suites/drivers/podman/tests/userns.rs deleted file mode 100644 index 6475697b67..0000000000 --- a/tests/suites/drivers/podman/tests/userns.rs +++ /dev/null @@ -1,68 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Podman driver user namespaces. -//! -//! The environment configures the gateway with one user-namespace mode and -//! publishes it (see the `podman-support` crate). The test compares a -//! sandbox's UID map with the one Podman itself gives a container in the same -//! mode, so it doesn't bake a particular Podman mapping into the test. - -use container_engine_support::Engine; -use podman_support::{Userns, normalize_uid_map, reference_uid_map}; -use testkit::{Context, Error, ResultExt as _}; - -fn main() -> std::process::ExitCode { - testkit::main() -} - -const WORKSPACE_OK: &str = "podman-userns-workspace-ok"; -const WORKSPACE_AND_UID_MAP_PROBE: &str = r#"set -eu -workload_owner="$(id -u):$(id -g)" -workspace_owner="$(stat -c '%u:%g' /sandbox)" -printf 'workload-owner=%s\nworkspace-owner=%s\n' "$workload_owner" "$workspace_owner" -test "$(id -u)" -ne 0 -test "$workspace_owner" = "$workload_owner" -probe=$(mktemp /sandbox/userns-probe.XXXXXX) -printf 'workspace probe\n' > "$probe" -rm "$probe" -echo podman-userns-workspace-ok -cat /proc/self/uid_map -"#; - -/// A sandbox gets the UID map Podman gives a container in the gateway's -/// user-namespace mode, and its non-root workload owns and can write to the -/// managed `/sandbox` workspace. -#[testkit::test] -async fn configured_userns_matches_podman_reference(cx: &mut Context) -> testkit::Result { - cx.expect_compute_driver("podman").await?; - let userns = Userns::from_env()?; - let engine = Engine::from_env()?; - let image = testkit::base_image(); - let reference = reference_uid_map(&engine, userns, &image).await?; - - let run = cx - .cli_sandbox("pu") - .image(&image) - .command(["sh", "-c", WORKSPACE_AND_UID_MAP_PROBE]) - .run() - .await? - .success() - .context("sandbox can write to its owned workspace and prints its UID map")?; - testkit::ensure!( - run.stdout.contains(WORKSPACE_OK), - "the non-root workload does not own or cannot write to /sandbox:\n{}", - run.stdout - ); - let sandbox = normalize_uid_map(&run.stdout).ok_or_else(|| { - Error::msg(format!( - "the sandbox printed no UID mappings:\n{}", - run.stdout - )) - })?; - testkit::ensure!( - sandbox == reference, - "the sandbox UID map differs from Podman's {userns:?} reference:\nexpected:\n{reference}\nactual:\n{sandbox}" - ); - Ok(()) -}