diff --git a/.github/workflows/tensorlake-images.yml b/.github/workflows/tensorlake-images.yml new file mode 100644 index 0000000000..4658bb38de --- /dev/null +++ b/.github/workflows/tensorlake-images.yml @@ -0,0 +1,93 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +name: Tensorlake Images + +# Build and register the Tensorlake sandbox and control-plane images with +# crates/openshell-driver-tensorlake/build-images.sh. Tensorlake runs the +# Docker builds, so this job needs only the `tl` CLI and an API key. +# +# Run it by hand. A build with `public: true` registers the pair for every +# Tensorlake project under a versioned name. The version comes from the +# checkout: run the workflow from a release tag to publish that release +# (v0.1.6 -> openshell-tensorlake-0-1-6), or from a branch to publish a +# build named after its short commit. Public names are permanent. Set +# `version` only when you need a name the checkout does not give you. +# +# Required secret: TENSORLAKE_API_KEY, a key for the Tensorlake project that +# owns the images. + +on: + workflow_dispatch: + inputs: + version: + description: "Image version suffix. Default: the release tag on the checkout as 0-1-6, or the short commit." + required: false + type: string + default: "" + public: + description: "Register the images for all Tensorlake projects." + required: false + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: tensorlake-images-${{ inputs.version || github.ref }} + cancel-in-progress: false + +defaults: + run: + shell: bash + +jobs: + build: + name: Build Tensorlake images + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The build script names a public pair after the release tag on HEAD. + fetch-tags: true + + - name: Check inputs + env: + VERSION: ${{ inputs.version }} + PUBLIC: ${{ inputs.public }} + run: | + set -euo pipefail + if [ -n "${VERSION}" ] && ! [[ "${VERSION}" =~ ^[a-z0-9][a-z0-9-]*$ ]]; then + echo "::error::version must contain only lowercase letters, digits, and dashes" >&2 + exit 1 + fi + + - name: Install the Tensorlake CLI + run: | + set -euo pipefail + curl -fsSL https://tensorlake.ai/install | sh + echo "${HOME}/.tensorlake/bin" >> "${GITHUB_PATH}" + + - name: Build and register the images + env: + TENSORLAKE_API_KEY: ${{ secrets.TENSORLAKE_API_KEY }} + VERSION: ${{ inputs.version }} + PUBLIC: ${{ inputs.public == true && '1' || '' }} + run: | + set -euo pipefail + if [ -z "${TENSORLAKE_API_KEY}" ]; then + echo "::error::the TENSORLAKE_API_KEY secret is not set" >&2 + exit 1 + fi + tl whoami + crates/openshell-driver-tensorlake/build-images.sh | tee build-images.log + { + echo "## Tensorlake images" + echo + echo '```' + sed -n '/^Registered:/,$p' build-images.log + echo '```' + } >> "${GITHUB_STEP_SUMMARY}" diff --git a/AGENTS.md b/AGENTS.md index 434d235b4a..67bd6e2296 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,7 @@ Do not rely on this file for a full inventory. The detailed public and contribut | `crates/openshell-driver-kubernetes/` | Kubernetes compute driver | In-process `ComputeDriver` backend for K8s sandbox pods | | `crates/openshell-driver-docker/` | Docker compute driver | In-process `ComputeDriver` backend for local Docker sandbox containers | | `crates/openshell-driver-podman/` | Podman compute driver | In-process `ComputeDriver` backend for local Podman sandbox containers | +| `crates/openshell-driver-tensorlake/` | Tensorlake compute driver | Standalone `ComputeDriver` subprocess that runs each sandbox in a Tensorlake microVM | | `crates/openshell-driver-vm/` | VM compute driver | Standalone libkrun-backed `ComputeDriver` subprocess (embeds its own rootfs + runtime) | | `crates/openshell-driver-mxc/` | Microsoft MXC compute driver | In-process Windows AppContainer and isolation-session compute backend | | `crates/openshell-prover/` | Policy prover | Policy verification and proof generation | diff --git a/Cargo.lock b/Cargo.lock index 006d8dd374..d9e1f751e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4610,6 +4610,31 @@ dependencies = [ "uuid", ] +[[package]] +name = "openshell-driver-tensorlake" +version = "0.0.0" +dependencies = [ + "clap", + "futures", + "miette", + "openshell-core", + "openshell-crypto", + "openshell-isolation-interface", + "openshell-otel", + "openshell-sandbox-backend", + "prost", + "reqwest 0.12.28", + "serde", + "serde_json", + "tar", + "thiserror 2.0.20", + "tokio", + "tokio-stream", + "tonic", + "tracing", + "url", +] + [[package]] name = "openshell-driver-vault" version = "0.0.0" @@ -8224,6 +8249,7 @@ dependencies = [ "futures-core", "pin-project-lite", "tokio", + "tokio-util", ] [[package]] diff --git a/crates/openshell-crypto/README.md b/crates/openshell-crypto/README.md index 68efe366e8..fec4a0aa92 100644 --- a/crates/openshell-crypto/README.md +++ b/crates/openshell-crypto/README.md @@ -130,7 +130,7 @@ not a whole-application crypto coverage claim: | Remaining use | Current scope and follow-up | | --- | --- | -| Reqwest clients (OIDC/JWKS, token exchange, provider refresh, Vault, token grants, telemetry) | These use Rustls's process-default provider after ensuring one exists; they do not necessarily honor an explicitly selected `CryptoContext`. The OpenSSL follow-up must supply compatible preconfigured TLS or another supported transport integration and test actual provider use. | +| Reqwest clients (OIDC/JWKS, token exchange, provider refresh, Vault, Tensorlake, token grants, telemetry) | These use Rustls's process-default provider after ensuring one exists; they do not necessarily honor an explicitly selected `CryptoContext`. The OpenSSL follow-up must supply compatible preconfigured TLS or another supported transport integration and test actual provider use. | | Kubernetes client TLS (`kube-client` 0.99) | The AWS-LC-enabled client attempts to install AWS-LC as the Rustls process default. It does not consult `CryptoContext`; the OpenSSL follow-up must adapt this transport before claiming selected-backend coverage. | | Outer-fence evidence digest (`openshell-isolation-interface::contract`) | The digest binds generation and native enforcement evidence using `sha2` through `Sha256Digest::compute`. This security-relevant hash remains outside facade dispatch and must be migrated with failure propagation before claiming exclusive backend ownership. | | VM image/archive digest verification and cached supervisor validation (`openshell-driver-vm`) | Security-relevant artifact integrity remains outside this runtime credential migration. Moving it requires covering the streaming readers, embedded-artifact cache, and build-time digest generation together; it must be addressed before claiming exclusive backend ownership. | diff --git a/crates/openshell-driver-tensorlake/Cargo.toml b/crates/openshell-driver-tensorlake/Cargo.toml new file mode 100644 index 0000000000..80a5618ecd --- /dev/null +++ b/crates/openshell-driver-tensorlake/Cargo.toml @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-driver-tensorlake" +description = "Tensorlake compute driver for OpenShell" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[[bin]] +name = "openshell-driver-tensorlake" +path = "src/main.rs" + +[dependencies] +openshell-core = { path = "../openshell-core", default-features = false } +openshell-crypto = { workspace = true } +openshell-otel = { path = "../openshell-otel" } +openshell-isolation-interface = { path = "../openshell-isolation-interface" } +openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } +tar = "0.4" + +tokio = { workspace = true } +tonic = { workspace = true, features = ["transport"] } +prost = { workspace = true } +futures = { workspace = true } +tokio-stream = { workspace = true, features = ["sync"] } +reqwest = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +clap = { workspace = true } +tracing = { workspace = true } +miette = { workspace = true } +thiserror = { workspace = true } +url = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true, features = ["test-util"] } + +[lints] +workspace = true diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md new file mode 100644 index 0000000000..86bc96e14b --- /dev/null +++ b/crates/openshell-driver-tensorlake/README.md @@ -0,0 +1,682 @@ +# openshell-driver-tensorlake + +This driver runs each OpenShell sandbox inside its own +[Tensorlake](https://tensorlake.ai) sandbox. A Tensorlake sandbox is a small +virtual machine (VM). The driver is a separate program that runs next to the +OpenShell gateway and talks to Tensorlake for it. + +## Two kinds of sandbox + +Two different things are called "sandbox" on this page: + +- A **Tensorlake sandbox** is the VM. Tensorlake creates it, runs it, and + deletes it. +- An **OpenShell sandbox** is what runs inside that VM: a guard, a workload, + and the policy between them. + +The guard (`openshell-supervisor`) holds the credentials and keeps a +connection to the gateway. The workload (`openshell-sandbox`) runs the +agent's commands. The workload has no network of its own. Every connection +it makes goes through the guard, and the guard applies the policy. + +The guard and the workload run in two different VMs. The workload VM has +no outbound network at all, and the guard VM reaches it through a +Tensorlake tunnel. Credentials never enter the VM that runs the agent. See +[Design decisions](#design-decisions). + +The user-facing page is +[Tensorlake Runtime](../../docs/how-it-works/sandboxes/tensorlake.mdx). + +## How it works + +``` +openshell CLI ──► gateway ──Unix socket──► openshell-driver-tensorlake ──HTTPS──► Tensorlake API + ▲ + │ the guard calls the gateway (outbound only) + ┌──────────────────┴── guard VM: openshell--guard ──┐ ┌── workload VM: openshell- ─────────┐ + │ guard: openshell-supervisor (uid 65534, credentials) │ │ 127.0.0.1:8443 socat forwarder (65533) │ + │ │ OpenShell TLS, end to end │ │ │ veth 169.254.77.1 -> .2:8444 │ + │ ▼ │ │ ┌─▼─ network namespace ───────────────┐ │ + │ 127.0.0.1:18443 ◄── tl sbx tunnel (uid 65533, TL key) ┼───┼─► openshell-sandbox (uid 1000) :8444 │ │ + │ network: internet, or --allow-out │ │ │ └─► agent processes, loopback only │ │ + └───────────────────────────────────────────────────────┘ │ └─────────────────────────────────────┘ │ + │ network: no outbound path at all │ + └─────────────────────────────────────────┘ +``` + +When the gateway asks for a new sandbox: + +1. The driver asks Tensorlake to create two VMs and returns at once. The + workload VM uses the sandbox image and a network policy with internet + access off and an empty allow list. The guard VM uses the guard image + (by default the same image) with 1 vCPU and 1 GiB. +2. In the background, the driver waits until both VMs report `running`. +3. The driver packs two archives. Each file has its owner and permissions + set. The workload archive holds the channel bootstrap and the channel + server key. The guard archive holds the gateway credentials, the + runtime descriptor that points at `127.0.0.1:18443`, and a Tensorlake + key for the tunnel. The driver uploads each archive with the Tensorlake + file API and starts `/opt/openshell/bin/openshell-tensorlake-launch` as + root in each VM with the Tensorlake process API. +4. In the workload VM, the launch script creates a network namespace with + loopback and one veth link, starts `openshell-sandbox` inside it, where + it listens on port 8444, and starts a `socat` forwarder as user 65533 + that accepts the tunnel on `127.0.0.1:8443` and connects over the veth + link. The forwarder exists because the runtime rejects loopback peers + and the Tensorlake tunnel always delivers to loopback. In the guard VM, + the script starts `tl sbx tunnel` as user 65533, which listens on + `127.0.0.1:18443` and relays bytes to port 8443 of the workload VM, and + the guard as user 65534. Neither user can read the other's files. The + guard's TLS handshake runs end to end to the workload; the tunnel and + the forwarder do not inspect the bytes. The workload runtime is PID 1 + of its own PID namespace, so network policy can resolve which binary + opened a connection. +5. The driver reports the sandbox as ready when both launch scripts + started. The gateway marks the sandbox ready when the guard connects to + it. During steps 1 to 5 the driver publishes progress events, so the + CLI shows the VM request, the VM start, the bundle upload, and the wait + for the guard instead of a silent spinner. +6. Every few seconds, the driver checks that both launch scripts are still + running and both VMs still exist. If a script stopped, the driver marks + the sandbox as failed with reason `LauncherExited`, the role, and the + exit status. If a VM is gone, the reason is `TensorlakeTerminated`. + Tensorlake does not restart the script. + +Tensorlake cannot push changes to the driver. So the driver asks Tensorlake +for the list of sandboxes every few seconds. + +### Stop and start + +`openshell sandbox stop` ends the OpenShell processes in both VMs and +suspends the VMs. Tensorlake keeps their disks, so the workspace and the +agent's files stay. To end the processes, the driver runs the launch script +with `--stop` as root: the script signals the previous launch script, kills +what is left in the workload namespace and under the unprivileged +identities, removes the namespace, and removes `/.openshell` and the +runtime directories. Then the driver suspends the VM. + +`openshell sandbox start` resumes the VMs and runs steps 2 to 5 again with +fresh credentials from the gateway. The guard gets a new session and the +workload a new channel key; the old ones are gone with `/.openshell`. The +main process starts again from the beginning, as in the other drivers. + +A failed sandbox cannot be started. Delete and recreate it. The one +exception: when both VMs of a failed sandbox are suspended, the sandbox +shows as stopped, and start launches it again. + +A guard VM suspended by hand, with `tl sbx suspend`, also shows the sandbox +as stopped, and `openshell sandbox start` brings it back. Do not suspend +the workload VM by hand: Tensorlake does not suspend it while the runtime +holds its network namespace, and the command waits for nothing (seen on +2026-10-21). A VM resumed by hand runs nothing of OpenShell; the sandbox +stays stopped until you start it. + +### Where the files live in the VMs + +| Path | VM | Owner | Contents | +|---|---|---|---| +| `/.openshell/channel/sandbox/` (mode 0711) | workload | workload | bootstrap file, TLS certificate, and TLS key for the channel to the guard | +| `/.openshell/supervisor/` (mode 0700) | guard | guard | auth bundle, sandbox token, gateway CA, runtime descriptor | +| `/.openshell/supervisor/env`, `args` | guard | root | the guard's environment and arguments | +| `/.openshell/tunnel/` (mode 0700) | guard | tunnel | `env` with the Tensorlake key, the sandbox API URL, and the platform API URL | +| `/.openshell/tunnel/args` | guard | root | the `tl sbx tunnel` arguments | +| `/.openshell/launch/params` | both | root | the role and the identities for the launch script | +| `/.openshell/launch/resolv.conf` | workload | root | written by the launch script; points the workload at the runtime's DNS relay | +| `/.openshell/launch/pid`, `uids` | both | root | written by the launch script; the PID of the script and the identities it started, so the next launch or a stop can end them | + +### The outer fence + +The workload runs in a network namespace whose only link leads to the +forwarder, and the workload VM gets a Tensorlake network policy that turns +off every outbound connection, DNS included. The only way out is the +channel to the guard, which arrives through the tunnel. The driver writes this recipe into +the sandbox's config, so the gateway knows which fence this sandbox got. +Tensorlake does not report the applied policy, so the driver cannot confirm +it from outside. + +`--allow-out` limits where the guard VM itself can connect. See +[Run the driver](#run-the-driver). + +### Design decisions + +**Why two VMs.** In one VM, a kernel exploit gives the agent the gateway +token and the provider credentials. In two VMs, it gives the agent root in +a VM that holds only its own channel key. Egress is still blocked by the +Tensorlake fence and still mediated by the guard. This matches the +Kubernetes driver, which runs one guard pod per workload pod. + +| Attacker | Gets | +|---|---| +| Agent with a kernel exploit | Root in a VM with no credentials | +| Project member with `tl sbx exec --user root` | Everything in the guard VM | +| Holder of a guard VM's Tensorlake key | Tunnels to any sandbox in the project | + +The guard key is the new exposure. Keep the control plane in a project of +its own. Keys scoped to one tunnel target would close it and need platform +work. + +**Why the tunnel.** Tensorlake has no private network between sandboxes +and no sandbox IP in its API. The HTTPS port proxy terminates TLS, so it +cannot carry the OpenShell channel. The tunnel relays raw TCP and works +with the workload's internet off. Measured on 2026-10-20: 100 tunnels from +one sandbox, 500 concurrent connections through one tunnel, about 300 MiB/s +each way, still relaying after 13 minutes idle, 15 MiB RSS per tunnel. If +Tensorlake adds a sandbox IP, the driver puts it into the `Tcp` transport +and drops the tunnel. Nothing else changes. + +**Why not guards in the control sandbox.** That saves the guard VMs, but +it puts every credential of the project in one kernel, shares 2 vCPUs +across all guards, and drops every session when the control sandbox +restarts. A 4 GiB control sandbox would fit about 50 guards. + +**Cost.** Two VMs per sandbox. The guard VM defaults to 1 vCPU and 1 GiB; +the guard uses about 32 MiB and the tunnel 15 MiB. Both VMs boot in +parallel, so create to ready stays a few seconds. All workload egress +crosses the guard VM, which pays for TLS and policy on it. Raise +`--guard-cpus` for agents that move bulk data. + +## Build the images + +`build-images.sh` builds two images on Tensorlake with the `--cas` flag. +Tensorlake runs each build, so you do not need Docker on your machine. +Images built this way start fast. + +| Image | Default name | Contents | +|---|---|---| +| Sandbox | `openshell-tensorlake` | guard, workload, Tensorlake CLI, socat, launch script | +| Control | `openshell-control` | gateway, this driver, start script | + +The sandbox image serves both VMs of a sandbox. The workload VM runs the +workload runtime from it, the guard VM runs the tunnel and the guard from +it. Set `--guard-image` to use a different image for guard VMs. + +```shell +crates/openshell-driver-tensorlake/build-images.sh +``` + +The control image records the name of the sandbox image. The driver uses +that image unless you set `OPENSHELL_SANDBOX_IMAGE`. So the two images +always work as a pair. + +The script copies the Rust source of your checkout, with uncommitted +changes, into a temporary build folder. Tensorlake uses the folder of the +Dockerfile as the build context, and it does not expand variables in +`FROM`. So both Dockerfiles pin the upstream OpenShell images to the +upstream commit that this branch is based on. Change the pin when you +rebase. + +Keep one pair of image names for development, for example +`openshell-tensorlake-test` and `openshell-control-test`. A build under an +existing name replaces that image, and new sandboxes use the new content. +Delete a name you no longer need with `tl sbx image rm `. + +### Rebuild after a change + +If you changed the launch script or `image/Dockerfile`, rebuild only the +sandbox image. The driver reads the image name on every sandbox create, so +you do not need to restart the control plane: + +```shell +tl sbx image create crates/openshell-driver-tensorlake/image/Dockerfile \ + --registered-name openshell-tensorlake-test --cas +``` + +If you changed the driver, rebuild both images and recreate the control +sandbox. Recreating it discards the gateway state and changes the sandbox +ID, so add the gateway to the CLI again afterwards: + +```shell +SANDBOX_IMAGE=openshell-tensorlake-test CONTROL_IMAGE=openshell-control-test \ + crates/openshell-driver-tensorlake/build-images.sh +RECREATE=1 CONTROL_IMAGE=openshell-control-test \ + crates/openshell-driver-tensorlake/control/deploy.sh +``` + +The sandbox image must not contain `/.openshell`. To add agent tools, build +a new image on top of it. + +### Publish for all Tensorlake users + +Build from a clean checkout, in the project that owns the public images: + +```shell +PUBLIC=1 crates/openshell-driver-tensorlake/build-images.sh +``` + +The script names the pair after the checkout, so a reader can tell what an +image holds and no two publishes share a name: + +| Checkout | Sandbox image | Control image | +|---|---|---| +| Release tag `v0.1.6` | `openshell-tensorlake-0-1-6` | `openshell-control-0-1-6` | +| Prerelease tag `v0.1.6-pre.2` | `openshell-tensorlake-0-1-6-pre-2` | `openshell-control-0-1-6-pre-2` | +| Any other commit | `openshell-tensorlake-` | `openshell-control-` | + +Any Tensorlake project can use a public pair without a build. Public names +must be unique across all of Tensorlake, and Tensorlake has no image tags, +so the version is part of the name. Do not replace a published version. +Publish a new one. Set `VERSION` only when you need a name the checkout +does not give you. + +The images contain no keys. The control plane creates its signing keys at +first start, and `deploy.sh` uploads the Tensorlake key at deploy time. + +The same build runs in CI from the `Tensorlake Images` workflow +(`.github/workflows/tensorlake-images.yml`). Start it by hand from a release +tag or a branch with the `public` flag. It needs the `TENSORLAKE_API_KEY` +repository secret for the project that owns the public images. + +## Run the driver + +The driver and the gateway must run as the same Unix user on the same host. +The gateway needs launch signing (`[openshell.gateway.gateway_jwt]`), and +Tensorlake VMs must be able to reach its address. + +```shell +export TENSORLAKE_API_KEY=... +openshell-driver-tensorlake \ + --bind-socket /run/openshell/tensorlake.sock \ + --grpc-endpoint https://gateway.example.com:8080 \ + --gateway-tls-ca /etc/openshell/gateway-ca.pem \ + --sandbox-image openshell-tensorlake \ + --allow-out api.anthropic.com,github.com + +openshell-gateway --compute-driver tensorlake \ + --compute-driver-socket /run/openshell/tensorlake.sock +``` + +| Flag | Environment | Default | +|---|---|---| +| `--bind-socket` | `OPENSHELL_COMPUTE_DRIVER_SOCKET` | required | +| `--grpc-endpoint` | `OPENSHELL_GRPC_ENDPOINT` | required | +| `--gateway-tls-ca` | `OPENSHELL_TENSORLAKE_GATEWAY_TLS_CA` | required for an `https` endpoint | +| `--tensorlake-api-url` | `TENSORLAKE_API_URL` | `https://sandbox.tensorlake.ai` | +| `--tensorlake-platform-api-url` | `TENSORLAKE_PLATFORM_API_URL` | `https://api.tensorlake.ai`; where the tunnel checks its key | +| `--tensorlake-api-key` | `TENSORLAKE_API_KEY` | required | +| `--sandbox-image` | `OPENSHELL_SANDBOX_IMAGE` | required | +| `--guard-image` | `OPENSHELL_TENSORLAKE_GUARD_IMAGE` | the sandbox image | +| `--guard-cpus` / `--guard-memory-mb` | `OPENSHELL_TENSORLAKE_GUARD_*` | 1 / 1024 | +| `--cpus` / `--memory-mb` / `--disk-mb` | `OPENSHELL_TENSORLAKE_*` | 2 / 4096 / Tensorlake default | +| `--timeout-secs` | `OPENSHELL_TENSORLAKE_TIMEOUT_SECS` | 0 (plan maximum) | +| `--allow-out` | `OPENSHELL_TENSORLAKE_ALLOW_OUT` | empty (internet on for the guard VM) | +| `--poll-interval-secs` | `OPENSHELL_TENSORLAKE_POLL_INTERVAL_SECS` | 3 | +| `--state-dir` | `OPENSHELL_TENSORLAKE_STATE_DIR` | `target/openshell-tensorlake-driver`; the control plane uses `/var/lib/openshell/tensorlake` | +| `--log-level` | `OPENSHELL_LOG_LEVEL` | `info`; also the default level for guards | +| `--otlp-endpoint` | `OPENSHELL_OTLP_ENDPOINT` | none | +| `--gateway-name` | `OPENSHELL_GATEWAY_NAME` | none; used in traces | +| `--admission-config-json` | `OPENSHELL_DRIVER_ADMISSION_CONFIG_JSON` | `{}`; see the gateway's driver admission docs | + +The guard trusts only the certificates in `--gateway-tls-ca`. It does not +trust public root certificates. If your gateway has a public certificate, +pass the root certificate that signed it. + +The Tensorlake timeout counts idle time. Keep the default `0`, which uses +the longest timeout your plan allows (7200 seconds on 2026-10-20). In a +test with a 180 second timeout, a sandbox with no user traffic was still +running and Ready after 5 minutes, so the guard's session and the tunnel +appear to keep the clock reset. Do not rely on that for long pauses. + +When you set `--allow-out`, the VM that runs the guard can connect only to +the hosts you listed, the gateway host, and the Tensorlake hosts the +tunnel talks to: the sandbox API host, every subdomain of it (the port +proxy lives there), and the platform API host. Tensorlake's resolver then +answers only for those names. Internet access stays on in +the Tensorlake policy, because turning it off also turns off DNS, and the +tunnel cannot find its own API. The workload VM always has internet access +off with an empty allow list. + +## Run the control plane on Tensorlake + +The control plane is the gateway and this driver. The `control/` folder +runs both in one long-lived Tensorlake sandbox. + +``` + your machine Tensorlake +┌──────────────┐ login + TLS ┌───────────────────────────────────┐ +│ openshell CLI│ ────────────► │ control sandbox │ +└──────────────┘ │ gateway :8080 (plain HTTP/2) │ + │ ▲ Unix socket │ + │ driver ──► Tensorlake API │ + └────▲──────────────────────────────┘ + │ https://8080-.sandbox.tensorlake.ai + guards in sandbox VMs (public port, TLS at the proxy) +``` + +The Tensorlake port proxy handles TLS. Guards trust the public certificate +bundle in the control image for that connection. + +1. Build the images (see [Build the images](#build-the-images)), or use + the published ones. + +2. Create the sandbox and start the control plane. Set the login service + so that the gateway checks who is calling: + + ```shell + export TENSORLAKE_API_KEY=... + export CONTROL_IMAGE=openshell-control-0-1-5 # or your own build + export OPENSHELL_OIDC_ISSUER=https://idp.example.com/realms/openshell + export OPENSHELL_OIDC_AUDIENCE=openshell-cli + crates/openshell-driver-tensorlake/control/deploy.sh + ``` + + The script copies these variables into + `/etc/openshell-control/control.env` (mode 0600): every + `OPENSHELL_OIDC_*` and `OPENSHELL_TENSORLAKE_*` variable, + `OPENSHELL_DB_URL`, `OPENSHELL_SANDBOX_IMAGE`, `OPENSHELL_GATEWAY_NAME`, + and `OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED`. So the driver settings + with an `OPENSHELL_TENSORLAKE_*` variable, the sandbox image, and the + gateway name can be set this way. The start script sets the socket, the + gateway endpoint, the gateway CA, and the state directory itself. The + Tensorlake API URLs, the log level, and the OTLP endpoint cannot be + changed from the control plane. Then the script starts the control + plane as a managed process that restarts on failure. Run the script + again to change settings. Gateway state stays in `/var/lib/openshell`. + Set `OPENSHELL_DB_URL` to use an external database. `CONTROL_NAME` + changes the sandbox name from `openshell-control`, and + `CONTROL_TIMEOUT_SECS` its idle timeout. + +3. Connect the CLI with the public URL. The CLI opens a browser so you can + log in once. It stores the login and renews it on its own: + + ```shell + openshell gateway add https://8080-.sandbox.tensorlake.ai \ + --oidc-issuer https://idp.example.com/realms/openshell \ + --oidc-client-id openshell-cli \ + --oidc-audience openshell-cli + ``` + + On a machine without a browser, set `OPENSHELL_NO_BROWSER=1` first. The + CLI then prints a code that you enter on another device. For scripts + and CI, set `OPENSHELL_OIDC_CLIENT_SECRET` and the CLI logs in without a + browser. + +### Why every user must log in + +A public gateway is inherent to a remote sandbox provider. Guards in +sandbox VMs must dial the gateway, they cannot hold a Tensorlake key, and +Tensorlake has no inbound tunnel to your machine. So port 8080 must accept +calls from anyone, and the URL is public in every mode. You cannot hide it. +A deployment without an identity provider could use mTLS over a Tensorlake +tunnel instead, but that is not implemented. + +The login is what makes the public URL safe. The gateway checks every call +for a valid login token from your login service. It checks the token's +signature, issuer, audience, and roles. A call without a valid token gets +`Unauthenticated`. The guards' URL uses the sandbox ID because the proxy +resolves sandbox names only for calls that carry a Tensorlake key. +`deploy.sh` prints the ID. + +The full list of gateway settings is in +[Authentication](../../docs/how-it-works/gateways/authentication.mdx). + +### What your login service needs + +OpenShell uses the OpenID Connect standard, so most company login services +work. Yours must offer: + +- Roles inside the token. Keycloak, Okta, and Auth0 can do this. A plain + Google sign-in cannot by itself. +- A public client for the CLI, with PKCE turned on and a redirect to + `http://127.0.0.1` on any port. Its client ID goes to + `--oidc-client-id`. +- Tokens whose `aud` claim matches `OPENSHELL_OIDC_AUDIENCE`. +- Two roles, `openshell-admin` and `openshell-user` by default, given to + the people who need them. Change the names with + `OPENSHELL_OIDC_ADMIN_ROLE` and `OPENSHELL_OIDC_USER_ROLE`. Change where + the gateway looks for roles with `OPENSHELL_OIDC_ROLES_CLAIM` (default + `realm_access.roles`). + +### Test without a login service + +The start script refuses to run without `OPENSHELL_OIDC_ISSUER`, unless +you set `OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1`. With that setting, +anyone who has the URL controls the gateway. Use it only for a short test +with test credentials. Reach the gateway through a Tensorlake tunnel, which +needs your Tensorlake key, instead of the public URL: + +```shell +tl sbx tunnel openshell-control 8080 --listen-port 18080 +openshell gateway add http://127.0.0.1:18080 --name tensorlake +``` + +The control sandbox holds the Tensorlake API key. Do not run other +workloads in it. + +## Scope + +A single team with its own Tensorlake project can run it today. + +## Testing + +There are three layers. The first runs on your machine with no Tensorlake +account. The other two create real VMs and need a Tensorlake key. + +### Unit tests and lint + +```shell +cargo test -p openshell-driver-tensorlake +cargo clippy -p openshell-driver-tensorlake --all-targets -- -D warnings +bash -n crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh \ + crates/openshell-driver-tensorlake/control/*.sh \ + crates/openshell-driver-tensorlake/build-images.sh +``` + +The unit tests cover: + +- Config validation, the redacted debug output, and the hosts that + `--allow-out` adds for the guard VM. +- The archive layout: every file's path, owner, and mode, and that the + split workload bundle holds no gateway token, no Tensorlake key, and no + guard file. +- Request mapping: CPU and memory quantities, Tensorlake names, and the + requests the driver rejects. +- Pairing of workload and guard VMs by name, the phase after a restart, + the phase after each poll observation, and the conditions reported for + stopped and starting sandboxes. +- Launcher failure messages and the progress events the CLI shows. +- The shape of the Tensorlake API requests, and the saved sandbox records + that recovery reads. + +They do not run the launch script, the Tensorlake API, the tunnel, or +policy enforcement. `mise run lint` and `mise run test:rust` run the same +checks for the whole workspace. + +### Conformance suite + +The CLI conformance suite in `tests/suites/conformance/cli` drives a +gateway through the `openshell` binary. It needs `OPENSHELL_BIN` and a +registered gateway, selected with `OPENSHELL_GATEWAY`. Its test files: + +| Test file | Scenarios | Run on Tensorlake | +|---|---|---| +| `smoke` | create, exec, delete | yes | +| `file_transfer` | round trip, git filtering, path safety | yes | +| `policy_advisor` | policy-local, mechanistic-proposal, new-hostname-proposal | yes | +| `lifecycle` | stop, start, delete while stopped | yes | + +The `mechanistic-proposal` scenario opens a TCP connection to `1.1.1.1:443` +from Bash inside the sandbox and expects `DENIED`. It then checks that the +proposal names the Bash binary, so it also proves binary identity through +the tunnel. + +### Verified on Tensorlake + +End-to-end runs on Tensorlake Cloud confirmed: + +- On 2026-10-20: create to Ready in about 4 seconds with two + VMs; `exec` runs as the workload user; the workload VM holds no gateway + token or Tensorlake key and only the runtime, the forwarder, and the + launch script run in it; DNS resolves through the guard; the default + policy denies egress; after `openshell policy update` allows one host + for `/usr/bin/curl`, that fetch returns 200, another host and the same + binary at another path stay denied, and the guard logs the binary + identity; 20 sequential fetches through guard and tunnel took 3.7 + seconds; delete removes both VMs; a guard launcher exit is reported as + `LauncherExited`. +- The VM kernel supports Landlock, seccomp, network, mount, + and PID namespaces; the file API writes as root and the process API runs + the launch script as root; the guard reaches the gateway through the port + proxy; image builds accept the multi-stage Dockerfiles and the `--public` + flag. +- On 2026-10-20, with the control plane on Tensorlake: the conformance + test files `smoke`, `file_transfer`, and `policy_advisor` pass, 7 + scenarios in about 2 minutes, and `mechanistic-proposal` sees `DENIED` + through the tunnel. Killing the launch script in either VM gives + `LauncherExited` with the role in the message. After a control plane + restart, the driver recovered 3 sandboxes; a Ready sandbox stayed Ready + and `exec` worked, and no `name cannot be changed` error appeared. A + sandbox created 3 seconds before the restart had both VMs running but no + launch script, and stayed in `Provisioning`. Delete and recreate such a sandbox. + With a 180 second idle timeout, a sandbox with no user traffic was still + running and Ready after 5 minutes. The tunnel first calls + `api.tensorlake.ai` to check its key, then `sandbox.tensorlake.ai`; the + guard reaches the gateway through `*.sandbox.tensorlake.ai`. A + Tensorlake policy with internet off and an allow list blocks all DNS, + so the tunnel failed with `dns error`; with internet on and an allow + list, listed hosts connect, an unlisted IP is reset at the TLS + handshake, and the resolver answers only for listed names. With + `--allow-out api.anthropic.com`, create to `hello` works and the guard + VM reaches that host. Delete removes both VMs of every sandbox. + +- On 2026-10-21, stop and start: the conformance test file `lifecycle` + passes. Stop takes about 5 seconds, including the launcher's stop run in + both VMs and the two suspend requests. Start resumes both VMs and + reaches Ready in about 4 seconds; a file written to `/sandbox` before + the stop is still there, the main process runs a second time, and a + stopped sandbox can be deleted. A guard VM suspended with `tl sbx + suspend` shows the sandbox as `Stopped` within 3 seconds, and start + brings it back. `tl sbx suspend` on a running workload VM did not finish + within 120 seconds; the driver's stop ends the runtime first and then + suspends without delay. The `smoke` test file still passes. +- On 2026-10-21, user login: with Keycloak 24 in a second Tensorlake + sandbox behind its exposed port, and `OPENSHELL_OIDC_ISSUER` set to that + realm, the gateway discovered the issuer and loaded its keys at start. + `openshell gateway add --oidc-issuer ...` opened the + browser and logged in. With the admin role, the OpenCode case study + passed in full through the public URL: model call, no egress, placeholder + key, rule approved and live in 10 seconds, stop and start. A call without + a token got `Unauthenticated`. A user-role account was denied until an + admin added it to the workspace, then could list and exec but not create + a provider, logged as `insufficient_workspace_role`. One defect: the + Tensorlake port proxy drops `grpc-status` and `grpc-message` from + trailers-only responses, so every denied call through the public URL + reaches the CLI as `protocol error: missing grpc-status trailer`. The + same call through `tl sbx tunnel` shows the real status. Successful + calls, which carry a body, are not affected. + +Three findings shaped the design. The sandbox runtime rejects +boundary peers on loopback, so the tunnel needs the veth forwarder. Binary +identity resolution walks a process's ancestors to its PID namespace init, +so the runtime must run in its own PID namespace. And the transparent TCP capability +is for guards that share the workload's network namespace, so this driver +no longer grants it. + +## Next steps + +This section is a temporary plan. Remove it once the work is done. + +### 1. Case study: run OpenCode on Tensorlake through OpenShell + +The hello test proves the plumbing. The case study proves what a real user +needs: a custom agent image works, the guard injects a real provider +credential, the policy blocks a real agent's stray traffic, and stop and +start keep the agent's files. It follows +[Run your first agent](../../docs/about/run-your-first-agent.mdx), with +OpenCode and the free OpenRouter model, so a viewer needs no paid key. + +The `--from` flag on sandbox create maps to a Tensorlake image name. The +guard VM always uses the driver's guard image. The workload VM uses the +`--from` image, and it needs the launch script, the workload runtime, +`socat`, and `iproute2` from it. + +Tensorlake can import a public OCI image by reference, with +`tl sbx image import ghcr.io/anomalyco/opencode:latest`. That import +works, but the sandbox does not: the launch fails with `LaunchFailed` +because `/opt/openshell/bin/openshell-tensorlake-launch` is not in the +image (tested 2026-10-21). So the agent image must be built on the +sandbox image. The build runs on Tensorlake, so you still need no Docker +on your machine. + +**Build the image.** The Dockerfile in `examples/opencode/` starts from +the sandbox image and installs the OpenCode release binary at the path +named in the `binaries` list of `providers/openrouter.yaml`. It takes the +glibc build from GitHub, not the binary from `ghcr.io/anomalyco/opencode`: +that image is Alpine, and its binary needs the musl loader, which the +Ubuntu base does not have (tested 2026-10-21, `cannot execute: required +file not found`). + +```shell +tl sbx image create crates/openshell-driver-tensorlake/examples/opencode/Dockerfile \ + --registered-name openshell-tensorlake-opencode --cas +``` + +The build takes about a minute. The binary runs on the base, and OpenCode +writes its config and database under `/sandbox`, the workload's home. + +**Create the provider.** The key stays in the gateway and the guard VM. It +never enters the workload VM: + +```shell +openshell profile import --file providers/openrouter.yaml +export OPENROUTER_API_KEY=your_api_key +openshell provider create --name openrouter --type openrouter --from-existing +``` + +**Run the agent:** + +```shell +openshell sandbox create --name demo \ + --from openshell-tensorlake-opencode \ + --provider openrouter \ + -- opencode -m openrouter/nvidia/nemotron-3.5-lightning:free +``` + +**Show the four things.** Record these in order. All four were run on +2026-10-21 against the test control plane, with the sandbox image +`openshell-tensorlake-test` and the free OpenRouter model. + +1. Zero network in the agent VM. Run `openshell sandbox exec -n demo -- + curl -sS https://example.com` and show the failure. Then run + `opencode run -m openrouter/nvidia/nemotron-3.5-lightning:free "reply + with OK"` and show the answer. The only path out is the guard. +2. The credential is not in the agent VM. The workload sees + `OPENROUTER_API_KEY`, but its value is a placeholder that starts with + `openshell:`. The guard swaps in the real key on the way to + `openrouter.ai`. The workload cannot read `/.openshell`. +3. One denied request and one approved rule. Ask OpenCode to run `curl + https://pypi.org/simple/requests/`. The connection fails. Within a few + seconds `openshell rule get demo --status pending` shows a drafted + rule for `pypi.org:443` from `/usr/bin/curl`, and two more for hosts + OpenCode tried on its own, `registry.npmjs.org` and + `models.opencode.ai`. Approve the PyPI rule with `openshell rule + approve demo --chunk-id `. The rule reaches the sandbox in about + 30 seconds, and the same curl then returns the page. +4. Stop and start. Write a file, run `openshell sandbox stop demo` + (Stopped in about 10 s), then `openshell sandbox start demo` (Ready in + about 10 s). The file, the OpenCode database, and the approved rule + are all still there. + +The tutorial page is +[Run OpenCode on Tensorlake](../../docs/tutorials/run-opencode-on-tensorlake.mdx). +It uses the default image name `openshell-tensorlake` in `FROM`; the dev +run above used `openshell-tensorlake-test`. + +### 2. Publish the first public image pair + +Run the `Tensorlake Images` workflow from a release tag with `public: true`, +or run `PUBLIC=1 build-images.sh` from a clean checkout of that tag in the +project that owns the public images. The pair takes its name from the tag. +Publish from a commit whose tests passed, because a published version +cannot be replaced. + +### 3. Later + +- GPU. +- Tensorlake keys scoped to one tunnel target, so a guard VM's key cannot + reach other sandboxes. +- A tunnel that reconnects after a dropped WebSocket, so the sandbox pauses + instead of failing. +- Error status through the port proxy. The proxy drops the gRPC status + from trailers-only responses, so users see `missing grpc-status trailer` + instead of `Unauthenticated` or `PermissionDenied`. Either Tensorlake + fixes the proxy, or the gateway sends errors with a body and trailers. diff --git a/crates/openshell-driver-tensorlake/build-images.sh b/crates/openshell-driver-tensorlake/build-images.sh new file mode 100755 index 0000000000..214d1b6fdd --- /dev/null +++ b/crates/openshell-driver-tensorlake/build-images.sh @@ -0,0 +1,105 @@ +#!/bin/bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Build and register the sandbox image and the control-plane image on +# Tensorlake as CAS images. Tensorlake runs each build, so no local Docker is +# needed. CAS images start fast, because content streams in on demand. +# +# The control image records the sandbox image name, so the two images always +# work as a pair. +# +# Optional: +# PUBLIC=1 publish both images to all Tensorlake projects. The +# checkout must be clean, so the images match a commit. +# VERSION added to the default names as `-`. A public +# build without VERSION takes it from the checkout: the +# release tag on HEAD with dots turned into dashes +# (v0.1.6-pre.2 -> 0-1-6-pre-2), or else the short commit +# hash. So a published pair is named after what it holds. +# SANDBOX_IMAGE full sandbox image name (default: openshell-tensorlake[-VERSION]) +# CONTROL_IMAGE full control image name (default: openshell-control[-VERSION]) + +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "${HERE}/../.." && pwd)" +SOURCE_PATHS=(Cargo.toml Cargo.lock rust-toolchain.toml crates proto providers) + +command -v tl >/dev/null || { echo "error: the tl CLI is not installed" >&2; exit 1; } + +PUBLIC_FLAG=() +if [ "${PUBLIC:-}" = "1" ]; then + if [ -n "$(git -C "${ROOT}" status --porcelain -- "${SOURCE_PATHS[@]}")" ]; then + echo "error: PUBLIC=1 needs a clean checkout; commit or stash your changes" >&2 + exit 1 + fi + PUBLIC_FLAG=(--public) +fi +COMMIT="$(git -C "${ROOT}" rev-parse HEAD)" +if [ -n "$(git -C "${ROOT}" status --porcelain -- "${SOURCE_PATHS[@]}")" ]; then + COMMIT="${COMMIT}-dirty" +fi + +# A public build is named after its source, so no two publishes share a +# name and a reader can tell what an image holds. Tensorlake has no image +# tags, so the version is part of the name. +if [ -z "${VERSION:-}" ] && [ "${PUBLIC:-}" = "1" ]; then + if TAG="$(git -C "${ROOT}" describe --tags --exact-match --match 'v[0-9]*' HEAD 2>/dev/null)"; then + VERSION="${TAG#v}" + VERSION="${VERSION//./-}" + else + VERSION="$(git -C "${ROOT}" rev-parse --short=7 HEAD)" + fi +fi +if [ -n "${VERSION:-}" ] && ! [[ "${VERSION}" =~ ^[a-z0-9][a-z0-9-]*$ ]]; then + echo "error: VERSION must contain only lowercase letters, digits, and dashes: ${VERSION}" >&2 + exit 1 +fi +# VERSION changes only the default names. Names set in SANDBOX_IMAGE or +# CONTROL_IMAGE are used as they are. +SUFFIX="${VERSION:+-${VERSION}}" +SANDBOX_IMAGE="${SANDBOX_IMAGE:-openshell-tensorlake${SUFFIX}}" +CONTROL_IMAGE="${CONTROL_IMAGE:-openshell-control${SUFFIX}}" + +CONTEXT="$(mktemp -d)" +trap 'rm -rf "${CONTEXT}"' EXIT + +# Control-image build context: Dockerfile, start script, pairing data, and +# the Rust source (tracked and new files only, so build outputs stay out). +cp "${HERE}/control/Dockerfile" "${HERE}/control/openshell-control-start.sh" "${CONTEXT}/" +mkdir -p "${CONTEXT}/share" "${CONTEXT}/src" +printf '%s\n' "${SANDBOX_IMAGE}" >"${CONTEXT}/share/sandbox-image" +printf '%s\n' "${COMMIT}" >"${CONTEXT}/share/source-commit" +( + cd "${ROOT}" + git ls-files -z --cached --others --exclude-standard -- "${SOURCE_PATHS[@]}" \ + | while IFS= read -r -d '' file; do + [ -e "${file}" ] && printf '%s\0' "${file}" + done \ + | COPYFILE_DISABLE=1 tar --null -T - -cf - \ + | tar -xf - -C "${CONTEXT}/src" +) + +echo "==> Building sandbox image ${SANDBOX_IMAGE}" +tl sbx image create "${HERE}/image/Dockerfile" \ + --registered-name "${SANDBOX_IMAGE}" \ + --cas ${PUBLIC_FLAG[@]+"${PUBLIC_FLAG[@]}"} + +echo "==> Building control image ${CONTROL_IMAGE} ($(du -sh "${CONTEXT}" | cut -f1) context)" +tl sbx image create "${CONTEXT}/Dockerfile" \ + --registered-name "${CONTROL_IMAGE}" \ + --cas --cpus 8 --memory 16384 --builder_disk_mb 40960 \ + ${PUBLIC_FLAG[@]+"${PUBLIC_FLAG[@]}"} + +cat <&2; exit 1; } +command -v tl >/dev/null || { echo "error: the tl CLI is not installed" >&2; exit 1; } + +if [ "${RECREATE:-}" = "1" ] && tl sbx describe "${NAME}" >/dev/null 2>&1; then + echo "==> Terminating existing sandbox ${NAME}" + tl sbx terminate "${NAME}" +fi +if tl sbx describe "${NAME}" >/dev/null 2>&1; then + echo "==> Using existing sandbox ${NAME}. Set RECREATE=1 to use a new image." + tl sbx kill "${NAME}" "${PROCESS}" >/dev/null 2>&1 || true +else + echo "==> Creating sandbox ${NAME} from image ${IMAGE}" + # The timeout counts idle time. 0 uses the plan maximum, so the control + # plane is not suspended while no user is connected. + tl sbx create "${NAME}" --image "${IMAGE}" --cpus 2 --memory 4096 \ + --timeout "${CONTROL_TIMEOUT_SECS:-0}" +fi + +# Guards in other sandboxes dial this port without a Tensorlake key. The +# proxy resolves sandbox names only for authenticated requests, so guards +# must use the sandbox ID. +SANDBOX_ID="$(tl sbx describe "${NAME}" | awk '/^ID:/ {print $2}')" +[ -n "${SANDBOX_ID}" ] || { echo "error: cannot read the ID of sandbox ${NAME}" >&2; exit 1; } +PUBLIC_URL="https://${PORT}-${SANDBOX_ID}.sandbox.tensorlake.ai" +echo "==> Exposing port ${PORT}" +tl sbx port expose "${NAME}" "${PORT}" + +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "${TMP_DIR}"' EXIT +ENV_FILE="${TMP_DIR}/control.env" +( + umask 077 + { + printf 'TENSORLAKE_API_KEY=%q\n' "${TENSORLAKE_API_KEY}" + printf 'OPENSHELL_CONTROL_PUBLIC_URL=%q\n' "${PUBLIC_URL}" + for var in $(compgen -e); do + case "${var}" in + OPENSHELL_OIDC_* | OPENSHELL_TENSORLAKE_* | OPENSHELL_DB_URL | OPENSHELL_SANDBOX_IMAGE \ + | OPENSHELL_GATEWAY_NAME | OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED) + printf '%s=%q\n' "${var}" "${!var}" + ;; + esac + done + } >"${ENV_FILE}" +) + +echo "==> Uploading settings" +tl sbx cp "${ENV_FILE}" "${NAME}:${REMOTE_ENV}" +tl sbx exec --user root "${NAME}" /bin/sh -c \ + "chown openshell:openshell ${REMOTE_ENV} && chmod 0600 ${REMOTE_ENV} \ + && chown -R openshell:openshell /var/lib/openshell /etc/openshell-control" + +echo "==> Starting the control plane" +tl sbx exec --detach --name "${PROCESS}" --restart always --user openshell \ + "${NAME}" /opt/openshell/bin/openshell-control-start + +cat <&2 +} + +fail() { + log "error: $*" + exit 1 +} + +[ -r "${ENV_FILE}" ] || fail "cannot read ${ENV_FILE}" +set -a +# shellcheck source=/dev/null +. "${ENV_FILE}" +set +a + +# Default to the sandbox image that was built with this control image. +DEFAULT_SANDBOX_IMAGE_FILE=/opt/openshell/share/sandbox-image +if [ -z "${OPENSHELL_SANDBOX_IMAGE:-}" ] && [ -r "${DEFAULT_SANDBOX_IMAGE_FILE}" ]; then + OPENSHELL_SANDBOX_IMAGE="$(cat "${DEFAULT_SANDBOX_IMAGE_FILE}")" +fi + +[ -n "${TENSORLAKE_API_KEY:-}" ] || fail "TENSORLAKE_API_KEY is not set" +[ -n "${OPENSHELL_CONTROL_PUBLIC_URL:-}" ] || fail "OPENSHELL_CONTROL_PUBLIC_URL is not set" +[ -n "${OPENSHELL_SANDBOX_IMAGE:-}" ] || fail "OPENSHELL_SANDBOX_IMAGE is not set" + +# The public port accepts anonymous requests, because guards cannot hold a +# Tensorlake key. So users must authenticate to the gateway itself. +ALLOW_UNAUTHENTICATED=false +if [ -z "${OPENSHELL_OIDC_ISSUER:-}" ]; then + if [ "${OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED:-}" != "1" ]; then + fail "set OPENSHELL_OIDC_ISSUER, or set OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1 for a test gateway" + fi + log "WARNING: user authentication is off. Anyone with ${OPENSHELL_CONTROL_PUBLIC_URL} can control this gateway." + ALLOW_UNAUTHENTICATED=true +fi + +GATEWAY_NAME="${OPENSHELL_GATEWAY_NAME:-tensorlake}" + +if [ ! -f "${KEY_DIR}/jwt/signing.pem" ]; then + log "creating gateway signing keys" + "${BIN_DIR}/openshell-gateway" generate-certs --output-dir "${KEY_DIR}" +fi + +cat >"${CONFIG}" </dev/null || true + fi + done +} +trap stop EXIT +trap 'exit 143' TERM INT + +# The guards dial the public URL. They trust only the given CA bundle, so +# pass the public roots that sign the Tensorlake proxy certificate. +"${BIN_DIR}/openshell-driver-tensorlake" \ + --bind-socket "${SOCKET}" \ + --gateway-name "${GATEWAY_NAME}" \ + --grpc-endpoint "${OPENSHELL_CONTROL_PUBLIC_URL}" \ + --gateway-tls-ca "${PUBLIC_CA}" \ + --sandbox-image "${OPENSHELL_SANDBOX_IMAGE}" \ + --state-dir "${STATE_DIR}/tensorlake" & +DRIVER_PID=$! + +for _ in $(seq 1 50); do + [ -S "${SOCKET}" ] && break + kill -0 "${DRIVER_PID}" 2>/dev/null || fail "compute driver exited during start" + sleep 0.2 +done +[ -S "${SOCKET}" ] || fail "compute driver did not create ${SOCKET}" + +# The gateway does not need the Tensorlake key. +env -u TENSORLAKE_API_KEY "${BIN_DIR}/openshell-gateway" \ + --config "${CONFIG}" \ + --bind-address 0.0.0.0 \ + --port "${PORT}" \ + --disable-tls \ + --compute-driver tensorlake \ + --compute-driver-socket "${SOCKET}" \ + --db-url "${OPENSHELL_DB_URL:-sqlite:${STATE_DIR}/gateway.db?mode=rwc}" & +GATEWAY_PID=$! + +log "control plane started at ${OPENSHELL_CONTROL_PUBLIC_URL}" + +set +e +wait -n "${DRIVER_PID}" "${GATEWAY_PID}" +status=$? +log "a control-plane process exited with status ${status}" +exit "${status}" diff --git a/crates/openshell-driver-tensorlake/examples/opencode/Dockerfile b/crates/openshell-driver-tensorlake/examples/opencode/Dockerfile new file mode 100644 index 0000000000..d940ee19eb --- /dev/null +++ b/crates/openshell-driver-tensorlake/examples/opencode/Dockerfile @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# OpenCode agent image for the Tensorlake driver case study. +# +# It starts from the OpenShell Tensorlake sandbox image, which holds the +# launcher and the workload runtime, and adds the OpenCode binary at the +# path named in providers/openrouter.yaml. Build it on Tensorlake: +# +# tl sbx image create crates/openshell-driver-tensorlake/examples/opencode/Dockerfile \ +# --registered-name openshell-tensorlake-opencode --cas +# +# The binary comes from the GitHub release, not from the +# ghcr.io/anomalyco/opencode image. That image is Alpine, and its binary +# needs the musl loader, which the Ubuntu base does not have. +# +# Tensorlake does not expand variables in FROM, so the base image name is +# fixed here. It is the default sandbox image name. Change it to match your +# image pair, for example openshell-tensorlake-test for a dev build. + +FROM openshell-tensorlake + +ARG OPENCODE_VERSION=1.19.3 +RUN curl -fsSL "https://github.com/anomalyco/opencode/releases/download/v${OPENCODE_VERSION}/opencode-linux-x64.tar.gz" \ + | tar -xz -C /usr/local/bin opencode \ + && chmod 0755 /usr/local/bin/opencode \ + && /usr/local/bin/opencode --version diff --git a/crates/openshell-driver-tensorlake/image/Dockerfile b/crates/openshell-driver-tensorlake/image/Dockerfile new file mode 100644 index 0000000000..151198e17e --- /dev/null +++ b/crates/openshell-driver-tensorlake/image/Dockerfile @@ -0,0 +1,53 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Tensorlake sandbox image for the OpenShell Tensorlake compute driver. +# +# It adds the OpenShell guard (openshell-supervisor), the workload runtime +# (openshell-sandbox), the Tensorlake CLI for the guard's tunnel, and the +# launcher to an Ubuntu base. One image serves both VMs of a sandbox: the +# workload VM runs openshell-sandbox from it, the guard VM runs the tunnel +# and openshell-supervisor from it. Add agent tools (for example Claude +# Code) in a derived image; the guard VM ignores them. +# +# Build and register it on Tensorlake with ../build-images.sh (no local +# Docker needed). +# +# Tensorlake uses this directory as the build context, and does not expand +# variables in FROM, so the image tags are fixed here. Pin the upstream +# commit this branch is based on, the same as control/Dockerfile. + +FROM ghcr.io/nvidia/openshell/supervisor:ea265a2f9a86e6fc1911041fec4b5fdcefd674dd AS supervisor +FROM ghcr.io/nvidia/openshell/sandbox:ea265a2f9a86e6fc1911041fec4b5fdcefd674dd AS sandbox + +FROM ubuntu:24.04 + +# iproute2: the workload network namespace and its veth link. socat: the +# forwarder from the Tensorlake tunnel into that namespace. util-linux: +# unshare and setpriv. ca-certificates: guard TLS to upstreams and the +# tunnel's TLS to the Tensorlake proxy. curl: the tl installer. +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl iproute2 socat util-linux \ + && rm -rf /var/lib/apt/lists/* + +# Tensorlake CLI. The guard VM runs `tl sbx tunnel` to reach the workload +# VM's TLS listener. Pinned; the installer verifies the SHA256SUMS file. +ENV TENSORLAKE_VERSION=cli-v0.5.154 +RUN curl -fsSL https://tensorlake.ai/install \ + | TENSORLAKE_INSTALL=/opt/openshell sh \ + && test -x /opt/openshell/bin/tl + +# Default workload identity (1000:1000), as in other OpenShell drivers. +RUN if ! getent group 1000 >/dev/null; then groupadd --gid 1000 sandbox; fi \ + && if ! getent passwd 1000 >/dev/null; then \ + useradd --uid 1000 --gid 1000 --home-dir /sandbox --no-create-home --shell /bin/bash sandbox; \ + fi \ + && install -d -m 0755 /sandbox /var/lib/openshell + +COPY --from=supervisor /openshell-supervisor /opt/openshell/bin/openshell-supervisor +COPY --from=sandbox /openshell-sandbox /opt/openshell/bin/openshell-sandbox +COPY openshell-tensorlake-launch.sh /opt/openshell/bin/openshell-tensorlake-launch +RUN chmod 0555 /opt/openshell/bin/openshell-supervisor /opt/openshell/bin/openshell-sandbox \ + /opt/openshell/bin/openshell-tensorlake-launch + +WORKDIR /sandbox diff --git a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh new file mode 100755 index 0000000000..71bd2f3ebb --- /dev/null +++ b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh @@ -0,0 +1,317 @@ +#!/bin/bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Start OpenShell inside a Tensorlake sandbox. +# +# The Tensorlake compute driver uploads a launch bundle and runs this script +# as root through the Tensorlake process API. The bundle's launch parameters +# name the role this VM plays: +# +# workload Start the workload runtime (openshell-sandbox) in a network +# namespace that has loopback and one veth link to this VM. It +# listens for the guard on a TLS port. A forwarder in the VM's +# own namespace accepts the Tensorlake tunnel on loopback and +# connects into the workload namespace over the veth link, so +# the runtime sees a non-loopback peer (it rejects loopback +# peers). Tensorlake's network policy gives this VM no outbound +# path; that policy and the namespace are the outer fence. +# guard Start a `tl sbx tunnel` to the workload VM and the guard +# (openshell-supervisor), as two unprivileged identities that +# cannot read each other's files. +# +# The script extracts the bundle with the owners and modes the driver set, +# deletes it, starts the role's processes, and stays in the foreground. It +# exits when any process it started exits. +# +# A sandbox is stopped and started again in the same VMs. Before a launch, +# the script ends the previous generation: it signals the previous script, +# kills what is left in the workload namespace and under the unprivileged +# identities, removes the namespace, and removes `/.openshell` and the +# runtime directories. The workspace stays. `--stop` does only that and +# exits, so the driver can end a generation before it suspends the VM. + +set -euo pipefail + +STOP_ONLY=0 +if [ "${1:-}" = "--stop" ]; then + STOP_ONLY=1 + shift +fi +BUNDLE="${1:-/var/lib/openshell/launch-bundle.tar}" +BIN_DIR=/opt/openshell/bin +PARAMS=/.openshell/launch/params +SUPERVISOR_ENV=/.openshell/supervisor/env +SUPERVISOR_ARGS=/.openshell/supervisor/args +TUNNEL_ENV=/.openshell/tunnel/env +TUNNEL_ARGS=/.openshell/tunnel/args +WORKLOAD_NETNS=openshell-workload +# Link-local addresses for the veth link between the VM and the workload +# namespace. The forwarder connects from .1 to the runtime at .2. +VETH_HOST_ADDR=169.254.77.1 +VETH_WORKLOAD_ADDR=169.254.77.2 +BOOTSTRAP=/.openshell/channel/sandbox/bootstrap.json +WORKLOAD_RESOLV_CONF=/.openshell/launch/resolv.conf +LAUNCH_PID=/.openshell/launch/pid +# Identities the launcher starts processes as, and the directories it +# creates outside /.openshell. The previous generation is ended by these. +LAUNCH_UIDS=/.openshell/launch/uids +RUN_DIRS=(/run/openshell /run/openshell-tunnel /run/openshell-supervisor-ca) + +log() { + printf '[openshell-tensorlake-launch] %s\n' "$*" >&2 +} + +fatal() { + log "FATAL: $*" + exit 1 +} + +[ "$(id -u)" -eq 0 ] || fatal "must run as root" + +# Wait up to $2 seconds for the PIDs in $1 to exit. +wait_gone() { + local pids="$1" deadline=$(($(date +%s) + $2)) pid alive + while :; do + alive=0 + for pid in $pids; do + kill -0 "$pid" 2>/dev/null && alive=1 + done + [ "$alive" -eq 0 ] && return 0 + [ "$(date +%s)" -ge "$deadline" ] && return 1 + sleep 0.2 + done +} + +# PIDs of every process that runs as one of the UIDs in $*. +pids_of_uids() { + local status pid uid + for status in /proc/[0-9]*/status; do + pid="${status#/proc/}" + pid="${pid%/status}" + [ "$pid" -eq "$$" ] && continue + uid="$(awk '/^Uid:/ {print $2; exit}' "$status" 2>/dev/null || true)" + [ -n "$uid" ] || continue + for wanted in "$@"; do + if [ "$uid" = "$wanted" ]; then + printf '%s\n' "$pid" + fi + done + done + # The last test above may fail; that is not an error for `set -e`. + return 0 +} + +# End the previous generation, if there is one, and remove its state. +stop_previous() { + local pids + [ -e /.openshell ] || return 0 + log "stopping the previous OpenShell generation" + if [ -f "$LAUNCH_PID" ]; then + pids="$(cat "$LAUNCH_PID" 2>/dev/null || true)" + if [ -n "$pids" ] && kill -0 "$pids" 2>/dev/null; then + # The previous script's trap ends what it started. + kill -TERM "$pids" 2>/dev/null || true + wait_gone "$pids" 10 || kill -KILL "$pids" 2>/dev/null || true + fi + fi + if ip netns list 2>/dev/null | grep -q "^${WORKLOAD_NETNS}\( \|$\)"; then + pids="$(ip netns pids "$WORKLOAD_NETNS" 2>/dev/null | tr '\n' ' ' || true)" + if [ -n "$pids" ]; then + # shellcheck disable=SC2086 + kill -KILL $pids 2>/dev/null || true + wait_gone "$pids" 10 || log "processes in $WORKLOAD_NETNS did not exit" + fi + ip netns delete "$WORKLOAD_NETNS" || log "cannot delete $WORKLOAD_NETNS" + fi + if [ -f "$LAUNCH_UIDS" ]; then + # shellcheck disable=SC2046 + pids="$(pids_of_uids $(cat "$LAUNCH_UIDS") | tr '\n' ' ' || true)" + if [ -n "$pids" ]; then + # shellcheck disable=SC2086 + kill -TERM $pids 2>/dev/null || true + # shellcheck disable=SC2086 + wait_gone "$pids" 5 || kill -KILL $pids 2>/dev/null || true + fi + fi + rm -rf /.openshell "${RUN_DIRS[@]}" + log "previous generation stopped" +} + +stop_previous +if [ "$STOP_ONLY" -eq 1 ]; then + exit 0 +fi + +[ -f "$BUNDLE" ] || fatal "launch bundle $BUNDLE is missing" + +umask 077 +chmod 0600 "$BUNDLE" +tar --extract --file "$BUNDLE" --directory / --same-owner --same-permissions --numeric-owner +rm -f "$BUNDLE" +printf '%s\n' "$$" >"$LAUNCH_PID" + +# Read launch parameters (KEY=VALUE, numeric values and absolute paths). +ROLE="" +WORKLOAD_UID="" WORKLOAD_GID="" SUPERVISOR_UID="" SUPERVISOR_GID="" TUNNEL_UID="" TUNNEL_GID="" +FORWARDER_UID="" FORWARDER_GID="" WORKLOAD_LISTEN_PORT="" WORKLOAD_FORWARD_PORT="" +WORKSPACE="" SUPERVISOR_RUN_DIR="" TUNNEL_RUN_DIR="" +while IFS='=' read -r key value; do + case "$key" in + ROLE) ROLE="$value" ;; + WORKLOAD_UID) WORKLOAD_UID="$value" ;; + WORKLOAD_GID) WORKLOAD_GID="$value" ;; + SUPERVISOR_UID) SUPERVISOR_UID="$value" ;; + SUPERVISOR_GID) SUPERVISOR_GID="$value" ;; + TUNNEL_UID) TUNNEL_UID="$value" ;; + TUNNEL_GID) TUNNEL_GID="$value" ;; + FORWARDER_UID) FORWARDER_UID="$value" ;; + FORWARDER_GID) FORWARDER_GID="$value" ;; + WORKLOAD_LISTEN_PORT) WORKLOAD_LISTEN_PORT="$value" ;; + WORKLOAD_FORWARD_PORT) WORKLOAD_FORWARD_PORT="$value" ;; + WORKSPACE) WORKSPACE="$value" ;; + SUPERVISOR_RUN_DIR) SUPERVISOR_RUN_DIR="$value" ;; + TUNNEL_RUN_DIR) TUNNEL_RUN_DIR="$value" ;; + "") ;; + *) fatal "unknown launch parameter $key" ;; + esac +done <"$PARAMS" + +require_numeric() { + for id in "$@"; do + [[ "$id" =~ ^[0-9]+$ ]] || fatal "launch identity '$id' is not numeric" + done +} + +require_absolute() { + for path in "$@"; do + [[ "$path" == /* ]] || fatal "launch path '$path' must be absolute" + done +} + +pids=() +cleanup() { + for pid in "${pids[@]}"; do + kill "$pid" 2>/dev/null || true + done +} +trap cleanup EXIT +# A stop arrives as SIGTERM. `wait` returns at once, the EXIT trap ends +# the started processes, and the script exits. +trap 'exit 143' TERM INT + +# Record the identities this generation runs as, so the next launch can +# end what is left of it. +case "$ROLE" in + workload) printf '%s\n' "$WORKLOAD_UID" "$FORWARDER_UID" >"$LAUNCH_UIDS" ;; + guard) printf '%s\n' "$SUPERVISOR_UID" "$TUNNEL_UID" >"$LAUNCH_UIDS" ;; +esac + +# Workload runtime, in private network, mount, and PID namespaces. The +# network namespace has loopback and one veth link to this VM, over which +# the guard connects through the forwarder. The resolver points at the +# sandbox runtime's DNS relay, and unprivileged processes may bind low ports +# so the relay can take port 53. +# +# The runtime is PID 1 of its own PID namespace, with a procfs that shows +# only that namespace. Process identity resolution for network policy walks +# a connecting process's ancestors up to the namespace init; without the +# namespace it would reach this root-owned script and fail. +start_workload() { + require_numeric "$WORKLOAD_UID" "$WORKLOAD_GID" + require_absolute "$WORKSPACE" + install -d -m 0755 "$WORKSPACE" + # Public supervisor CA for workload TLS trust. openshell-sandbox requires + # the parent to be traversable by every workload identity, and creates + # the `material` child as the workload identity. It holds no secrets. + install -d -m 0755 -o "$WORKLOAD_UID" -g "$WORKLOAD_GID" /run/openshell-supervisor-ca + printf 'nameserver 127.0.0.53\noptions timeout:2 attempts:2\n' >"$WORKLOAD_RESOLV_CONF" + chmod 0644 "$WORKLOAD_RESOLV_CONF" + ip netns add "$WORKLOAD_NETNS" + ip link add osfw0 type veth peer name osfw1 + ip link set osfw1 netns "$WORKLOAD_NETNS" + ip addr add "$VETH_HOST_ADDR/30" dev osfw0 + ip link set osfw0 up + ip -n "$WORKLOAD_NETNS" addr add "$VETH_WORKLOAD_ADDR/30" dev osfw1 + ip -n "$WORKLOAD_NETNS" link set osfw1 up + ip -n "$WORKLOAD_NETNS" link set lo up + log "starting workload runtime as ${WORKLOAD_UID}:${WORKLOAD_GID}" + ip netns exec "$WORKLOAD_NETNS" unshare --pid --fork --kill-child --mount-proc \ + --mount --propagation private -- /bin/bash -euc ' + ip link set lo up + echo 0 >/proc/sys/net/ipv4/ip_unprivileged_port_start + mount --bind "$1" /etc/resolv.conf + exec "$2/openshell-sandbox" launch-capability-free "$3" "$4" "$5" "$6" + ' openshell-workload "$WORKLOAD_RESOLV_CONF" "$BIN_DIR" \ + "$WORKLOAD_UID" "$WORKLOAD_GID" "$BOOTSTRAP" "$WORKSPACE" & + pids+=("$!") +} + +# Forwarder for the guard's tunnel. The Tensorlake tunnel delivers to +# 127.0.0.1 in this VM, and the sandbox runtime rejects loopback peers, so +# the forwarder accepts on loopback and connects into the workload namespace +# from the veth address. It runs as an unprivileged identity with no files +# of its own. Every boundary RPC crosses both sockets as small frames, so +# both disable Nagle (nodelay) to avoid delayed-ACK stalls. +start_forwarder() { + require_numeric "$FORWARDER_UID" "$FORWARDER_GID" "$WORKLOAD_LISTEN_PORT" "$WORKLOAD_FORWARD_PORT" + log "starting tunnel forwarder 127.0.0.1:${WORKLOAD_FORWARD_PORT} -> ${VETH_WORKLOAD_ADDR}:${WORKLOAD_LISTEN_PORT}" + setpriv --reuid="$FORWARDER_UID" --regid="$FORWARDER_GID" --clear-groups \ + --inh-caps=-all --bounding-set=-all --no-new-privs \ + env -i PATH=/usr/bin:/bin socat \ + "TCP4-LISTEN:${WORKLOAD_FORWARD_PORT},bind=127.0.0.1,reuseaddr,fork,nodelay" \ + "TCP4:${VETH_WORKLOAD_ADDR}:${WORKLOAD_LISTEN_PORT},bind=${VETH_HOST_ADDR},nodelay" & + pids+=("$!") +} + +# Guard: unprivileged identity, clean environment, no capabilities. +start_guard() { + require_numeric "$SUPERVISOR_UID" "$SUPERVISOR_GID" + require_absolute "$SUPERVISOR_RUN_DIR" + # Guard runtime directory: proxy TLS material, SSH socket, health socket. + install -d -m 0700 -o "$SUPERVISOR_UID" -g "$SUPERVISOR_GID" "$SUPERVISOR_RUN_DIR" + local supervisor_env supervisor_args + mapfile -d '' -t supervisor_env <"$SUPERVISOR_ENV" + mapfile -d '' -t supervisor_args <"$SUPERVISOR_ARGS" + log "starting guard as ${SUPERVISOR_UID}:${SUPERVISOR_GID}" + setpriv --reuid="$SUPERVISOR_UID" --regid="$SUPERVISOR_GID" --clear-groups \ + --inh-caps=-all --bounding-set=-all --no-new-privs \ + env -i "${supervisor_env[@]}" "$BIN_DIR/openshell-supervisor" "${supervisor_args[@]}" & + pids+=("$!") +} + +# Tunnel to the workload VM. The tunnel identity holds the Tensorlake key +# and nothing else; the guard identity cannot read it. +start_tunnel() { + require_numeric "$TUNNEL_UID" "$TUNNEL_GID" + require_absolute "$TUNNEL_RUN_DIR" + install -d -m 0700 -o "$TUNNEL_UID" -g "$TUNNEL_GID" "$TUNNEL_RUN_DIR" + local tunnel_env tunnel_args + mapfile -d '' -t tunnel_env <"$TUNNEL_ENV" + mapfile -d '' -t tunnel_args <"$TUNNEL_ARGS" + log "starting tunnel to the workload VM as ${TUNNEL_UID}:${TUNNEL_GID}" + setpriv --reuid="$TUNNEL_UID" --regid="$TUNNEL_GID" --clear-groups \ + --inh-caps=-all --bounding-set=-all --no-new-privs \ + env -i HOME="$TUNNEL_RUN_DIR" PATH=/usr/bin:/bin "${tunnel_env[@]}" \ + "$BIN_DIR/tl" "${tunnel_args[@]}" & + pids+=("$!") +} + +case "$ROLE" in + workload) + start_workload + start_forwarder + ;; + guard) + start_tunnel + start_guard + ;; + *) fatal "unknown launch role '$ROLE'" ;; +esac + +set +e +wait -n "${pids[@]}" +status=$? +set -e +log "a launched process exited with status $status; stopping the others" +exit "$status" diff --git a/crates/openshell-driver-tensorlake/src/client.rs b/crates/openshell-driver-tensorlake/src/client.rs new file mode 100644 index 0000000000..9b737a2cfa --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/client.rs @@ -0,0 +1,448 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Minimal Tensorlake sandbox HTTP client. +//! +//! Lifecycle calls go to the sandbox API (`POST/GET/DELETE /sandboxes`, +//! `POST /sandboxes/{id}/suspend` and `/resume`). +//! File and process calls go to the per-sandbox proxy (`sandbox_url`) with the +//! `X-Tensorlake-Sandbox-Id` routing header. + +use std::collections::BTreeMap; +use std::time::Duration; + +use reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +const SANDBOX_ID_HEADER: &str = "X-Tensorlake-Sandbox-Id"; +const ROUTE_HINT_HEADER: &str = "X-Tensorlake-Route-Hint"; +/// The Tensorlake SDK sends the client deadline in milliseconds on every +/// request so the server can stop work at the same point. +const REQUEST_TIMEOUT_HEADER: &str = "X-Tensorlake-Request-Timeout-Ms"; + +/// Upper bound on opening a TCP connection to the API or a sandbox proxy. +/// The Tensorlake SDK sets none; this matches the `OpenShell` SDK transport. +const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +/// Upper bound on one whole request, from send to the last response byte. +/// +/// This is the Tensorlake SDK default (`DEFAULT_HTTP_TIMEOUT_SEC`), sized for +/// a blocking create that waits for the server's ready timeout. The driver +/// creates with `wait: false` and uploads only a small configuration tar, so +/// every call should finish well inside it. The bound exists because the +/// status poll awaits launcher checks one sandbox at a time: one stalled +/// connection must fail instead of freezing reconciliation for every sandbox. +const REQUEST_TIMEOUT: Duration = Duration::from_mins(5); + +#[derive(Debug, thiserror::Error)] +pub enum TensorlakeError { + #[error("Tensorlake request failed: {0}")] + Transport(#[from] reqwest::Error), + #[error("Tensorlake API returned {status}: {body}")] + Api { status: StatusCode, body: String }, + #[error("Tensorlake sandbox not found")] + NotFound, + #[error("Tensorlake sandbox {0} has no sandbox_url for file and process calls")] + MissingProxyUrl(String), +} + +#[derive(Debug, Clone, Default, Serialize)] +pub struct CreateSandboxRequest { + #[serde(skip_serializing_if = "Option::is_none")] + pub image: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub resources: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_secs: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub network: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// `false` returns immediately with state `pending`. + #[serde(skip_serializing_if = "Option::is_none")] + pub wait: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct Resources { + pub cpus: f64, + pub memory_mb: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub disk_mb: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct NetworkPolicy { + pub allow_internet_access: bool, + #[serde(default)] + pub allow_out: Vec, + #[serde(default)] + pub deny_out: Vec, +} + +impl NetworkPolicy { + /// No outbound path at all. With an empty allow list, + /// `allow_internet_access: false` turns off every outbound connection, + /// DNS included. Inbound tunnel traffic is not affected. + pub fn no_egress() -> Self { + Self { + allow_internet_access: false, + allow_out: Vec::new(), + deny_out: Vec::new(), + } + } +} + +#[derive(Debug, Clone, Deserialize)] +pub struct CreateSandboxResponse { + pub sandbox_id: String, +} + +/// Subset of Tensorlake `SandboxInfo` used by the driver. +#[derive(Debug, Clone, Deserialize)] +pub struct SandboxInfo { + #[serde(alias = "id")] + pub sandbox_id: String, + #[serde(alias = "state")] + pub status: String, + #[serde(default)] + pub name: Option, + #[serde(default)] + pub sandbox_url: Option, + #[serde(default)] + pub routing_hint: Option, + #[serde(default)] + pub termination_reason: Option, + #[serde(default)] + pub pending_reason: Option, + #[serde(default)] + pub error_details: Option, +} + +#[derive(Debug, Deserialize)] +struct ListSandboxesResponse { + sandboxes: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct StartProcessRequest { + pub command: String, + pub args: Vec, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub env: BTreeMap, + pub user: String, + pub stdin_mode: &'static str, +} + +/// Process state from the Tensorlake process API. +#[derive(Debug, Clone, Deserialize)] +pub struct ProcessInfo { + pub pid: i64, + /// `running`, `exited`, `signaled`, or `oom_killed`. + pub status: String, + #[serde(default)] + pub exit_code: Option, + #[serde(default)] + pub signal: Option, +} + +impl ProcessInfo { + pub fn is_running(&self) -> bool { + self.status == "running" + } + + /// Short summary of how the process ended, for status messages. + pub fn outcome(&self) -> String { + match (self.status.as_str(), self.exit_code, self.signal) { + ("exited", Some(code), _) => format!("exited with status {code}"), + ("signaled", _, Some(signal)) => format!("was killed by signal {signal}"), + ("oom_killed", _, _) => "was killed because it ran out of memory".into(), + (status, _, _) => format!("stopped ({status})"), + } + } +} + +#[derive(Debug, Clone)] +pub struct TensorlakeClient { + http: reqwest::Client, + api_url: String, + api_key: String, +} + +impl TensorlakeClient { + pub fn new(api_url: &str, api_key: &str) -> Result { + // Reqwest uses Rustls's process-default provider. Ensure one exists + // through the crypto facade instead of hard-coding a backend here. + // Classification: like the other Reqwest clients listed in + // `openshell-crypto/README.md`, this transport does not necessarily + // honor an explicitly selected `CryptoContext`. + openshell_crypto::tls::ensure_default_provider(); + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert( + REQUEST_TIMEOUT_HEADER, + reqwest::header::HeaderValue::from_str(&REQUEST_TIMEOUT.as_millis().to_string()) + .expect("a decimal millisecond count is a valid header value"), + ); + let http = reqwest::Client::builder() + .user_agent(format!( + "openshell-driver-tensorlake/{}", + openshell_core::VERSION + )) + .default_headers(headers) + .connect_timeout(CONNECT_TIMEOUT) + .timeout(REQUEST_TIMEOUT) + .build()?; + Ok(Self { + http, + api_url: api_url.trim_end_matches('/').to_string(), + api_key: api_key.to_string(), + }) + } + + pub async fn create_sandbox( + &self, + request: &CreateSandboxRequest, + ) -> Result { + let response = self + .http + .post(format!("{}/sandboxes", self.api_url)) + .bearer_auth(&self.api_key) + .json(request) + .send() + .await?; + Ok(check(response).await?.json().await?) + } + + pub async fn get_sandbox(&self, id: &str) -> Result { + let response = self + .http + .get(format!("{}/sandboxes/{id}", self.api_url)) + .bearer_auth(&self.api_key) + .send() + .await?; + Ok(check(response).await?.json().await?) + } + + pub async fn list_sandboxes(&self) -> Result, TensorlakeError> { + let response = self + .http + .get(format!("{}/sandboxes", self.api_url)) + .bearer_auth(&self.api_key) + .send() + .await?; + let body: ListSandboxesResponse = check(response).await?.json().await?; + Ok(body.sandboxes) + } + + /// Suspend a running sandbox. Tensorlake keeps its disk and memory; + /// the sandbox is `suspending`, then `suspended`. + pub async fn suspend_sandbox(&self, id: &str) -> Result<(), TensorlakeError> { + self.lifecycle_post(id, "suspend").await + } + + /// Resume a suspended sandbox. It is `pending`, then `running`. + pub async fn resume_sandbox(&self, id: &str) -> Result<(), TensorlakeError> { + self.lifecycle_post(id, "resume").await + } + + async fn lifecycle_post(&self, id: &str, action: &str) -> Result<(), TensorlakeError> { + let response = self + .http + .post(format!("{}/sandboxes/{id}/{action}", self.api_url)) + .bearer_auth(&self.api_key) + .send() + .await?; + check(response).await?; + Ok(()) + } + + /// Terminate a sandbox. Returns `false` when it no longer exists. + pub async fn delete_sandbox(&self, id: &str) -> Result { + let response = self + .http + .delete(format!("{}/sandboxes/{id}", self.api_url)) + .bearer_auth(&self.api_key) + .send() + .await?; + match check(response).await { + Ok(_) => Ok(true), + Err(TensorlakeError::NotFound) => Ok(false), + Err(error) => Err(error), + } + } + + /// Write raw bytes to an absolute path inside a running sandbox. + pub async fn write_file( + &self, + sandbox: &SandboxInfo, + path: &str, + contents: Vec, + ) -> Result<(), TensorlakeError> { + let request = self + .proxy_request(sandbox, reqwest::Method::PUT, "/api/v1/files")? + .query(&[("path", path)]) + .body(contents); + check(request.send().await?).await?; + Ok(()) + } + + /// Start a background process inside a running sandbox. + pub async fn start_process( + &self, + sandbox: &SandboxInfo, + request: &StartProcessRequest, + ) -> Result { + let request = self + .proxy_request(sandbox, reqwest::Method::POST, "/api/v1/processes")? + .json(request); + Ok(check(request.send().await?).await?.json().await?) + } + + /// Read one process by PID. Returns `None` when the process is unknown. + pub async fn get_process( + &self, + sandbox: &SandboxInfo, + pid: i64, + ) -> Result, TensorlakeError> { + let request = self.proxy_request( + sandbox, + reqwest::Method::GET, + &format!("/api/v1/processes/{pid}"), + )?; + match check(request.send().await?).await { + Ok(response) => Ok(Some(response.json().await?)), + Err(TensorlakeError::NotFound) => Ok(None), + Err(error) => Err(error), + } + } + + fn proxy_request( + &self, + sandbox: &SandboxInfo, + method: reqwest::Method, + path: &str, + ) -> Result { + let base = proxy_base(sandbox)?; + let mut request = self + .http + .request(method, format!("{base}{path}")) + .bearer_auth(&self.api_key) + .header(SANDBOX_ID_HEADER, &sandbox.sandbox_id); + if let Some(hint) = sandbox.routing_hint.as_deref().filter(|h| !h.is_empty()) { + request = request.header(ROUTE_HINT_HEADER, hint); + } + Ok(request) + } +} + +/// Reduce `sandbox_url` to `scheme://host[:port]`, as the Tensorlake SDK does. +fn proxy_base(sandbox: &SandboxInfo) -> Result { + let missing = || TensorlakeError::MissingProxyUrl(sandbox.sandbox_id.clone()); + let raw = sandbox + .sandbox_url + .as_deref() + .filter(|url| !url.is_empty()) + .ok_or_else(missing)?; + let url = url::Url::parse(raw).map_err(|_| missing())?; + let host = url.host_str().ok_or_else(missing)?; + Ok(url.port().map_or_else( + || format!("{}://{host}", url.scheme()), + |port| format!("{}://{host}:{port}", url.scheme()), + )) +} + +async fn check(response: reqwest::Response) -> Result { + let status = response.status(); + if status.is_success() { + return Ok(response); + } + if status == StatusCode::NOT_FOUND { + return Err(TensorlakeError::NotFound); + } + let body = response.text().await.unwrap_or_default(); + Err(TensorlakeError::Api { + status, + body: body.chars().take(512).collect(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn info(url: Option<&str>) -> SandboxInfo { + SandboxInfo { + sandbox_id: "sbx1".into(), + status: "running".into(), + name: None, + sandbox_url: url.map(str::to_string), + routing_hint: None, + termination_reason: None, + pending_reason: None, + error_details: None, + } + } + + #[test] + fn proxy_base_keeps_scheme_host_and_port() { + assert_eq!( + proxy_base(&info(Some("https://sandbox.tensorlake.ai/some/path"))).unwrap(), + "https://sandbox.tensorlake.ai" + ); + assert_eq!( + proxy_base(&info(Some("http://localhost:9443"))).unwrap(), + "http://localhost:9443" + ); + } + + #[test] + fn proxy_base_requires_sandbox_url() { + assert!(matches!( + proxy_base(&info(None)), + Err(TensorlakeError::MissingProxyUrl(_)) + )); + } + + #[test] + fn create_request_omits_unset_fields() { + let request = CreateSandboxRequest { + image: Some("img".into()), + wait: Some(false), + ..CreateSandboxRequest::default() + }; + assert_eq!( + serde_json::to_value(&request).unwrap(), + serde_json::json!({"image": "img", "wait": false}) + ); + } + + #[test] + fn start_process_request_has_no_managed_process_name() { + let request = StartProcessRequest { + command: "/bin/true".into(), + args: Vec::new(), + env: BTreeMap::new(), + user: "root".into(), + stdin_mode: "closed", + }; + let value = serde_json::to_value(&request).unwrap(); + assert!(value.get("name").is_none()); + } + + #[test] + fn process_outcome_describes_exit() { + let parsed: ProcessInfo = serde_json::from_value(serde_json::json!({ + "handle": 2, "pid": 721, "status": "exited", "exit_code": 1, "signal": null + })) + .unwrap(); + assert!(!parsed.is_running()); + assert_eq!(parsed.outcome(), "exited with status 1"); + } + + #[test] + fn sandbox_info_accepts_id_and_state_aliases() { + let parsed: SandboxInfo = + serde_json::from_value(serde_json::json!({"id": "a", "state": "pending"})).unwrap(); + assert_eq!(parsed.sandbox_id, "a"); + assert_eq!(parsed.status, "pending"); + } +} diff --git a/crates/openshell-driver-tensorlake/src/config.rs b/crates/openshell-driver-tensorlake/src/config.rs new file mode 100644 index 0000000000..1ba5137d9c --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -0,0 +1,318 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Operator configuration for the Tensorlake compute driver. + +use std::path::PathBuf; +use std::time::Duration; + +/// Default Tensorlake sandbox lifecycle API. +pub const DEFAULT_API_URL: &str = "https://sandbox.tensorlake.ai"; + +/// Default Tensorlake platform API. The tunnel in each guard VM checks its +/// key there before it connects to the sandbox API. +pub const DEFAULT_PLATFORM_API_URL: &str = "https://api.tensorlake.ai"; + +/// Default vCPU count when the sandbox template sets no CPU limit. +pub const DEFAULT_CPUS: f64 = 2.0; + +/// Default memory in MiB when the sandbox template sets no memory limit. +pub const DEFAULT_MEMORY_MB: i64 = 4096; + +/// Default status poll interval. Tensorlake has no watch API. +pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(3); + +/// Default vCPU count for a guard VM. +pub const DEFAULT_GUARD_CPUS: f64 = 1.0; + +/// Default memory in MiB for a guard VM. The guard uses about 32 MiB and +/// the tunnel about 15 MiB. +pub const DEFAULT_GUARD_MEMORY_MB: i64 = 1024; + +#[derive(Clone)] +pub struct TensorlakeComputeConfig { + /// Tensorlake sandbox lifecycle API base URL. + pub api_url: String, + /// Tensorlake platform API base URL. The guard VM's tunnel checks its + /// key there, so the host must be reachable from the guard VM. + pub platform_api_url: String, + /// Tensorlake API key. Sent as a bearer token. + pub api_key: String, + /// Registered Tensorlake image that contains the `OpenShell` guard, + /// starter, and launcher. + pub default_image: String, + /// Gateway gRPC endpoint that the guard in each VM dials. + pub grpc_endpoint: String, + /// Gateway CA bundle (PEM). Required for an https endpoint, because the + /// guard trusts only this CA. + pub gateway_tls_ca: Option, + pub default_cpus: f64, + pub default_memory_mb: i64, + pub default_disk_mb: Option, + /// Tensorlake idle timeout. `Some(0)` uses the plan maximum. `None` uses + /// the Tensorlake default (600 seconds). + pub timeout_secs: Option, + /// Tensorlake `allow_out` entries. Empty keeps Tensorlake's default + /// internet access and relies on the `OpenShell` guard alone. + pub allow_out: Vec, + pub poll_interval: Duration, + /// Default log level for the guard when the sandbox spec sets none. + pub log_level: String, + /// Registered Tensorlake image for guard VMs. `None` uses + /// `default_image`, which contains the guard and the Tensorlake CLI. + pub guard_image: Option, + pub guard_cpus: f64, + pub guard_memory_mb: i64, + /// Where the driver keeps a copy of each sandbox request, so that a + /// restart can report recovered sandboxes under their `OpenShell` names. + pub state_dir: PathBuf, +} + +impl std::fmt::Debug for TensorlakeComputeConfig { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("TensorlakeComputeConfig") + .field("api_url", &self.api_url) + .field("platform_api_url", &self.platform_api_url) + .field("api_key", &"[REDACTED]") + .field("default_image", &self.default_image) + .field("grpc_endpoint", &self.grpc_endpoint) + .field("gateway_tls_ca", &self.gateway_tls_ca) + .field("default_cpus", &self.default_cpus) + .field("default_memory_mb", &self.default_memory_mb) + .field("default_disk_mb", &self.default_disk_mb) + .field("timeout_secs", &self.timeout_secs) + .field("allow_out", &self.allow_out) + .field("poll_interval", &self.poll_interval) + .field("guard_image", &self.guard_image) + .field("guard_cpus", &self.guard_cpus) + .field("guard_memory_mb", &self.guard_memory_mb) + .field("state_dir", &self.state_dir) + .finish() + } +} + +impl TensorlakeComputeConfig { + pub fn validate(&self) -> Result<(), String> { + if self.api_key.trim().is_empty() { + return Err("Tensorlake API key is required".into()); + } + if self.default_image.trim().is_empty() { + return Err("Tensorlake sandbox image is required".into()); + } + if self.grpc_endpoint.trim().is_empty() { + return Err( + "gateway gRPC endpoint is required; Tensorlake VMs dial it over the internet" + .into(), + ); + } + let endpoint = url::Url::parse(&self.grpc_endpoint) + .map_err(|error| format!("invalid gateway gRPC endpoint: {error}"))?; + match endpoint.scheme() { + // The guard trusts only OPENSHELL_TLS_CA and has no public roots. + "https" if self.gateway_tls_ca.is_none() => { + return Err( + "an https gateway gRPC endpoint requires a gateway CA bundle; the guard trusts only that CA" + .into(), + ); + } + "http" | "https" => {} + other => { + return Err(format!( + "gateway gRPC endpoint must use http or https, got '{other}'" + )); + } + } + // The guard's tunnel receives these URLs as TENSORLAKE_SANDBOX_API_URL + // and TENSORLAKE_API_URL. The tl CLI silently ignores values of any + // other shape and falls back to the public service, so reject them + // here. + validate_tunnel_url("Tensorlake API URL", &self.api_url)?; + validate_tunnel_url("Tensorlake platform API URL", &self.platform_api_url)?; + if self.default_cpus.is_nan() || self.default_cpus <= 0.0 || self.default_memory_mb <= 0 { + return Err("default CPU and memory must be positive".into()); + } + if self.guard_cpus.is_nan() || self.guard_cpus <= 0.0 || self.guard_memory_mb <= 0 { + return Err("guard CPU and memory must be positive".into()); + } + if self + .guard_image + .as_deref() + .is_some_and(|image| image.trim().is_empty()) + { + return Err("guard image must not be empty".into()); + } + Ok(()) + } + + /// Image for guard VMs. + pub fn guard_image(&self) -> &str { + self.guard_image.as_deref().unwrap_or(&self.default_image) + } + + /// Tensorlake `allow_out` for the guard VM, with the hosts the guard + /// itself needs added: the gateway, the sandbox API that the tunnel + /// relays through, and the platform API where the tunnel checks its + /// key. Verified on 2026-10-20: the tunnel calls + /// `api.tensorlake.ai/platform/v1/keys/introspect` first, then + /// `sandbox.tensorlake.ai`; the guard reaches the gateway through + /// `*.sandbox.tensorlake.ai`. + pub fn effective_allow_out(&self) -> Vec { + let mut entries = self.allow_out.clone(); + if entries.is_empty() { + return entries; + } + let mut push = |host: String| { + if !entries.contains(&host) { + entries.push(host); + } + }; + if let Some(host) = url_host(&self.grpc_endpoint) { + push(host); + } + if let Some(host) = url_host(&self.api_url) { + push(format!("*.{host}")); + push(host); + } + if let Some(host) = url_host(&self.platform_api_url) { + push(host); + } + entries + } +} + +fn url_host(value: &str) -> Option { + url::Url::parse(value) + .ok() + .and_then(|url| url.host_str().map(str::to_string)) +} + +fn validate_tunnel_url(label: &str, value: &str) -> Result<(), String> { + let url = url::Url::parse(value).map_err(|error| format!("invalid {label}: {error}"))?; + if !matches!(url.scheme(), "http" | "https") + || url.host_str().is_none() + || url.query().is_some() + || url.fragment().is_some() + || !url.username().is_empty() + || url.password().is_some() + { + return Err(format!( + "{label} must be an http or https URL with a host and no query, fragment, or credentials" + )); + } + Ok(()) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + pub fn test_config() -> TensorlakeComputeConfig { + TensorlakeComputeConfig { + api_url: DEFAULT_API_URL.into(), + platform_api_url: DEFAULT_PLATFORM_API_URL.into(), + api_key: "key".into(), + default_image: "openshell-tensorlake".into(), + grpc_endpoint: "https://gateway.example.com:8080".into(), + gateway_tls_ca: None, + default_cpus: DEFAULT_CPUS, + default_memory_mb: DEFAULT_MEMORY_MB, + default_disk_mb: None, + timeout_secs: None, + allow_out: Vec::new(), + poll_interval: DEFAULT_POLL_INTERVAL, + log_level: "info".into(), + guard_image: None, + guard_cpus: DEFAULT_GUARD_CPUS, + guard_memory_mb: DEFAULT_GUARD_MEMORY_MB, + state_dir: std::env::temp_dir().join(format!( + "openshell-tensorlake-driver-test-{}", + std::process::id() + )), + } + } + + #[test] + fn empty_allow_out_stays_empty() { + assert!(test_config().effective_allow_out().is_empty()); + } + + #[test] + fn allow_out_includes_gateway_host() { + let mut config = test_config(); + config.allow_out = vec!["api.anthropic.com".into()]; + assert_eq!( + config.effective_allow_out(), + vec![ + "api.anthropic.com", + "gateway.example.com", + "*.sandbox.tensorlake.ai", + "sandbox.tensorlake.ai", + "api.tensorlake.ai" + ] + ); + } + + #[test] + fn allow_out_does_not_repeat_hosts() { + let mut config = test_config(); + config.allow_out = vec!["sandbox.tensorlake.ai".into(), "api.tensorlake.ai".into()]; + assert_eq!( + config.effective_allow_out(), + vec![ + "sandbox.tensorlake.ai", + "api.tensorlake.ai", + "gateway.example.com", + "*.sandbox.tensorlake.ai" + ] + ); + } + + #[test] + fn debug_hides_api_key() { + let mut config = test_config(); + config.api_key = "tl_secret_value".into(); + assert!(!format!("{config:?}").contains("tl_secret_value")); + } + + #[test] + fn validate_rejects_api_urls_the_tunnel_ignores() { + for api_url in [ + "ftp://sandbox.example.test", + "https://sandbox.example.test/?scope=x", + "https://sandbox.example.test/#frag", + "https://user:pw@sandbox.example.test", + ] { + let mut config = test_config(); + config.gateway_tls_ca = Some("ca".into()); + config.api_url = api_url.into(); + assert!(config.validate().is_err(), "{api_url}"); + } + let mut config = test_config(); + config.gateway_tls_ca = Some("ca".into()); + config.api_url = "https://byoc.example.test:8443/base".into(); + assert_eq!(config.validate(), Ok(())); + config.platform_api_url = "https://user:pw@api.example.test".into(); + assert!(config.validate().unwrap_err().contains("platform API URL")); + } + + #[test] + fn validate_rejects_missing_endpoint() { + let mut config = test_config(); + config.grpc_endpoint.clear(); + assert!(config.validate().is_err()); + } + + #[test] + fn validate_requires_ca_for_https_endpoint() { + let mut config = test_config(); + assert!(config.validate().unwrap_err().contains("CA bundle")); + config.gateway_tls_ca = Some(PathBuf::from("/etc/openshell/gateway-ca.pem")); + assert!(config.validate().is_ok()); + config.gateway_tls_ca = None; + config.grpc_endpoint = "http://gateway.example.com:8080".into(); + assert!(config.validate().is_ok()); + config.grpc_endpoint = "ftp://gateway.example.com".into(); + assert!(config.validate().is_err()); + } +} diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs new file mode 100644 index 0000000000..0a7a30d573 --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -0,0 +1,2162 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Tensorlake compute driver. +//! +//! Each `OpenShell` sandbox maps to one Tensorlake sandbox (a small VM) for +//! the workload and a second one for the +//! guard. Create returns after Tensorlake accepts the requests. A background +//! task then waits for the VMs to run, uploads a launch bundle to each, and +//! starts the in-image launcher as root. A poll loop keeps status current +//! because Tensorlake has no watch API. +//! +//! Stop ends the launched processes in both VMs and suspends the VMs, which +//! keep their disks. Start resumes the VMs and launches a new generation +//! with the fresh credentials the gateway sends, so the workspace comes back +//! as it was. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use futures::{Stream, StreamExt as _}; +use openshell_core::progress::{ + PROGRESS_STEP_PULLING_IMAGE, PROGRESS_STEP_REQUESTING_SANDBOX, PROGRESS_STEP_STARTING_SANDBOX, + mark_progress_active, mark_progress_complete, mark_progress_detail, +}; +use openshell_core::proto::compute::v1::{ + CpuResourceCapabilities, DriverCondition, DriverPlatformEvent, DriverSandbox, + DriverSandboxStatus, GetCapabilitiesResponse, GpuResourceCapabilities, + MemoryResourceCapabilities, ResolvedWorkloadIdentity as ProtoIdentity, ResourceCapabilities, + WatchSandboxesDeletedEvent, WatchSandboxesEvent, WatchSandboxesPlatformEvent, + WatchSandboxesSandboxEvent, watch_sandboxes_event, +}; +use openshell_core::resource_admission::DriverAdmissionConfig; +use openshell_isolation_interface::contract::ResolvedWorkloadIdentity; +use tokio::sync::{Mutex, broadcast}; +use tonic::Status; +use tracing::{info, warn}; + +use crate::client::{ + CreateSandboxRequest, NetworkPolicy, ProcessInfo, Resources, SandboxInfo, StartProcessRequest, + TensorlakeClient, TensorlakeError, +}; +use crate::config::TensorlakeComputeConfig; +use crate::launch::{self, LaunchBundleInput}; +use crate::state::StateStore; + +/// Prefix for Tensorlake sandbox names created by this driver. +pub const NAME_PREFIX: &str = "openshell-"; + +/// Suffix of the guard VM's Tensorlake name. +pub const GUARD_NAME_SUFFIX: &str = "-guard"; + +/// How long a Tensorlake sandbox may stay pending before create fails. +const PROVISION_TIMEOUT: Duration = Duration::from_mins(10); + +/// How long stop waits for a VM to leave `pending` or `suspending`, and for +/// the launcher's stop run to finish, before it gives up. +const STOP_TIMEOUT: Duration = Duration::from_mins(3); + +/// How long the launcher's `--stop` run may take to end a generation. +const END_GENERATION_TIMEOUT: Duration = Duration::from_mins(1); + +const WATCH_BUFFER: usize = 256; + +/// `source` of the platform events this driver publishes. +const EVENT_SOURCE: &str = "tensorlake"; + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Phase { + /// Tensorlake accepted the sandbox; the VM is not running yet. + Pending, + /// The VM runs; the driver is uploading the bundle and starting the launcher. + Launching, + /// The launcher started. The gateway waits for the guard session. + Running, + /// Both VMs are suspended, or one of them is. The disks are kept, and + /// start resumes the VMs and launches a new generation. + Stopped, + Failed { + reason: String, + message: String, + }, + Deleting, +} + +#[derive(Debug, Clone)] +struct Record { + sandbox: DriverSandbox, + /// The workload VM. + tensorlake_id: String, + tensorlake_name: String, + /// The guard VM. Empty for a recovered record whose guard VM is gone. + guard_tensorlake_id: String, + identity: Option, + phase: Phase, + /// PID of the launcher in the workload VM. `None` for recovered records. + launcher_pid: Option, + /// PID of the launcher in the guard VM. `None` for recovered records. + guard_launcher_pid: Option, + /// Counts launches. A provisioning task changes the record only while + /// its launch is the current one; stop and start each begin a new one. + launch: u64, +} + +impl Record { + fn snapshot(&self) -> DriverSandbox { + let mut sandbox = self.sandbox.clone(); + sandbox.status = Some(DriverSandboxStatus { + name: self.tensorlake_name.clone(), + instance_id: self.tensorlake_id.clone(), + conditions: phase_conditions(&self.phase), + deleting: self.phase == Phase::Deleting, + resolved_identity: self.identity.as_ref().map(|identity| ProtoIdentity { + uid: identity.uid, + gid: identity.gid, + supplementary_gids: identity.supplementary_gids.clone(), + source: identity.source.clone(), + resource_digest: identity.resource_digest.clone(), + }), + ..DriverSandboxStatus::default() + }); + sandbox + } +} + +fn condition(r#type: &str, status: &str, reason: &str, message: String) -> DriverCondition { + DriverCondition { + r#type: r#type.to_string(), + status: status.to_string(), + reason: reason.to_string(), + message, + transition_time: None, + } +} + +/// The conditions the gateway reads for a phase. `Ready` carries the phase. +/// `Suspended=True` tells the gateway a stopped sandbox stays stopped, and +/// `Bootstrapping=True` tells it a stopped sandbox is starting again. +fn phase_conditions(phase: &Phase) -> Vec { + let mut conditions = vec![ready_condition(phase)]; + match phase { + Phase::Stopped => conditions.push(condition( + "Suspended", + "True", + "ComputeStopped", + "Tensorlake VMs are suspended and keep their disks".to_string(), + )), + Phase::Pending | Phase::Launching => conditions.push(condition( + "Bootstrapping", + "True", + "Starting", + "OpenShell launch in progress".to_string(), + )), + Phase::Running | Phase::Failed { .. } | Phase::Deleting => {} + } + conditions +} + +fn ready_condition(phase: &Phase) -> DriverCondition { + let (status, reason, message) = match phase { + Phase::Pending => ( + "False", + "Starting", + "Tensorlake sandbox is pending".to_string(), + ), + Phase::Launching => ( + "False", + "Starting", + "starting the OpenShell guard in the Tensorlake sandbox".to_string(), + ), + Phase::Running => ( + "True", + "TensorlakeRunning", + "Tensorlake sandbox is running".to_string(), + ), + Phase::Stopped => ( + "False", + "Stopped", + "Tensorlake VMs are suspended; start the sandbox to resume them".to_string(), + ), + Phase::Failed { reason, message } => ("False", reason.as_str(), message.clone()), + Phase::Deleting => ( + "False", + "Deleting", + "Tensorlake sandbox is being deleted".to_string(), + ), + }; + condition("Ready", status, reason, message) +} + +/// Tensorlake sandbox name for an `OpenShell` sandbox ID. +pub fn tensorlake_name(sandbox_id: &str) -> String { + let sanitized: String = sandbox_id + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() { + c.to_ascii_lowercase() + } else { + '-' + } + }) + .collect(); + format!("{NAME_PREFIX}{sanitized}") +} + +/// Tensorlake name of the guard VM for an `OpenShell` sandbox ID. +pub fn tensorlake_guard_name(sandbox_id: &str) -> String { + format!("{}{GUARD_NAME_SUFFIX}", tensorlake_name(sandbox_id)) +} + +/// Which `OpenShell` sandbox a Tensorlake name belongs to, and whether it is +/// the guard VM. `None` for names this driver did not create, such as the +/// control sandbox `openshell-control`. `OpenShell` sandbox IDs are UUIDs, +/// and `tensorlake_name` keeps them intact, so the ID part must look like +/// one. +fn parse_tensorlake_name(name: &str) -> Option<(&str, bool)> { + let rest = name.strip_prefix(NAME_PREFIX)?; + let (id, guard) = rest + .strip_suffix(GUARD_NAME_SUFFIX) + .map_or((rest, false), |id| (id, true)); + let uuid_shaped = id.len() == 36 + && id.bytes().enumerate().all(|(index, byte)| match index { + 8 | 13 | 18 | 23 => byte == b'-', + _ => byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase(), + }); + uuid_shaped.then_some((id, guard)) +} + +fn create_error(error: TensorlakeError) -> Status { + match error { + TensorlakeError::Api { status, .. } if status.as_u16() == 409 => { + Status::already_exists("Tensorlake sandbox already exists") + } + other => Status::unavailable(other.to_string()), + } +} + +/// Parse a Kubernetes-style CPU quantity (`2`, `1.5`, `500m`) into vCPUs. +fn parse_cpus(quantity: &str) -> Result { + let quantity = quantity.trim(); + let value = quantity.strip_suffix('m').map_or_else( + || quantity.parse::(), + |millis| millis.parse::().map(|value| value / 1000.0), + ); + match value { + Ok(cpus) if cpus > 0.0 && cpus.is_finite() => Ok(cpus), + _ => Err(format!("invalid CPU quantity '{quantity}'")), + } +} + +/// Parse a Kubernetes-style memory quantity into MiB. +fn parse_memory_mb(quantity: &str) -> Result { + let quantity = quantity.trim(); + let units: [(&str, f64); 8] = [ + ("Ki", 1.0 / 1024.0), + ("Mi", 1.0), + ("Gi", 1024.0), + ("Ti", 1024.0 * 1024.0), + ("K", 1000.0 / 1_048_576.0), + ("M", 1_000_000.0 / 1_048_576.0), + ("G", 1_000_000_000.0 / 1_048_576.0), + ("T", 1_000_000_000_000.0 / 1_048_576.0), + ]; + let (number, scale) = units + .iter() + .find_map(|(suffix, scale)| quantity.strip_suffix(suffix).map(|n| (n, *scale))) + .unwrap_or((quantity, 1.0 / 1_048_576.0)); + match number.parse::() { + #[allow(clippy::cast_possible_truncation)] + Ok(value) if value > 0.0 && value.is_finite() => Ok(((value * scale).ceil() as i64).max(1)), + _ => Err(format!("invalid memory quantity '{quantity}'")), + } +} + +fn first_non_empty(values: [&str; 2]) -> Option<&str> { + values.into_iter().find(|value| !value.trim().is_empty()) +} + +#[derive(Clone)] +pub struct TensorlakeComputeDriver { + client: TensorlakeClient, + config: Arc, + admission: Arc, + gateway_ca_pem: Option>>, + records: Arc>>, + events: broadcast::Sender, + /// Saved sandbox requests, read back after a restart. + state: StateStore, +} + +impl std::fmt::Debug for TensorlakeComputeDriver { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("TensorlakeComputeDriver") + .field("config", &self.config) + .finish() + } +} + +impl TensorlakeComputeDriver { + /// Build the driver, recover sandboxes it created before a restart, and + /// start the status poll loop. + pub async fn new( + config: TensorlakeComputeConfig, + admission: DriverAdmissionConfig, + ) -> Result { + config.validate()?; + let gateway_ca_pem = match &config.gateway_tls_ca { + Some(path) => { + Some(Arc::new(std::fs::read(path).map_err(|error| { + format!("read gateway CA {}: {error}", path.display()) + })?)) + } + None => None, + }; + let client = + TensorlakeClient::new(&config.api_url, &config.api_key).map_err(|e| e.to_string())?; + let (events, _) = broadcast::channel(WATCH_BUFFER); + let state = StateStore::new(&config.state_dir); + let driver = Self { + client, + config: Arc::new(config), + admission: Arc::new(admission), + gateway_ca_pem, + records: Arc::new(Mutex::new(HashMap::new())), + events, + state, + }; + driver.recover().await?; + let poller = driver.clone(); + tokio::spawn(async move { poller.poll_loop().await }); + Ok(driver) + } + + #[cfg(test)] + fn for_tests(config: TensorlakeComputeConfig) -> Self { + let (events, _) = broadcast::channel(WATCH_BUFFER); + let state = StateStore::new(&config.state_dir); + Self { + client: TensorlakeClient::new(&config.api_url, &config.api_key).unwrap(), + config: Arc::new(config), + admission: Arc::new(DriverAdmissionConfig::default()), + gateway_ca_pem: None, + records: Arc::new(Mutex::new(HashMap::new())), + events, + state, + } + } + + pub fn capabilities(&self) -> GetCapabilitiesResponse { + let mut extension = openshell_core::extension_protocol::extension_metadata( + openshell_core::extension_protocol::ExtensionFamily::Compute, + "openshell/tensorlake", + openshell_core::VERSION, + [], + ); + // The launch bundle needs gateway-signed launch credentials. + extension + .required_capabilities + .push(openshell_core::extension_protocol::COMPUTE_LAUNCH_AUTHENTICATION.to_string()); + GetCapabilitiesResponse { + resource_admission_policy: self.admission.acknowledgement(), + driver_name: "tensorlake".to_string(), + driver_version: openshell_core::VERSION.to_string(), + default_image: self.config.default_image.clone(), + gateway_manages_lifecycle: false, + 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: false, + count_selection_supported: false, + }), + }), + rootfs_tar_staging_dir: String::new(), + rootfs_tar_max_bytes: 0, + extension: Some(extension), + } + } + + fn image_for(&self, sandbox: &DriverSandbox) -> String { + sandbox + .spec + .as_ref() + .and_then(|spec| spec.template.as_ref()) + .map(|template| template.image.trim()) + .filter(|image| !image.is_empty()) + .unwrap_or(&self.config.default_image) + .to_string() + } + + fn resources_for(&self, sandbox: &DriverSandbox) -> Result { + let requirements = sandbox + .spec + .as_ref() + .and_then(|spec| spec.template.as_ref()) + .and_then(|template| template.resources.as_ref()); + let cpus = requirements + .and_then(|r| first_non_empty([&r.cpu_limit, &r.cpu_request])) + .map_or(Ok(self.config.default_cpus), parse_cpus)?; + let memory_mb = requirements + .and_then(|r| first_non_empty([&r.memory_limit, &r.memory_request])) + .map_or(Ok(self.config.default_memory_mb), parse_memory_mb)?; + Ok(Resources { + cpus, + memory_mb, + disk_mb: self.config.default_disk_mb, + }) + } + + /// Validate everything that can be checked before Tensorlake is called. + pub fn validate_sandbox_create( + &self, + sandbox: &DriverSandbox, + ) -> Result<(Resources, ResolvedWorkloadIdentity), Status> { + openshell_core::resource_admission::check_sandbox_driver_config( + self.admission.allow_driver_config, + sandbox, + )?; + if sandbox.id.trim().is_empty() { + return Err(Status::invalid_argument("sandbox.id is required")); + } + let spec = sandbox + .spec + .as_ref() + .ok_or_else(|| Status::invalid_argument("sandbox.spec is required"))?; + if let Some(template) = spec.template.as_ref() { + if !template.agent_socket_path.trim().is_empty() { + return Err(Status::failed_precondition( + "the Tensorlake 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( + "the Tensorlake driver does not support template.platform_config", + )); + } + } + if spec + .resource_requirements + .as_ref() + .and_then(|requirements| requirements.gpu.as_ref()) + .is_some() + { + return Err(Status::failed_precondition( + "the Tensorlake driver does not support GPU sandboxes yet", + )); + } + let resources = self + .resources_for(sandbox) + .map_err(Status::invalid_argument)?; + let identity = launch::resolve_identity(sandbox, &self.image_for(sandbox)) + .map_err(Status::failed_precondition)?; + Ok((resources, identity)) + } + + pub async fn create_sandbox(&self, sandbox: &DriverSandbox) -> Result<(), Status> { + let (resources, identity) = self.validate_sandbox_create(sandbox)?; + // The gateway mints launch authentication after validation, so only + // create can require it. + if sandbox + .spec + .as_ref() + .is_none_or(|spec| spec.launch_authentication.is_empty()) + { + return Err(Status::failed_precondition( + "Tensorlake sandboxes require launch-scoped gateway authentication", + )); + } + if self.records.lock().await.contains_key(&sandbox.id) { + return Err(Status::already_exists("sandbox already exists")); + } + // The guard VM needs the gateway and the Tensorlake hosts. Empty + // keeps Tensorlake's default internet. With an allow list, internet + // access stays on: Tensorlake then connects only to the listed hosts + // and its resolver answers only for them. Turning internet off as + // well blocks DNS, and the tunnel cannot resolve its own API host + // (verified on 2026-10-20). + let allow_out = self.config.effective_allow_out(); + let guard_network = (!allow_out.is_empty()).then(|| NetworkPolicy { + allow_internet_access: true, + allow_out, + deny_out: Vec::new(), + }); + // The workload VM gets no outbound path at all. Its connections + // travel over the boundary channel to the guard. + let workload_network = Some(NetworkPolicy::no_egress()); + let name = tensorlake_name(&sandbox.id); + // Keep secrets out of the stored record; only the provisioning task + // sees the launch credentials. Save it before any VM exists, so a + // restart always finds the record for a VM it finds. + let mut stored = sandbox.clone(); + if let Some(spec) = stored.spec.as_mut() { + spec.sandbox_token.clear(); + spec.launch_authentication.clear(); + } + self.state + .save(&stored) + .await + .map_err(|error| Status::internal(format!("save sandbox record: {error}")))?; + let created = match self + .client + .create_sandbox(&CreateSandboxRequest { + image: Some(self.image_for(sandbox)), + resources: Some(resources), + timeout_secs: self.config.timeout_secs, + network: workload_network, + name: Some(name.clone()), + wait: Some(false), + }) + .await + { + Ok(created) => created, + Err(error) => { + self.discard_state(&sandbox.id).await; + return Err(create_error(error)); + } + }; + info!( + sandbox_id = %sandbox.id, + tensorlake_sandbox_id = %created.sandbox_id, + "Created Tensorlake sandbox" + ); + let guard = self + .client + .create_sandbox(&CreateSandboxRequest { + image: Some(self.config.guard_image().to_string()), + resources: Some(Resources { + cpus: self.config.guard_cpus, + memory_mb: self.config.guard_memory_mb, + disk_mb: None, + }), + timeout_secs: self.config.timeout_secs, + network: guard_network, + name: Some(tensorlake_guard_name(&sandbox.id)), + wait: Some(false), + }) + .await; + let guard_tensorlake_id = match guard { + Ok(guard) => { + info!( + sandbox_id = %sandbox.id, + tensorlake_sandbox_id = %guard.sandbox_id, + "Created Tensorlake guard sandbox" + ); + guard.sandbox_id + } + Err(error) => { + // Never leave a workload VM without its guard. + if let Err(cleanup) = self.client.delete_sandbox(&created.sandbox_id).await { + warn!( + sandbox_id = %sandbox.id, + tensorlake_sandbox_id = %created.sandbox_id, + %cleanup, + "Failed to delete the workload VM after the guard VM create failed" + ); + } + self.discard_state(&sandbox.id).await; + return Err(create_error(error)); + } + }; + + let record = Record { + sandbox: stored, + tensorlake_id: created.sandbox_id.clone(), + tensorlake_name: name, + guard_tensorlake_id: guard_tensorlake_id.clone(), + identity: Some(identity.clone()), + phase: Phase::Pending, + launcher_pid: None, + guard_launcher_pid: None, + launch: 0, + }; + self.records + .lock() + .await + .insert(sandbox.id.clone(), record.clone()); + self.emit_sandbox(&record); + self.publish_progress(&sandbox.id, LaunchProgress::Accepted); + + self.spawn_launch(Launch { + sandbox: sandbox.clone(), + tensorlake_id: created.sandbox_id, + guard_tensorlake_id, + identity, + id: 0, + resume: false, + }); + Ok(()) + } + + /// Stop the sandbox: end the launched processes in both VMs, then + /// suspend the VMs. Their disks stay. Safe to call again; a VM that is + /// already suspended is left alone. + pub async fn stop_sandbox(&self, sandbox_id: &str) -> Result<(), Status> { + let record = { + let mut records = self.records.lock().await; + let Some(record) = records.get_mut(sandbox_id) else { + return Err(Status::not_found("sandbox not found")); + }; + if record.phase == Phase::Deleting { + return Err(Status::failed_precondition("sandbox is being deleted")); + } + // Take the launch away from a provisioning task first, so it + // cannot start a launcher after the VM was stopped. + record.launch += 1; + record.launcher_pid = None; + record.guard_launcher_pid = None; + record.phase = Phase::Stopped; + record.clone() + }; + self.emit_sandbox(&record); + for (tensorlake_id, role) in [ + (&record.tensorlake_id, "workload"), + (&record.guard_tensorlake_id, "guard"), + ] { + if tensorlake_id.is_empty() { + continue; + } + self.stop_vm(sandbox_id, tensorlake_id, role) + .await + .map_err(Status::unavailable)?; + } + info!(sandbox_id, "Stopped Tensorlake sandbox"); + Ok(()) + } + + /// End the generation in one VM and suspend it. + async fn stop_vm( + &self, + sandbox_id: &str, + tensorlake_id: &str, + role: &str, + ) -> Result<(), String> { + let started = Instant::now(); + loop { + let info = match self.client.get_sandbox(tensorlake_id).await { + Ok(info) => info, + // The poll loop reports a lost VM; stop has nothing to do. + Err(TensorlakeError::NotFound) => return Ok(()), + Err(error) => return Err(format!("get Tensorlake {role} sandbox: {error}")), + }; + match info.status.as_str() { + "running" => { + self.end_generation(sandbox_id, &info, role).await?; + self.client + .suspend_sandbox(tensorlake_id) + .await + .map_err(|error| format!("suspend Tensorlake {role} sandbox: {error}"))?; + info!(sandbox_id, tensorlake_sandbox_id = %tensorlake_id, role, "Suspended Tensorlake sandbox"); + return Ok(()); + } + // A VM that is still booting or resuming: wait, then stop it. + "pending" | "snapshotting" => {} + // Already suspended, or terminated (the poll loop reports it). + _ => return Ok(()), + } + if started.elapsed() > STOP_TIMEOUT { + return Err(format!( + "Tensorlake {role} sandbox stayed '{}' for too long to stop it", + info.status + )); + } + tokio::time::sleep(self.config.poll_interval).await; + } + } + + /// Run the launcher's `--stop` in a running VM and wait for it to + /// finish. A failed run is logged; the next launch cleans up again. + async fn end_generation( + &self, + sandbox_id: &str, + info: &SandboxInfo, + role: &str, + ) -> Result<(), String> { + let stop = self + .client + .start_process( + info, + &StartProcessRequest { + command: launch::LAUNCHER_PATH.to_string(), + args: vec![launch::LAUNCHER_STOP_ARG.to_string()], + env: std::collections::BTreeMap::new(), + user: "root".to_string(), + stdin_mode: "closed", + }, + ) + .await + .map_err(|error| format!("stop the OpenShell {role} generation: {error}"))?; + let started = Instant::now(); + loop { + match self.client.get_process(info, stop.pid).await { + Ok(Some(process)) if process.is_running() => {} + Ok(Some(process)) => { + if process.exit_code != Some(0) { + warn!( + sandbox_id, + role, + outcome = %process.outcome(), + "OpenShell launcher stop run did not finish cleanly" + ); + } + return Ok(()); + } + Ok(None) => return Ok(()), + Err(error) => { + return Err(format!("wait for the OpenShell {role} stop run: {error}")); + } + } + if started.elapsed() > END_GENERATION_TIMEOUT { + warn!( + sandbox_id, + role, "OpenShell launcher stop run is still running; suspending anyway" + ); + return Ok(()); + } + tokio::time::sleep(Duration::from_millis(500)).await; + } + } + + /// Start a stopped sandbox: resume both VMs and launch a new generation + /// with the fresh credentials. Returns at once; a background task does + /// the work, as for create. A sandbox that is launching or running is + /// left alone, so a retried start is harmless. + pub async fn start_sandbox( + &self, + sandbox_id: &str, + launch_authentication: Vec, + ) -> Result<(), Status> { + if launch_authentication.is_empty() { + return Err(Status::failed_precondition( + "Tensorlake sandboxes require launch-scoped gateway authentication", + )); + } + let (launch, record) = { + let mut records = self.records.lock().await; + let Some(record) = records.get_mut(sandbox_id) else { + return Err(Status::not_found("sandbox not found")); + }; + match &record.phase { + Phase::Stopped => {} + Phase::Pending | Phase::Launching | Phase::Running => return Ok(()), + Phase::Deleting => { + return Err(Status::failed_precondition("sandbox is being deleted")); + } + Phase::Failed { message, .. } => { + return Err(Status::failed_precondition(format!( + "sandbox cannot be started: {message}" + ))); + } + } + if record.guard_tensorlake_id.is_empty() { + return Err(Status::failed_precondition( + "the guard VM of this sandbox is gone; delete and recreate it", + )); + } + let Some(spec) = record.sandbox.spec.as_mut() else { + return Err(Status::failed_precondition( + "no saved request for this sandbox; delete and recreate it", + )); + }; + spec.launch_authentication = launch_authentication; + let identity = match record.identity.clone() { + Some(identity) => identity, + None => launch::resolve_identity(&record.sandbox, &self.image_for(&record.sandbox)) + .map_err(Status::failed_precondition)?, + }; + record.identity = Some(identity.clone()); + record.launch += 1; + record.phase = Phase::Pending; + let launch = Launch { + sandbox: record.sandbox.clone(), + tensorlake_id: record.tensorlake_id.clone(), + guard_tensorlake_id: record.guard_tensorlake_id.clone(), + identity, + id: record.launch, + resume: true, + }; + // The stored copy never holds the credentials. + if let Some(spec) = record.sandbox.spec.as_mut() { + spec.launch_authentication.clear(); + } + (launch, record.clone()) + }; + self.emit_sandbox(&record); + self.publish_progress(sandbox_id, LaunchProgress::Resuming); + self.spawn_launch(launch); + Ok(()) + } + + /// Run a launch in the background and record its failure. + fn spawn_launch(&self, launch: Launch) { + let driver = self.clone(); + tokio::spawn(async move { + let sandbox_id = launch.sandbox.id.clone(); + let launch_id = launch.id; + if let Err(message) = driver.launch(launch).await { + warn!(sandbox_id = %sandbox_id, %message, "Tensorlake sandbox launch failed"); + driver.publish_progress(&sandbox_id, LaunchProgress::Failed(&message)); + driver + .set_launch_phase( + &sandbox_id, + launch_id, + Phase::Failed { + reason: "LaunchFailed".into(), + message, + }, + ) + .await; + } + }); + } + + async fn launch(&self, launch: Launch) -> Result<(), String> { + if launch.resume { + for (tensorlake_id, role) in [ + (&launch.tensorlake_id, "workload"), + (&launch.guard_tensorlake_id, "guard"), + ] { + if !self.owns_launch(&launch.sandbox.id, launch.id).await { + return Ok(()); + } + self.resume_vm(tensorlake_id, role).await?; + } + } + self.provision( + &launch.sandbox, + &launch.tensorlake_id, + &launch.guard_tensorlake_id, + &launch.identity, + launch.id, + ) + .await + } + + /// Ask Tensorlake to resume a suspended VM. A VM that is still + /// suspending is resumed once it is suspended. A running VM, for example + /// one resumed by hand, needs nothing. + async fn resume_vm(&self, tensorlake_id: &str, role: &str) -> Result<(), String> { + let started = Instant::now(); + loop { + let info = self + .client + .get_sandbox(tensorlake_id) + .await + .map_err(|error| format!("get Tensorlake {role} sandbox: {error}"))?; + match info.status.as_str() { + "suspended" => { + self.client + .resume_sandbox(tensorlake_id) + .await + .map_err(|error| format!("resume Tensorlake {role} sandbox: {error}"))?; + info!(tensorlake_sandbox_id = %tensorlake_id, role, "Resumed Tensorlake sandbox"); + return Ok(()); + } + "running" | "pending" | "snapshotting" => return Ok(()), + "suspending" => {} + other => { + return Err(format!( + "Tensorlake {role} sandbox is '{other}' and cannot be resumed{}", + failure_detail(&info) + )); + } + } + if started.elapsed() > STOP_TIMEOUT { + return Err(format!( + "Tensorlake {role} sandbox stayed 'suspending' for too long to resume it" + )); + } + tokio::time::sleep(self.config.poll_interval).await; + } + } + + /// Wait for the VMs, upload the launch bundles, and start the launchers. + async fn provision( + &self, + sandbox: &DriverSandbox, + tensorlake_id: &str, + guard_tensorlake_id: &str, + identity: &ResolvedWorkloadIdentity, + launch: u64, + ) -> Result<(), String> { + let started = Instant::now(); + let Some(workload_info) = self + .wait_running(sandbox, tensorlake_id, "workload", started, launch) + .await? + else { + return Ok(()); + }; + let Some(guard_info) = self + .wait_running(sandbox, guard_tensorlake_id, "guard", started, launch) + .await? + else { + return Ok(()); + }; + if !self.owns_launch(&sandbox.id, launch).await { + return Ok(()); + } + self.set_launch_phase(&sandbox.id, launch, Phase::Launching) + .await; + self.publish_progress(&sandbox.id, LaunchProgress::VmRunning); + self.publish_progress(&sandbox.id, LaunchProgress::UploadingBundle); + + let bundles = launch::build_launch_bundles(LaunchBundleInput { + sandbox, + config: &self.config, + tensorlake_sandbox_id: tensorlake_id, + guard_tensorlake_id, + identity, + gateway_ca_pem: self.gateway_ca_pem.as_deref().map(Vec::as_slice), + })?; + self.client + .write_file(&workload_info, launch::BUNDLE_UPLOAD_PATH, bundles.workload) + .await + .map_err(|error| format!("upload launch bundle: {error}"))?; + self.client + .write_file(&guard_info, launch::BUNDLE_UPLOAD_PATH, bundles.guard) + .await + .map_err(|error| format!("upload guard launch bundle: {error}"))?; + if !self.owns_launch(&sandbox.id, launch).await { + return Ok(()); + } + self.publish_progress(&sandbox.id, LaunchProgress::StartingLauncher); + let guard_launcher_pid = self.start_launcher(sandbox, &guard_info, "guard").await?; + let launcher_pid = self + .start_launcher(sandbox, &workload_info, "workload") + .await?; + if let Some(record) = self + .records + .lock() + .await + .get_mut(&sandbox.id) + .filter(|record| record.launch == launch) + { + record.launcher_pid = Some(launcher_pid); + record.guard_launcher_pid = Some(guard_launcher_pid); + } + self.set_launch_phase(&sandbox.id, launch, Phase::Running) + .await; + self.publish_progress(&sandbox.id, LaunchProgress::LauncherStarted); + Ok(()) + } + + /// Poll one VM until it runs. `Ok(None)` means the sandbox was deleted + /// meanwhile and provisioning should stop quietly. + async fn wait_running( + &self, + sandbox: &DriverSandbox, + tensorlake_id: &str, + role: &str, + started: Instant, + launch: u64, + ) -> Result, String> { + let mut last_pending_reason: Option = None; + loop { + if !self.owns_launch(&sandbox.id, launch).await { + return Ok(None); + } + let info = self + .client + .get_sandbox(tensorlake_id) + .await + .map_err(|error| format!("get Tensorlake {role} sandbox: {error}"))?; + match info.status.as_str() { + "running" => return Ok(Some(info)), + "pending" => { + // Report a new pending reason once, not on every poll. + let reason = info + .pending_reason + .as_deref() + .map(str::trim) + .filter(|reason| !reason.is_empty()) + .map(str::to_string); + if reason.is_some() && reason != last_pending_reason { + self.publish_progress( + &sandbox.id, + LaunchProgress::Pending(reason.as_deref().unwrap_or_default()), + ); + last_pending_reason = reason; + } + } + other => { + return Err(format!( + "Tensorlake {role} sandbox entered state '{other}' before launch{}", + failure_detail(&info) + )); + } + } + if started.elapsed() > PROVISION_TIMEOUT { + return Err(format!( + "Tensorlake {role} sandbox did not start within 10 minutes" + )); + } + tokio::time::sleep(self.config.poll_interval).await; + } + } + + /// Start the in-image launcher as root and return its PID. + async fn start_launcher( + &self, + sandbox: &DriverSandbox, + info: &SandboxInfo, + role: &str, + ) -> Result { + let launcher = self + .client + .start_process( + info, + &StartProcessRequest { + command: launch::LAUNCHER_PATH.to_string(), + args: vec![launch::BUNDLE_UPLOAD_PATH.to_string()], + env: std::collections::BTreeMap::new(), + user: "root".to_string(), + stdin_mode: "closed", + }, + ) + .await + .map_err(|error| format!("start OpenShell {role} launcher: {error}"))?; + info!( + sandbox_id = %sandbox.id, + tensorlake_sandbox_id = %info.sandbox_id, + launcher_pid = launcher.pid, + role, + "Started OpenShell launcher in Tensorlake sandbox" + ); + Ok(launcher.pid) + } + + pub async fn get_sandbox(&self, sandbox_id: &str) -> Option { + self.records + .lock() + .await + .get(sandbox_id) + .map(Record::snapshot) + } + + pub async fn list_sandboxes(&self) -> Vec { + let mut sandboxes: Vec<_> = self + .records + .lock() + .await + .values() + .map(Record::snapshot) + .collect(); + sandboxes.sort_by(|a, b| a.id.cmp(&b.id)); + sandboxes + } + + pub async fn delete_sandbox(&self, sandbox_id: &str) -> Result { + let (tensorlake_id, guard_tensorlake_id) = { + let mut records = self.records.lock().await; + let Some(record) = records.get_mut(sandbox_id) else { + return Ok(false); + }; + record.phase = Phase::Deleting; + let record = record.clone(); + drop(records); + self.emit_sandbox(&record); + (record.tensorlake_id, record.guard_tensorlake_id) + }; + let mut remaining = false; + for id in [&tensorlake_id, &guard_tensorlake_id] { + if id.is_empty() { + continue; + } + remaining |= self + .client + .delete_sandbox(id) + .await + .map_err(|error| Status::unavailable(error.to_string()))?; + } + if !remaining { + self.forget(sandbox_id).await; + } + Ok(true) + } + + pub async fn watch_sandboxes( + &self, + ) -> impl Stream> + Send + 'static { + let receiver = self.events.subscribe(); + let initial = self.list_sandboxes().await; + let live = tokio_stream::wrappers::BroadcastStream::new(receiver).filter_map(|item| { + std::future::ready(match item { + Ok(event) => Some(Ok(event)), + Err(error) => Some(Err(Status::data_loss(format!( + "Tensorlake watch fell behind: {error}" + )))), + }) + }); + futures::stream::iter( + initial + .into_iter() + .map(|sandbox| Ok(sandbox_event(sandbox))), + ) + .chain(live) + } + + /// Whether `launch` is still the sandbox's current launch. A stop, a + /// start, or a delete ends a launch; its task then stops quietly. + async fn owns_launch(&self, sandbox_id: &str, launch: u64) -> bool { + self.records + .lock() + .await + .get(sandbox_id) + .is_some_and(|record| record.phase != Phase::Deleting && record.launch == launch) + } + + /// Set the phase from a launch task. Ignored once the launch is over. + async fn set_launch_phase(&self, sandbox_id: &str, launch: u64, phase: Phase) { + let record = { + let mut records = self.records.lock().await; + let Some(record) = records.get_mut(sandbox_id) else { + return; + }; + if record.phase == Phase::Deleting || record.launch != launch || record.phase == phase { + return; + } + record.phase = phase; + record.clone() + }; + self.emit_sandbox(&record); + } + + /// Set the phase from the poll loop. + async fn set_phase(&self, sandbox_id: &str, phase: Phase) { + let record = { + let mut records = self.records.lock().await; + let Some(record) = records.get_mut(sandbox_id) else { + return; + }; + if record.phase == Phase::Deleting || record.phase == phase { + return; + } + record.phase = phase; + record.clone() + }; + self.emit_sandbox(&record); + } + + async fn forget(&self, sandbox_id: &str) { + if self.records.lock().await.remove(sandbox_id).is_some() { + self.discard_state(sandbox_id).await; + let _ = self.events.send(WatchSandboxesEvent { + payload: Some(watch_sandboxes_event::Payload::Deleted( + WatchSandboxesDeletedEvent { + sandbox_id: sandbox_id.to_string(), + }, + )), + }); + } + } + + /// Remove the saved request of a sandbox that no longer exists. + async fn discard_state(&self, sandbox_id: &str) { + if let Err(error) = self.state.remove(sandbox_id).await { + warn!(sandbox_id, %error, "Failed to remove the saved sandbox record"); + } + } + + fn emit_sandbox(&self, record: &Record) { + let _ = self.events.send(sandbox_event(record.snapshot())); + } + + /// Publish a launch progress event. The gateway forwards it to the CLI, + /// which shows the step on its provisioning spinner, so the user sees + /// what the driver waits for while the VM boots. + fn publish_progress(&self, sandbox_id: &str, progress: LaunchProgress<'_>) { + let _ = self.events.send(WatchSandboxesEvent { + payload: Some(watch_sandboxes_event::Payload::PlatformEvent( + WatchSandboxesPlatformEvent { + sandbox_id: sandbox_id.to_string(), + event: Some(progress.into_event()), + }, + )), + }); + } + + /// Rebuild records for sandboxes this driver created before a restart. + /// Launch credentials are not kept, so pending sandboxes cannot finish + /// launching and are reported as failed. The saved request gives each + /// record back its `OpenShell` name; the gateway rejects a snapshot + /// whose name differs from its own record. + async fn recover(&self) -> Result<(), String> { + let sandboxes = self + .client + .list_sandboxes() + .await + .map_err(|error| format!("list Tensorlake sandboxes: {error}"))?; + let mut recovered = Vec::new(); + for (sandbox_id, workload, guard) in pair_by_name(&sandboxes) { + let Some(phase) = recovered_phase(workload, guard) else { + continue; + }; + let saved = match self.state.load(sandbox_id).await { + Ok(saved) => saved, + Err(error) => { + warn!(sandbox_id, %error, "Failed to read the saved sandbox record"); + None + } + }; + if saved.is_none() { + warn!( + sandbox_id, + "No saved record for this sandbox; the gateway cannot update its status. Delete and recreate it" + ); + } + if let Some(record) = recovered_record(sandbox_id, saved, workload, guard, phase) { + recovered.push((sandbox_id.to_string(), record)); + } + } + // A saved request whose VMs are gone, for example terminated with + // `tl` while the driver was down, has nothing left to recover. + match self.state.saved_ids().await { + Ok(ids) => { + for id in ids { + if !recovered + .iter() + .any(|(recovered_id, _)| *recovered_id == id) + { + info!(sandbox_id = %id, "Dropping the saved record of a sandbox with no VMs"); + self.discard_state(&id).await; + } + } + } + Err(error) => warn!(%error, "Failed to list the saved sandbox records"), + } + let mut records = self.records.lock().await; + records.extend(recovered); + info!(recovered = records.len(), "Recovered Tensorlake sandboxes"); + Ok(()) + } + + async fn poll_loop(&self) { + loop { + tokio::time::sleep(self.config.poll_interval).await; + if let Err(error) = self.poll_once().await { + warn!(%error, "Tensorlake status poll failed"); + } + } + } + + async fn poll_once(&self) -> Result<(), TensorlakeError> { + // Read the records before the Tensorlake list. A record created after + // this point is not in the list yet and must not look terminated. + let records: Vec<(String, Record)> = self + .records + .lock() + .await + .iter() + .map(|(id, record)| (id.clone(), record.clone())) + .collect(); + let observed: HashMap = self + .client + .list_sandboxes() + .await? + .into_iter() + .map(|info| (info.sandbox_id.clone(), info)) + .collect(); + for (sandbox_id, record) in records { + let info = observed.get(&record.tensorlake_id); + let guard_info = observed.get(&record.guard_tensorlake_id); + match reconcile(&record.phase, info, guard_info) { + Reconcile::Keep => {} + Reconcile::Forget => self.forget(&sandbox_id).await, + Reconcile::Set(next) => self.set_phase(&sandbox_id, next).await, + } + if record.phase != Phase::Running { + continue; + } + let launchers = [ + (info, record.launcher_pid, "workload"), + (guard_info, record.guard_launcher_pid, "guard"), + ]; + for (info, pid, role) in launchers { + if let (Some(info), Some(pid)) = (info, pid) + && observed_phase(info) == Some(Phase::Running) + { + self.check_launcher(&sandbox_id, info, pid, role).await; + } + } + } + Ok(()) + } + + /// Mark the sandbox failed when a launcher has stopped. Without the + /// launcher the guard never connects, and the gateway would wait. + async fn check_launcher(&self, sandbox_id: &str, info: &SandboxInfo, pid: i64, role: &str) { + match self.client.get_process(info, pid).await { + Ok(process) => { + if let Some(failed) = launcher_failure(&info.sandbox_id, process.as_ref(), role) { + warn!(%sandbox_id, role, ?failed, "OpenShell launcher stopped"); + self.set_phase(sandbox_id, failed).await; + } + } + Err(error) => { + warn!(%sandbox_id, role, %error, "Tensorlake launcher status check failed"); + } + } + } +} + +/// Group the Tensorlake sandboxes this driver created by `OpenShell` sandbox +/// ID: `(id, workload VM, guard VM)`. +fn pair_by_name( + sandboxes: &[SandboxInfo], +) -> Vec<(&str, Option<&SandboxInfo>, Option<&SandboxInfo>)> { + let mut pairs: std::collections::BTreeMap<&str, (Option<&SandboxInfo>, Option<&SandboxInfo>)> = + std::collections::BTreeMap::new(); + for info in sandboxes { + let Some((sandbox_id, guard)) = info.name.as_deref().and_then(parse_tensorlake_name) else { + continue; + }; + let pair = pairs.entry(sandbox_id).or_default(); + if guard { + pair.1 = Some(info); + } else { + pair.0 = Some(info); + } + } + pairs + .into_iter() + .map(|(id, (workload, guard))| (id, workload, guard)) + .collect() +} + +/// Phase for a pair found after a driver restart. `None` means nothing is +/// left to track. +/// The record for a sandbox found at restart. `saved` is the request the +/// gateway sent at create, when the state store still has it. A guard VM +/// whose workload VM is gone is still recorded, under the workload's name, +/// so that delete can remove it. +fn recovered_record( + sandbox_id: &str, + saved: Option, + workload: Option<&SandboxInfo>, + guard: Option<&SandboxInfo>, + phase: Phase, +) -> Option { + let anchor = workload.or(guard)?; + let mut sandbox = saved.unwrap_or_default(); + sandbox.id = sandbox_id.to_string(); + sandbox.status = None; + Some(Record { + sandbox, + tensorlake_id: anchor.sandbox_id.clone(), + tensorlake_name: tensorlake_name(sandbox_id), + guard_tensorlake_id: guard + .map(|info| info.sandbox_id.clone()) + .unwrap_or_default(), + identity: None, + phase, + launcher_pid: None, + guard_launcher_pid: None, + launch: 0, + }) +} + +fn recovered_phase(workload: Option<&SandboxInfo>, guard: Option<&SandboxInfo>) -> Option { + let workload_phase = workload.and_then(observed_phase); + let guard_phase = guard.and_then(observed_phase); + let restarted = || Phase::Failed { + reason: "DriverRestarted".into(), + message: + "the Tensorlake driver restarted before this sandbox launched; delete and recreate it" + .into(), + }; + let half = |what: &str| Phase::Failed { + reason: "PairIncomplete".into(), + message: format!("the {what} VM of this sandbox is gone; delete and recreate it"), + }; + Some(match (workload_phase, guard_phase) { + (None, None) => return None, + (None, Some(_)) => half("workload"), + (Some(_), None) => half("guard"), + // A stopped sandbox, or a stop or start the restart interrupted. + // Start resumes what is suspended and launches again. + (Some(Phase::Stopped), _) | (_, Some(Phase::Stopped)) => Phase::Stopped, + (Some(Phase::Pending), _) | (_, Some(Phase::Pending)) => restarted(), + (Some(phase), _) => phase, + }) +} + +#[derive(Debug, PartialEq, Eq)] +enum Reconcile { + Keep, + Forget, + Set(Phase), +} + +/// Decide how one poll observation changes a record. `guard` is `None` +/// when Tensorlake no longer lists the guard VM. +fn reconcile( + current: &Phase, + workload: Option<&SandboxInfo>, + guard: Option<&SandboxInfo>, +) -> Reconcile { + let workload_phase = workload.and_then(observed_phase); + let guard_phase = guard.and_then(observed_phase); + let any_present = workload_phase.is_some() || guard_phase.is_some(); + match current { + // Gone from Tensorlake while we delete it: finish the delete. + Phase::Deleting if !any_present => return Reconcile::Forget, + // Keep the current phase while a delete runs. + Phase::Deleting + // The provisioning task owns launch progress and reports its own + // failures. + | Phase::Pending + | Phase::Launching => return Reconcile::Keep, + // A failed launch stays failed while the VMs still exist. Nothing + // will launch it again, unless both VMs are suspended: then the + // sandbox is stopped, and start launches it again. + Phase::Failed { .. } + if workload_phase + .as_ref() + .is_some_and(|phase| *phase != Phase::Stopped) + && guard_phase + .as_ref() + .is_some_and(|phase| *phase != Phase::Stopped) => + { + return Reconcile::Keep; + } + // A stopped sandbox stays stopped while its VMs exist, whatever + // their state: a VM resumed by hand runs nothing of OpenShell. + Phase::Stopped if workload_phase.is_some() && guard_phase.is_some() => { + return Reconcile::Keep; + } + _ => {} + } + let gone = |what: &str, info: Option<&SandboxInfo>| { + Reconcile::Set(Phase::Failed { + reason: "TensorlakeTerminated".into(), + message: format!( + "Tensorlake {what} sandbox is no longer running{}", + info.map(failure_detail).unwrap_or_default() + ), + }) + }; + match (workload_phase, guard_phase) { + (None, _) => gone("workload", workload), + (Some(_), None) => gone("guard", guard), + // A VM suspended by hand stops the sandbox. Start resumes it. + (Some(Phase::Stopped), _) | (_, Some(Phase::Stopped)) => Reconcile::Set(Phase::Stopped), + (Some(next), _) => Reconcile::Set(next), + } +} + +/// The failed phase for a launcher that is no longer running. +fn launcher_failure( + tensorlake_id: &str, + process: Option<&ProcessInfo>, + role: &str, +) -> Option { + let outcome = match process { + Some(process) if process.is_running() => return None, + Some(process) => process.outcome(), + None => "is no longer known to Tensorlake".to_string(), + }; + Some(Phase::Failed { + reason: "LauncherExited".into(), + message: format!( + "the OpenShell {role} launcher {outcome}; run `tl sbx logs {tensorlake_id}` for details" + ), + }) +} + +/// Map Tensorlake status to a phase. `None` means the VM is gone. +fn observed_phase(info: &SandboxInfo) -> Option { + match info.status.as_str() { + "pending" => Some(Phase::Pending), + "running" | "snapshotting" => Some(Phase::Running), + "suspending" | "suspended" => Some(Phase::Stopped), + _ => None, + } +} + +fn failure_detail(info: &SandboxInfo) -> String { + let mut parts = Vec::new(); + if let Some(reason) = info.termination_reason.as_deref().filter(|r| !r.is_empty()) { + parts.push(format!("termination reason: {reason}")); + } + if let Some(details) = info.error_details.as_ref().filter(|d| !d.is_null()) { + parts.push(format!("details: {details}")); + } + if parts.is_empty() { + String::new() + } else { + format!(" ({})", parts.join("; ")) + } +} + +/// Launch steps the driver reports while a sandbox boots. +/// +/// Tensorlake provides the image, so there is no pull step to show. The +/// `pulling_image` step is completed together with the VM start, and the +/// remaining time is shown under `starting_sandbox`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LaunchProgress<'a> { + /// Tensorlake accepted the create request; the VM is not running yet. + Accepted, + /// Start asked Tensorlake to resume the suspended VMs. + Resuming, + /// Tensorlake reported why the VM is still pending. + Pending(&'a str), + /// The VM runs. + VmRunning, + /// The driver uploads the launch bundle. + UploadingBundle, + /// The driver starts the in-image launcher. + StartingLauncher, + /// The launcher runs; the gateway now waits for the guard session. + LauncherStarted, + /// Provisioning failed; the message explains why. + Failed(&'a str), +} + +impl LaunchProgress<'_> { + fn into_event(self) -> DriverPlatformEvent { + let (event_type, reason, message) = match self { + Self::Accepted => ( + "Normal", + "Accepted", + "Tensorlake accepted the sandbox request".to_string(), + ), + Self::Resuming => ( + "Normal", + "Resuming", + "Resuming the Tensorlake VMs".to_string(), + ), + Self::Pending(reason) => ( + "Normal", + "Pending", + format!("Tensorlake sandbox is pending: {reason}"), + ), + Self::VmRunning => ("Normal", "Running", "Tensorlake VM is running".to_string()), + Self::UploadingBundle => ( + "Normal", + "UploadingBundle", + "Uploading the OpenShell launch bundle".to_string(), + ), + Self::StartingLauncher => ( + "Normal", + "StartingLauncher", + "Starting the OpenShell launcher".to_string(), + ), + Self::LauncherStarted => ( + "Normal", + "LauncherStarted", + "OpenShell launcher started; waiting for the guard session".to_string(), + ), + Self::Failed(message) => ( + "Warning", + "LaunchFailed", + format!("Tensorlake sandbox launch failed: {message}"), + ), + }; + let mut event = DriverPlatformEvent { + event_time: openshell_core::time::timestamp_from_millis(openshell_core::time::now_ms()) + .ok(), + source: EVENT_SOURCE.to_string(), + r#type: event_type.to_string(), + reason: reason.to_string(), + message, + metadata: HashMap::new(), + }; + let metadata = &mut event.metadata; + match self { + Self::Accepted => { + mark_progress_active(metadata, PROGRESS_STEP_REQUESTING_SANDBOX); + mark_progress_detail(metadata, "Waiting for the Tensorlake VM"); + } + Self::Resuming => { + mark_progress_active(metadata, PROGRESS_STEP_REQUESTING_SANDBOX); + mark_progress_detail(metadata, "Resuming the Tensorlake VMs"); + } + Self::Pending(reason) => { + mark_progress_active(metadata, PROGRESS_STEP_REQUESTING_SANDBOX); + mark_progress_detail(metadata, reason); + } + Self::VmRunning => { + mark_progress_complete( + metadata, + PROGRESS_STEP_REQUESTING_SANDBOX, + "Tensorlake VM running", + ); + mark_progress_active(metadata, PROGRESS_STEP_PULLING_IMAGE); + } + Self::UploadingBundle => { + mark_progress_complete( + metadata, + PROGRESS_STEP_PULLING_IMAGE, + "Image provided by Tensorlake", + ); + mark_progress_active(metadata, PROGRESS_STEP_STARTING_SANDBOX); + mark_progress_detail(metadata, "Uploading launch bundle"); + } + Self::StartingLauncher => { + mark_progress_active(metadata, PROGRESS_STEP_STARTING_SANDBOX); + mark_progress_detail(metadata, "Starting OpenShell launcher"); + } + Self::LauncherStarted => { + mark_progress_active(metadata, PROGRESS_STEP_STARTING_SANDBOX); + mark_progress_detail(metadata, "Waiting for the OpenShell guard"); + } + Self::Failed(_) => {} + } + event + } +} + +/// What a launch task needs. `sandbox` carries the launch credentials; +/// the stored record does not. +struct Launch { + sandbox: DriverSandbox, + tensorlake_id: String, + guard_tensorlake_id: String, + identity: ResolvedWorkloadIdentity, + /// The record's launch counter when this launch began. + id: u64, + /// Resume suspended VMs first (start), or expect new ones (create). + resume: bool, +} + +fn sandbox_event(sandbox: DriverSandbox) -> WatchSandboxesEvent { + WatchSandboxesEvent { + payload: Some(watch_sandboxes_event::Payload::Sandbox( + WatchSandboxesSandboxEvent { + sandbox: Some(sandbox), + }, + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + use openshell_core::proto::compute::v1::{ + DriverResourceRequirements, DriverSandboxSpec, DriverSandboxTemplate, + }; + + fn driver() -> TensorlakeComputeDriver { + TensorlakeComputeDriver::for_tests(crate::config::tests::test_config()) + } + + fn sandbox(template: DriverSandboxTemplate) -> DriverSandbox { + DriverSandbox { + id: "sb-1".into(), + name: "demo".into(), + spec: Some(DriverSandboxSpec { + template: Some(template), + launch_authentication: b"{}".to_vec(), + ..DriverSandboxSpec::default() + }), + ..DriverSandbox::default() + } + } + + #[test] + fn capabilities_require_launch_authentication() { + let capabilities = driver().capabilities(); + let extension = capabilities.extension.unwrap(); + assert!(extension.required_capabilities.iter().any(|capability| { + capability == openshell_core::extension_protocol::COMPUTE_LAUNCH_AUTHENTICATION + })); + assert!(!capabilities.gateway_manages_lifecycle); + assert!(!capabilities.driver_reports_runtime_readiness); + } + + #[test] + fn validate_uses_template_resources_and_defaults() { + let driver = driver(); + let (resources, identity) = driver + .validate_sandbox_create(&sandbox(DriverSandboxTemplate { + resources: Some(DriverResourceRequirements { + cpu_limit: "4".into(), + memory_limit: "8Gi".into(), + ..DriverResourceRequirements::default() + }), + ..DriverSandboxTemplate::default() + })) + .unwrap(); + assert!((resources.cpus - 4.0).abs() < f64::EPSILON); + assert_eq!(resources.memory_mb, 8192); + assert_eq!(identity.resource_digest, "openshell-tensorlake"); + + let (resources, _) = driver + .validate_sandbox_create(&sandbox(DriverSandboxTemplate::default())) + .unwrap(); + assert!((resources.cpus - crate::config::DEFAULT_CPUS).abs() < f64::EPSILON); + assert_eq!(resources.memory_mb, crate::config::DEFAULT_MEMORY_MB); + } + + #[tokio::test] + async fn only_create_requires_launch_authentication() { + let driver = driver(); + let mut missing_auth = sandbox(DriverSandboxTemplate::default()); + missing_auth + .spec + .as_mut() + .unwrap() + .launch_authentication + .clear(); + assert!(driver.validate_sandbox_create(&missing_auth).is_ok()); + let error = driver.create_sandbox(&missing_auth).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + } + + #[test] + fn validate_rejects_unsupported_requests() { + let driver = driver(); + let agent_socket = sandbox(DriverSandboxTemplate { + agent_socket_path: "/run/agent.sock".into(), + ..DriverSandboxTemplate::default() + }); + assert!(driver.validate_sandbox_create(&agent_socket).is_err()); + } + + #[test] + fn names_use_prefix_and_lowercase() { + assert_eq!( + tensorlake_name("3F2A-b9_x"), + "openshell-3f2a-b9-x".to_string() + ); + } + + #[test] + fn cpu_quantities() { + assert!((parse_cpus("2").unwrap() - 2.0).abs() < f64::EPSILON); + assert!((parse_cpus("500m").unwrap() - 0.5).abs() < f64::EPSILON); + assert!(parse_cpus("0").is_err()); + assert!(parse_cpus("lots").is_err()); + } + + #[test] + fn memory_quantities() { + assert_eq!(parse_memory_mb("2Gi").unwrap(), 2048); + assert_eq!(parse_memory_mb("512Mi").unwrap(), 512); + assert_eq!(parse_memory_mb("1G").unwrap(), 954); + assert_eq!(parse_memory_mb("1048576").unwrap(), 1); + assert!(parse_memory_mb("-1Gi").is_err()); + } + + #[test] + fn stopped_and_starting_carry_their_conditions() { + let find = |conditions: &[DriverCondition], r#type: &str| { + conditions + .iter() + .find(|condition| condition.r#type == r#type) + .map(|condition| (condition.status.clone(), condition.reason.clone())) + }; + let stopped = phase_conditions(&Phase::Stopped); + assert_eq!( + find(&stopped, "Ready"), + Some(("False".into(), "Stopped".into())) + ); + assert_eq!( + find(&stopped, "Suspended"), + Some(("True".into(), "ComputeStopped".into())) + ); + assert_eq!(find(&stopped, "Bootstrapping"), None); + for phase in [Phase::Pending, Phase::Launching] { + let starting = phase_conditions(&phase); + assert_eq!( + find(&starting, "Bootstrapping"), + Some(("True".into(), "Starting".into())) + ); + assert_eq!(find(&starting, "Suspended"), None); + } + let running = phase_conditions(&Phase::Running); + assert_eq!(running.len(), 1); + assert_eq!( + find(&running, "Ready"), + Some(("True".into(), "TensorlakeRunning".into())) + ); + } + + #[test] + fn ready_condition_maps_phases() { + assert_eq!(ready_condition(&Phase::Running).status, "True"); + let pending = ready_condition(&Phase::Pending); + assert_eq!( + (pending.status.as_str(), pending.reason.as_str()), + ("False", "Starting") + ); + let failed = ready_condition(&Phase::Failed { + reason: "LaunchFailed".into(), + message: "boom".into(), + }); + assert_eq!(failed.reason, "LaunchFailed"); + } + + fn info(status: &str) -> SandboxInfo { + SandboxInfo { + sandbox_id: "x".into(), + status: status.into(), + name: None, + sandbox_url: None, + routing_hint: None, + termination_reason: None, + pending_reason: None, + error_details: None, + } + } + + #[test] + fn reconcile_leaves_launch_to_the_provisioning_task() { + // A new record can be missing from a list that started before create. + assert_eq!(reconcile(&Phase::Pending, None, None), Reconcile::Keep); + assert_eq!(reconcile(&Phase::Launching, None, None), Reconcile::Keep); + assert_eq!( + reconcile(&Phase::Pending, Some(&info("running")), None), + Reconcile::Keep + ); + } + + #[test] + fn reconcile_keeps_failed_launch_failed() { + let failed = Phase::Failed { + reason: "DriverRestarted".into(), + message: "m".into(), + }; + for status in ["pending", "running"] { + let vm = info(status); + assert_eq!(reconcile(&failed, Some(&vm), Some(&vm)), Reconcile::Keep); + } + // Once a VM is gone, the failure reason follows the VM. + for guard in [Some(&info("running")), None] { + assert!(matches!( + reconcile(&failed, None, guard), + Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" + )); + } + assert!(matches!( + reconcile(&failed, Some(&info("running")), None), + Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" + )); + } + + #[test] + fn reconcile_tracks_running_sandboxes() { + let guard = info("running"); + assert_eq!(reconcile(&Phase::Deleting, None, None), Reconcile::Forget); + assert_eq!( + reconcile(&Phase::Deleting, Some(&info("running")), None), + Reconcile::Keep + ); + assert_eq!( + reconcile(&Phase::Running, Some(&info("suspended")), Some(&guard)), + Reconcile::Set(Phase::Stopped) + ); + // A stopped sandbox stays stopped until start launches it again, + // even when someone resumes a VM by hand. + for workload in ["suspending", "suspended", "pending", "running"] { + assert_eq!( + reconcile(&Phase::Stopped, Some(&info(workload)), Some(&guard)), + Reconcile::Keep + ); + } + assert!(matches!( + reconcile(&Phase::Stopped, None, Some(&guard)), + Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" + )); + assert!(matches!( + reconcile(&Phase::Stopped, Some(&info("suspended")), None), + Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" + )); + assert!(matches!( + reconcile(&Phase::Running, Some(&info("terminated")), Some(&guard)), + Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" + )); + } + + #[test] + fn reconcile_tracks_both_vms() { + let running = info("running"); + let suspended = info("suspended"); + // Both present and running: keep running. + assert_eq!( + reconcile(&Phase::Running, Some(&running), Some(&running)), + Reconcile::Set(Phase::Running) + ); + // Delete finishes only when both are gone. + assert_eq!( + reconcile(&Phase::Deleting, None, Some(&running)), + Reconcile::Keep + ); + assert_eq!(reconcile(&Phase::Deleting, None, None), Reconcile::Forget); + // A lost guard VM fails the sandbox and names the guard. + let Reconcile::Set(Phase::Failed { reason, message }) = + reconcile(&Phase::Running, Some(&running), None) + else { + panic!("a lost guard VM must fail the sandbox"); + }; + assert_eq!(reason, "TensorlakeTerminated"); + assert!(message.contains("guard")); + // A suspended guard VM stops the sandbox. + assert_eq!( + reconcile(&Phase::Running, Some(&running), Some(&suspended)), + Reconcile::Set(Phase::Stopped) + ); + // A failed sandbox whose VMs were suspended can be started again. + let failed = Phase::Failed { + reason: "LauncherExited".into(), + message: "m".into(), + }; + assert_eq!( + reconcile(&failed, Some(&suspended), Some(&suspended)), + Reconcile::Set(Phase::Stopped) + ); + } + + fn named(name: &str, status: &str) -> SandboxInfo { + SandboxInfo { + sandbox_id: format!("id-{name}"), + name: Some(name.into()), + ..info(status) + } + } + + const ID: &str = "fda3b8c8-4d1f-4c8e-a762-d863a24e0137"; + + #[test] + fn names_identify_guard_vms() { + assert_eq!(tensorlake_guard_name(ID), format!("openshell-{ID}-guard")); + assert_eq!( + parse_tensorlake_name(&format!("openshell-{ID}")), + Some((ID, false)) + ); + assert_eq!( + parse_tensorlake_name(&format!("openshell-{ID}-guard")), + Some((ID, true)) + ); + // The control sandbox and other operator sandboxes share the prefix. + assert_eq!(parse_tensorlake_name("openshell-control"), None); + assert_eq!(parse_tensorlake_name("openshell-control-split"), None); + assert_eq!(parse_tensorlake_name("openshell-"), None); + assert_eq!(parse_tensorlake_name("openshell--guard"), None); + assert_eq!(parse_tensorlake_name(&format!("other-{ID}")), None); + } + + #[test] + fn recovered_record_reports_the_saved_name() { + let id = "aaaaaaaa-0000-4000-8000-000000000001"; + let workload = named(&format!("openshell-{id}"), "running"); + let guard = named(&format!("openshell-{id}-guard"), "running"); + let saved = DriverSandbox { + id: id.into(), + name: "demo".into(), + namespace: "default".into(), + workspace: "ws".into(), + status: Some(DriverSandboxStatus::default()), + ..DriverSandbox::default() + }; + + let record = recovered_record( + id, + Some(saved), + Some(&workload), + Some(&guard), + Phase::Running, + ) + .unwrap(); + let snapshot = record.snapshot(); + assert_eq!(snapshot.id, id); + assert_eq!(snapshot.name, "demo"); + assert_eq!(snapshot.namespace, "default"); + assert_eq!(snapshot.workspace, "ws"); + assert_eq!(record.tensorlake_id, workload.sandbox_id); + assert_eq!(record.guard_tensorlake_id, guard.sandbox_id); + let status = snapshot.status.unwrap(); + assert_eq!(status.name, format!("openshell-{id}")); + assert_eq!(status.conditions[0].reason, "TensorlakeRunning"); + + // Without the saved request only the ID is known. + let record = recovered_record(id, None, None, Some(&guard), Phase::Stopped).unwrap(); + assert_eq!(record.sandbox.id, id); + assert!(record.sandbox.name.is_empty()); + assert_eq!(record.tensorlake_id, guard.sandbox_id); + + assert!(recovered_record(id, None, None, None, Phase::Running).is_none()); + } + + #[test] + fn recovery_pairs_vms_by_name() { + let (a, b, c) = ( + "aaaaaaaa-0000-4000-8000-000000000001", + "bbbbbbbb-0000-4000-8000-000000000002", + "cccccccc-0000-4000-8000-000000000003", + ); + let sandboxes = vec![ + named(&format!("openshell-{a}"), "running"), + named(&format!("openshell-{a}-guard"), "running"), + named(&format!("openshell-{b}"), "running"), + named(&format!("openshell-{c}-guard"), "running"), + named("openshell-control", "running"), + named("unrelated", "running"), + ]; + let pairs = pair_by_name(&sandboxes); + assert_eq!(pairs.len(), 3); + let (id, workload, guard) = pairs[0]; + assert_eq!(id, a); + assert_eq!(workload.unwrap().sandbox_id, format!("id-openshell-{a}")); + assert_eq!(guard.unwrap().sandbox_id, format!("id-openshell-{a}-guard")); + assert_eq!(recovered_phase(workload, guard), Some(Phase::Running)); + // A workload VM without its guard is broken. + let (_, workload, guard) = pairs[1]; + assert!(matches!( + recovered_phase(workload, guard), + Some(Phase::Failed { reason, .. }) if reason == "PairIncomplete" + )); + // A guard VM without its workload is recorded so delete can reach it. + let (_, workload, guard) = pairs[2]; + assert!(matches!( + recovered_phase(workload, guard), + Some(Phase::Failed { reason, .. }) if reason == "PairIncomplete" + )); + // A pending VM at restart cannot finish launching. + assert!(matches!( + recovered_phase( + Some(&named("openshell-d", "running")), + Some(&named("openshell-d-guard", "pending")), + ), + Some(Phase::Failed { reason, .. }) if reason == "DriverRestarted" + )); + // Suspended VMs are a stopped sandbox, also with a stop or start + // half done. + for guard in ["suspended", "suspending", "running", "pending"] { + assert_eq!( + recovered_phase( + Some(&named("openshell-f", "suspended")), + Some(&named("openshell-f-guard", guard)), + ), + Some(Phase::Stopped) + ); + } + assert_eq!( + recovered_phase(Some(&named("openshell-e", "terminated")), None), + None + ); + } + + fn process(status: &str, exit_code: Option) -> ProcessInfo { + serde_json::from_value(serde_json::json!({ + "pid": 721, "status": status, "exit_code": exit_code, "signal": null + })) + .unwrap() + } + + #[test] + fn launcher_failure_reports_stopped_launchers() { + assert_eq!( + launcher_failure("tl1", Some(&process("running", None)), "workload"), + None + ); + let Some(Phase::Failed { reason, message }) = + launcher_failure("tl1", Some(&process("exited", Some(1))), "guard") + else { + panic!("an exited launcher must fail the sandbox"); + }; + assert_eq!(reason, "LauncherExited"); + assert!(message.contains("guard launcher exited with status 1")); + assert!(message.contains("tl sbx logs tl1")); + assert!(launcher_failure("tl1", None, "workload").is_some()); + } + + #[test] + fn launch_progress_maps_to_cli_steps() { + use openshell_core::progress::{ + PROGRESS_ACTIVE_DETAIL_KEY, PROGRESS_ACTIVE_STEP_KEY, PROGRESS_COMPLETE_LABEL_KEY, + PROGRESS_COMPLETE_STEP_KEY, + }; + + let accepted = LaunchProgress::Accepted.into_event(); + assert_eq!(accepted.source, EVENT_SOURCE); + assert_eq!(accepted.r#type, "Normal"); + assert!(accepted.event_time.is_some()); + assert_eq!( + accepted.metadata.get(PROGRESS_ACTIVE_STEP_KEY).unwrap(), + PROGRESS_STEP_REQUESTING_SANDBOX + ); + + let pending = LaunchProgress::Pending("waiting for capacity").into_event(); + assert_eq!( + pending.metadata.get(PROGRESS_ACTIVE_DETAIL_KEY).unwrap(), + "waiting for capacity" + ); + assert!(pending.message.contains("waiting for capacity")); + + let running = LaunchProgress::VmRunning.into_event(); + assert_eq!( + running.metadata.get(PROGRESS_COMPLETE_STEP_KEY).unwrap(), + PROGRESS_STEP_REQUESTING_SANDBOX + ); + assert_eq!( + running.metadata.get(PROGRESS_COMPLETE_LABEL_KEY).unwrap(), + "Tensorlake VM running" + ); + + let uploading = LaunchProgress::UploadingBundle.into_event(); + assert_eq!( + uploading.metadata.get(PROGRESS_COMPLETE_STEP_KEY).unwrap(), + PROGRESS_STEP_PULLING_IMAGE + ); + assert_eq!( + uploading.metadata.get(PROGRESS_ACTIVE_STEP_KEY).unwrap(), + PROGRESS_STEP_STARTING_SANDBOX + ); + + for progress in [ + LaunchProgress::StartingLauncher, + LaunchProgress::LauncherStarted, + ] { + let event = progress.into_event(); + assert_eq!( + event.metadata.get(PROGRESS_ACTIVE_STEP_KEY).unwrap(), + PROGRESS_STEP_STARTING_SANDBOX + ); + assert!(event.metadata.contains_key(PROGRESS_ACTIVE_DETAIL_KEY)); + } + + let failed = LaunchProgress::Failed("upload failed").into_event(); + assert_eq!(failed.r#type, "Warning"); + assert_eq!(failed.reason, "LaunchFailed"); + assert!(failed.message.contains("upload failed")); + assert!(failed.metadata.is_empty()); + } + + #[tokio::test] + async fn progress_events_reach_watchers() { + let driver = driver(); + let mut stream = Box::pin(driver.watch_sandboxes().await); + driver.publish_progress("sb-1", LaunchProgress::Accepted); + let event = stream.next().await.unwrap().unwrap(); + let Some(watch_sandboxes_event::Payload::PlatformEvent(platform)) = event.payload else { + panic!("expected a platform event"); + }; + assert_eq!(platform.sandbox_id, "sb-1"); + assert_eq!(platform.event.unwrap().reason, "Accepted"); + } + + #[test] + fn observed_phase_treats_terminal_states_as_gone() { + assert_eq!(observed_phase(&info("running")), Some(Phase::Running)); + assert_eq!(observed_phase(&info("suspended")), Some(Phase::Stopped)); + assert_eq!(observed_phase(&info("suspending")), Some(Phase::Stopped)); + for status in ["terminated", "failed", "timeout"] { + assert_eq!(observed_phase(&info(status)), None); + } + } +} diff --git a/crates/openshell-driver-tensorlake/src/grpc.rs b/crates/openshell-driver-tensorlake/src/grpc.rs new file mode 100644 index 0000000000..89628de07c --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/grpc.rs @@ -0,0 +1,176 @@ +// 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 std::pin::Pin; + +use futures::Stream; +use openshell_core::proto::compute::v1::{ + AuthenticateSandboxRequest, AuthenticateSandboxResponse, CreateSandboxRequest, + CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, DeleteWorkspaceRequest, + DeleteWorkspaceResponse, EnsureWorkspaceRequest, EnsureWorkspaceResponse, + GetCapabilitiesRequest, GetCapabilitiesResponse, GetSandboxRequest, GetSandboxResponse, + ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest, StartSandboxResponse, + StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, + ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, + compute_driver_server::ComputeDriver, +}; +use tonic::{Request, Response, Status}; + +use crate::TensorlakeComputeDriver; + +type WatchStream = Pin> + Send>>; + +#[derive(Debug, Clone)] +pub struct ComputeDriverService { + driver: TensorlakeComputeDriver, +} + +impl ComputeDriverService { + #[must_use] + pub fn new(driver: TensorlakeComputeDriver) -> Self { + Self { driver } + } +} + +fn required_id(sandbox_id: &str) -> Result<(), Status> { + if sandbox_id.is_empty() { + Err(Status::invalid_argument("sandbox_id is required")) + } else { + Ok(()) + } +} + +#[tonic::async_trait] +impl ComputeDriver for ComputeDriverService { + async fn get_capabilities( + &self, + request: Request, + ) -> Result, Status> { + let capabilities = self.driver.capabilities(); + openshell_core::extension_protocol::validate_gateway_metadata( + openshell_core::extension_protocol::ExtensionFamily::Compute, + "tensorlake", + capabilities.extension.as_ref(), + request.into_inner().gateway, + ) + .map_err(|error| Status::failed_precondition(error.to_string()))?; + Ok(Response::new(capabilities)) + } + + async fn authenticate_sandbox( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "tensorlake does not authenticate sandbox credentials", + )) + } + + 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.driver.validate_sandbox_create(&sandbox)?; + Ok(Response::new(ValidateSandboxCreateResponse {})) + } + + async fn get_sandbox( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + required_id(&request.sandbox_id)?; + let sandbox = self + .driver + .get_sandbox(&request.sandbox_id) + .await + .ok_or_else(|| Status::not_found("sandbox not found"))?; + Ok(Response::new(GetSandboxResponse { + sandbox: Some(sandbox), + })) + } + + async fn list_sandboxes( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(ListSandboxesResponse { + sandboxes: self.driver.list_sandboxes().await, + })) + } + + async fn create_sandbox( + &self, + request: Request, + ) -> Result, Status> { + let sandbox = request + .into_inner() + .sandbox + .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; + self.driver.create_sandbox(&sandbox).await?; + Ok(Response::new(CreateSandboxResponse::default())) + } + + async fn stop_sandbox( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + required_id(&request.sandbox_id)?; + self.driver.stop_sandbox(&request.sandbox_id).await?; + Ok(Response::new(StopSandboxResponse {})) + } + + async fn start_sandbox( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + required_id(&request.sandbox_id)?; + self.driver + .start_sandbox(&request.sandbox_id, request.launch_authentication) + .await?; + // The driver does not advertise sandbox authentication, so there is + // no runtime identity to return. + Ok(Response::new(StartSandboxResponse::default())) + } + + async fn delete_sandbox( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + required_id(&request.sandbox_id)?; + let deleted = self.driver.delete_sandbox(&request.sandbox_id).await?; + Ok(Response::new(DeleteSandboxResponse { deleted })) + } + + type WatchSandboxesStream = WatchStream; + + async fn watch_sandboxes( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(Box::pin(self.driver.watch_sandboxes().await))) + } + + 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 {})) + } +} diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs new file mode 100644 index 0000000000..41172219a3 --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -0,0 +1,957 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Launch bundles for the Tensorlake topologies. +//! +//! The driver builds tar archives per sandbox generation. The in-image +//! launcher extracts an archive as root, so each file keeps the owner and +//! mode set here, then starts the role named in the launch parameters. +//! +//! - `/.openshell/channel/sandbox/*` belongs to the workload identity. It holds +//! only the boundary bootstrap and the boundary TLS server key. +//! - `/.openshell/supervisor/*` belongs to the guard identity (mode 0700). It +//! holds gateway credentials, which the workload identity cannot read. +//! - `/.openshell/tunnel/*` belongs to the tunnel identity (mode 0700). It +//! holds the Tensorlake key the guard VM's tunnel authenticates with. +//! +//! The workload VM gets the channel files and listens on a TLS port. The +//! guard VM gets the supervisor and tunnel files; its tunnel dials the +//! workload VM's port on loopback. The workload VM has no outbound network +//! at all (a Tensorlake network policy), so the only path out is the +//! authenticated boundary channel. + +use std::collections::{BTreeMap, HashMap}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::path::PathBuf; + +use openshell_core::proto::compute::v1::DriverSandbox; +use openshell_isolation_interface::contract::{ProvisioningEvidence, ResolvedWorkloadIdentity}; +use openshell_sandbox_backend::boundary_protocol::{ + BoundaryConfig, BoundaryListener, GatewayVerificationKey, SandboxRuntimeDescriptor, + SandboxTlsClientConfig, SandboxTlsServerConfig, SandboxTransport, + generate_sandbox_tls_material, +}; +use serde::Serialize; + +use crate::config::TensorlakeComputeConfig; + +/// Path in the VM where the driver uploads the bundle. +pub const BUNDLE_UPLOAD_PATH: &str = "/var/lib/openshell/launch-bundle.tar"; +/// Launcher baked into the Tensorlake image. +pub const LAUNCHER_PATH: &str = "/opt/openshell/bin/openshell-tensorlake-launch"; +/// Launcher argument that ends the current generation without starting +/// a new one. Stop runs it before it suspends the VM. +pub const LAUNCHER_STOP_ARG: &str = "--stop"; +/// Guard identity inside the VM. It differs from the workload identity so the +/// workload cannot read gateway credentials. +pub const SUPERVISOR_UID: u32 = 65_534; +pub const SUPERVISOR_GID: u32 = 65_534; +/// Tunnel identity inside the guard VM. It holds the Tensorlake key, which +/// the guard identity cannot read. +pub const TUNNEL_UID: u32 = 65_533; +pub const TUNNEL_GID: u32 = 65_533; +/// Loopback port in the workload VM where the forwarder accepts the guard's +/// tunnel. The Tensorlake tunnel always delivers to loopback. +pub const WORKLOAD_FORWARD_PORT: u16 = 8443; +/// Port inside the workload network namespace where `openshell-sandbox` +/// listens for the guard. The forwarder connects to it over the veth link, +/// because the runtime rejects loopback peers. +pub const WORKLOAD_LISTEN_PORT: u16 = 8444; +/// Loopback port in the guard VM where the tunnel listens for the guard. +pub const GUARD_TUNNEL_PORT: u16 = 18_443; +/// Forwarder identity inside the workload VM. It owns no files. +pub const FORWARDER_UID: u32 = 65_533; +pub const FORWARDER_GID: u32 = 65_533; + +const WORKSPACE: &str = "/sandbox"; +const BOOTSTRAP_PATH: &str = "/.openshell/channel/sandbox/bootstrap.json"; +const SERVER_CERT_PATH: &str = "/.openshell/channel/sandbox/server.crt"; +const SERVER_KEY_PATH: &str = "/.openshell/channel/sandbox/server.key"; +const SUPERVISOR_DIR: &str = "/.openshell/supervisor"; +const RUNTIME_DESCRIPTOR_PATH: &str = "/.openshell/supervisor/runtime-descriptor.json"; +const AUTH_BUNDLE_PATH: &str = "/.openshell/supervisor/auth.json"; +const SANDBOX_TOKEN_PATH: &str = "/.openshell/supervisor/sandbox.jwt"; +const GATEWAY_CA_PATH: &str = "/.openshell/supervisor/gateway-ca.pem"; +const SUPERVISOR_ENV_PATH: &str = "/.openshell/supervisor/env"; +const SUPERVISOR_ARGS_PATH: &str = "/.openshell/supervisor/args"; +const LAUNCH_PARAMS_PATH: &str = "/.openshell/launch/params"; +const SUPERVISOR_RUN_DIR: &str = "/run/openshell"; +const SUPERVISOR_HEALTH_SOCKET: &str = "/run/openshell/supervisor-health.sock"; +const TUNNEL_DIR: &str = "/.openshell/tunnel"; +const TUNNEL_ENV_PATH: &str = "/.openshell/tunnel/env"; +const TUNNEL_ARGS_PATH: &str = "/.openshell/tunnel/args"; +const TUNNEL_RUN_DIR: &str = "/run/openshell-tunnel"; + +/// Which processes a launch bundle starts in its VM. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + /// Only `openshell-sandbox`, listening for a remote guard. + Workload, + /// Only the tunnel and `openshell-supervisor`. + Guard, +} + +impl Role { + const fn as_str(self) -> &'static str { + match self { + Self::Workload => "workload", + Self::Guard => "guard", + } + } +} + +fn invalid(error: impl std::fmt::Display) -> String { + error.to_string() +} + +/// Resolve the workload identity without inspecting the image. +/// +/// Tensorlake gives the driver no access to the image's account files, so +/// only numeric selectors are accepted. An empty request uses the `OpenShell` +/// default. +pub fn resolve_identity( + sandbox: &DriverSandbox, + image: &str, +) -> Result { + let request = sandbox + .spec + .as_ref() + .and_then(|spec| spec.workload_identity.as_ref()); + let user = request.map_or("", |identity| identity.user.trim()); + let group = request.map_or("", |identity| identity.group.trim()); + let parse = |value: &str, default: u32, kind: &str| -> Result { + if value.is_empty() { + return Ok(default); + } + value.parse::().map_err(|_| { + format!("the Tensorlake driver accepts only a numeric workload {kind}, got '{value}'") + }) + }; + let uid = parse( + user, + openshell_core::sandbox_env::DEFAULT_SANDBOX_UID, + "user", + )?; + let gid = parse( + group, + openshell_core::sandbox_env::DEFAULT_SANDBOX_GID, + "group", + )?; + if [SUPERVISOR_UID, TUNNEL_UID, FORWARDER_UID].contains(&uid) + || [SUPERVISOR_GID, TUNNEL_GID, FORWARDER_GID].contains(&gid) + { + return Err(format!( + "workload identity {uid}:{gid} is reserved for the OpenShell guard" + )); + } + let source = if user.is_empty() && group.is_empty() { + "default" + } else { + "policy" + }; + ResolvedWorkloadIdentity::new(uid, gid, Vec::new(), source.into(), image.into()) + .map_err(invalid) +} + +/// Evidence for the outer fence the driver requested. The driver cannot +/// inspect the VM, so the evidence names the recipe: the workload runs in a +/// network namespace whose only link leads to the tunnel forwarder, in a VM +/// that has internet access off and an empty allow list. Egress needs a +/// mediated decision, revocation takes effect at the guard, and guard loss +/// leaves the workload without a path. +#[derive(Serialize)] +struct TensorlakeOuterFenceEvidence<'a> { + topology: &'static str, + tensorlake_sandbox_id: &'a str, + guard_tensorlake_sandbox_id: &'a str, + workload_network: &'static str, + launcher: &'static str, +} + +/// Bind the launch recipe to one generation as provisioning evidence. +fn provisioning_evidence( + tensorlake_sandbox_id: &str, + guard_tensorlake_sandbox_id: &str, + generation: &str, +) -> Result { + if tensorlake_sandbox_id.is_empty() || guard_tensorlake_sandbox_id.is_empty() { + return Err("Tensorlake sandbox ID is required for provisioning evidence".to_string()); + } + let evidence = TensorlakeOuterFenceEvidence { + topology: "split", + tensorlake_sandbox_id, + guard_tensorlake_sandbox_id, + workload_network: "private-netns-veth-to-forwarder-no-egress", + launcher: LAUNCHER_PATH, + }; + let encoded = serde_json::to_vec(&evidence).map_err(invalid)?; + let projection = + ProvisioningEvidence::from_enforcement_evidence(generation, &encoded).map_err(invalid)?; + projection.validate(generation).map_err(invalid)?; + Ok(projection) +} + +/// Environment for workload children. Control keys are removed. +fn 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 +} + +/// Guard environment, in launch order. +fn supervisor_environment( + sandbox: &DriverSandbox, + config: &TensorlakeComputeConfig, + has_gateway_ca: bool, +) -> Result, String> { + use openshell_core::sandbox_env as env; + let main_process_spec = + env::MainProcessConfig::encode_driver_spec(sandbox.spec.as_ref()).map_err(invalid)?; + let mut environment = vec![ + ( + "PATH".to_string(), + "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".to_string(), + ), + ( + env::ADMITTED_ISOLATION_BACKEND.to_string(), + openshell_sandbox_backend::BACKEND_NAME.to_string(), + ), + (env::MAIN_PROCESS_SPEC.to_string(), main_process_spec), + (env::ENDPOINT.to_string(), config.grpc_endpoint.clone()), + (env::SANDBOX_ID.to_string(), sandbox.id.clone()), + (env::SANDBOX.to_string(), sandbox.name.clone()), + ( + env::SSH_SOCKET_PATH.to_string(), + openshell_core::container_paths::SSH_SOCKET_PATH.to_string(), + ), + ( + env::PROXY_TLS_DIR.to_string(), + format!("{SUPERVISOR_RUN_DIR}/proxy-tls"), + ), + // No transparent interception: the guard never shares the workload's + // network namespace here, so workload connections arrive over the + // boundary channel with their identity, as in the Kubernetes driver. + (env::NETWORK_RUNTIME_CAPABILITIES.to_string(), String::new()), + ( + env::LOG_LEVEL.to_string(), + openshell_core::driver_utils::sandbox_log_level(sandbox, &config.log_level), + ), + ( + env::TELEMETRY_ENABLED.to_string(), + openshell_core::telemetry::enabled_env_value().to_string(), + ), + ]; + if has_gateway_ca { + environment.push((env::TLS_CA.to_string(), GATEWAY_CA_PATH.to_string())); + } + if sandbox + .spec + .as_ref() + .is_some_and(|spec| !spec.sandbox_token.is_empty()) + { + environment.push(( + env::SANDBOX_TOKEN_FILE.to_string(), + SANDBOX_TOKEN_PATH.to_string(), + )); + } + for (key, value) in &environment { + if key.contains(['=', '\0']) || value.contains('\0') { + return Err(format!( + "guard environment entry {key} is not representable" + )); + } + } + Ok(environment) +} + +fn supervisor_args() -> Vec { + vec![ + format!("--backend-descriptor-file={RUNTIME_DESCRIPTOR_PATH}"), + format!("--auth-bundle-file={AUTH_BUNDLE_PATH}"), + format!("--workdir={WORKSPACE}"), + format!("--health-socket-path={SUPERVISOR_HEALTH_SOCKET}"), + ] +} + +/// NUL-separated list, read by the launcher with `mapfile -d ''`. +fn nul_list>(items: I) -> Vec { + let mut out = Vec::new(); + for item in items { + out.extend_from_slice(item.as_bytes()); + out.push(0); + } + out +} + +pub struct LaunchBundleInput<'a> { + pub sandbox: &'a DriverSandbox, + pub config: &'a TensorlakeComputeConfig, + /// The workload VM. + pub tensorlake_sandbox_id: &'a str, + /// The guard VM. + pub guard_tensorlake_id: &'a str, + pub identity: &'a ResolvedWorkloadIdentity, + pub gateway_ca_pem: Option<&'a [u8]>, +} + +/// The tar archives for one sandbox generation. Paths are relative to `/`. +#[derive(Debug)] +pub struct LaunchBundles { + /// Uploaded to the workload VM. + pub workload: Vec, + /// Uploaded to the guard VM. + pub guard: Vec, +} + +/// Build the launch bundles. +pub fn build_launch_bundles(input: LaunchBundleInput<'_>) -> Result { + let LaunchBundleInput { + sandbox, + config, + tensorlake_sandbox_id, + guard_tensorlake_id, + identity, + gateway_ca_pem, + } = input; + let spec = sandbox + .spec + .as_ref() + .ok_or_else(|| "sandbox.spec is required".to_string())?; + if spec.launch_authentication.is_empty() { + return Err("Tensorlake sandboxes require launch-scoped gateway authentication".into()); + } + let launch_authentication: openshell_core::jwt::SandboxLaunchAuthentication = + serde_json::from_slice(&spec.launch_authentication) + .map_err(|error| format!("decode launch authentication: {error}"))?; + launch_authentication.validate().map_err(invalid)?; + + let session_id = launch_authentication.supervisor.session_id; + let generation = launch_authentication + .supervisor + .runtime_generation + .to_string(); + let tls = generate_sandbox_tls_material(session_id).map_err(invalid)?; + let provisioning_evidence = + provisioning_evidence(tensorlake_sandbox_id, guard_tensorlake_id, &generation)?; + let mut resource_claims = BTreeMap::from([ + ( + "tensorlake.sandbox_id".to_string(), + tensorlake_sandbox_id.to_string(), + ), + ( + "tensorlake.image".to_string(), + identity.resource_digest.clone(), + ), + ]); + resource_claims.insert( + "tensorlake.guard_sandbox_id".to_string(), + guard_tensorlake_id.to_string(), + ); + 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 server_tls = SandboxTlsServerConfig { + certificate_chain_path: PathBuf::from(SERVER_CERT_PATH), + private_key_path: PathBuf::from(SERVER_KEY_PATH), + }; + // The TLS listener must not bind loopback, because workload sockets share + // it. `0.0.0.0` also accepts the tunnel's connection, which arrives on + // loopback; the sandbox runtime protects the port from workload sockets. + let listener = BoundaryListener::TlsTcp { + address: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), WORKLOAD_LISTEN_PORT), + tls: server_tls, + }; + let transport = SandboxTransport::Tcp { + authority: format!("{tensorlake_sandbox_id}:{WORKLOAD_LISTEN_PORT}"), + addresses: vec![SocketAddr::new( + IpAddr::V4(Ipv4Addr::LOCALHOST), + GUARD_TUNNEL_PORT, + )], + }; + let boundary = BoundaryConfig { + boundary_id: sandbox.id.clone(), + generation: 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, + resource_claims: resource_claims.clone(), + resource_claim_files: BTreeMap::new(), + workload_identity: identity.clone(), + provisioning_evidence: provisioning_evidence.clone(), + child_env: child_environment(sandbox), + }; + let runtime_descriptor = SandboxRuntimeDescriptor { + boundary_id: sandbox.id.clone(), + generation, + session_id, + transport, + tls: SandboxTlsClientConfig { + server_name: tls.server_name.clone(), + trust_anchor_pem: tls.trust_anchor_pem.clone(), + }, + host_gateway_ip: None, + resource_claims, + workload_identity: identity.clone(), + provisioning_evidence, + }; + let guard_files = GuardFiles { + runtime_descriptor: &runtime_descriptor, + auth_bundle: &launch_authentication.supervisor, + sandbox_token: &spec.sandbox_token, + gateway_ca_pem, + environment: supervisor_environment(sandbox, config, gateway_ca_pem.is_some())?, + }; + + let mut workload_archive = Archive::default(); + workload_archive.directory(".openshell", 0o755, ROOT)?; + add_workload_files(&mut workload_archive, identity, &boundary, &tls)?; + add_params(&mut workload_archive, Role::Workload, identity)?; + let mut guard_archive = Archive::default(); + guard_archive.directory(".openshell", 0o755, ROOT)?; + add_guard_files(&mut guard_archive, &guard_files)?; + add_tunnel_files(&mut guard_archive, config, tensorlake_sandbox_id)?; + add_params(&mut guard_archive, Role::Guard, identity)?; + Ok(LaunchBundles { + workload: workload_archive.finish()?, + guard: guard_archive.finish()?, + }) +} + +const ROOT: Owner = Owner::new(0, 0); + +/// Channel files for the workload identity: the bootstrap and the boundary +/// server key. No gateway or provider secret. +fn add_workload_files( + archive: &mut Archive, + identity: &ResolvedWorkloadIdentity, + boundary: &BoundaryConfig, + tls: &openshell_sandbox_backend::boundary_protocol::SandboxTlsMaterial, +) -> Result<(), String> { + let workload = Owner::new(identity.uid, identity.gid); + archive.directory(".openshell/channel", 0o755, ROOT)?; + archive.directory(".openshell/channel/sandbox", 0o711, workload)?; + archive.file( + BOOTSTRAP_PATH, + 0o600, + workload, + &serde_json::to_vec(boundary).map_err(invalid)?, + )?; + archive.file( + SERVER_CERT_PATH, + 0o600, + workload, + tls.certificate_chain_pem.as_bytes(), + )?; + archive.file( + SERVER_KEY_PATH, + 0o600, + workload, + tls.private_key_pem.as_bytes(), + ) +} + +struct GuardFiles<'a> { + runtime_descriptor: &'a SandboxRuntimeDescriptor, + auth_bundle: &'a openshell_core::jwt::SupervisorAuthBundle, + sandbox_token: &'a str, + gateway_ca_pem: Option<&'a [u8]>, + environment: Vec<(String, String)>, +} + +/// Credentials and settings for the guard identity. +fn add_guard_files(archive: &mut Archive, files: &GuardFiles<'_>) -> Result<(), String> { + let guard = Owner::new(SUPERVISOR_UID, SUPERVISOR_GID); + archive.directory(SUPERVISOR_DIR, 0o700, guard)?; + archive.file( + RUNTIME_DESCRIPTOR_PATH, + 0o600, + guard, + &serde_json::to_vec(files.runtime_descriptor).map_err(invalid)?, + )?; + archive.file( + AUTH_BUNDLE_PATH, + 0o600, + guard, + &serde_json::to_vec(files.auth_bundle).map_err(invalid)?, + )?; + if !files.sandbox_token.is_empty() { + archive.file( + SANDBOX_TOKEN_PATH, + 0o600, + guard, + format!("{}\n", files.sandbox_token).as_bytes(), + )?; + } + if let Some(ca) = files.gateway_ca_pem { + archive.file(GATEWAY_CA_PATH, 0o600, guard, ca)?; + } + archive.file( + SUPERVISOR_ENV_PATH, + 0o600, + ROOT, + &nul_list( + files + .environment + .iter() + .map(|(key, value)| format!("{key}={value}")), + ), + )?; + archive.file( + SUPERVISOR_ARGS_PATH, + 0o600, + ROOT, + &nul_list(supervisor_args()), + ) +} + +/// The Tensorlake key, the Tensorlake API URLs, and the `tl sbx tunnel` +/// arguments for the tunnel identity in the guard VM. +/// +/// The launch script starts the tunnel with `env -i`, so this file is the +/// whole environment the `tl` CLI sees. `tl` reads the sandbox API URL +/// from `TENSORLAKE_SANDBOX_API_URL` and the platform API URL, where it +/// checks the key, from `TENSORLAKE_API_URL`. +fn add_tunnel_files( + archive: &mut Archive, + config: &TensorlakeComputeConfig, + workload_tensorlake_id: &str, +) -> Result<(), String> { + let tunnel = Owner::new(TUNNEL_UID, TUNNEL_GID); + if config.api_key.contains(['\0', '\n']) { + return Err("Tensorlake API key is not representable in the tunnel environment".into()); + } + if config.api_url.contains(['\0', '\n']) || config.platform_api_url.contains(['\0', '\n']) { + return Err("Tensorlake API URL is not representable in the tunnel environment".into()); + } + archive.directory(TUNNEL_DIR, 0o700, tunnel)?; + archive.file( + TUNNEL_ENV_PATH, + 0o600, + tunnel, + &nul_list([ + format!("TENSORLAKE_API_KEY={}", config.api_key), + format!("TENSORLAKE_SANDBOX_API_URL={}", config.api_url), + format!("TENSORLAKE_API_URL={}", config.platform_api_url), + ]), + )?; + archive.file( + TUNNEL_ARGS_PATH, + 0o600, + ROOT, + &nul_list(tunnel_args(workload_tensorlake_id)), + ) +} + +fn tunnel_args(workload_tensorlake_id: &str) -> Vec { + vec![ + "sbx".to_string(), + "tunnel".to_string(), + workload_tensorlake_id.to_string(), + WORKLOAD_FORWARD_PORT.to_string(), + "--listen-port".to_string(), + GUARD_TUNNEL_PORT.to_string(), + ] +} + +/// Launch parameters the launcher reads: the role, the identities, and the +/// directories it must create. +fn add_params( + archive: &mut Archive, + role: Role, + identity: &ResolvedWorkloadIdentity, +) -> Result<(), String> { + use std::fmt::Write as _; + let mut params = format!("ROLE={}\nWORKSPACE={WORKSPACE}\n", role.as_str()); + match role { + Role::Workload => writeln!( + params, + "WORKLOAD_UID={}\nWORKLOAD_GID={}\nFORWARDER_UID={FORWARDER_UID}\nFORWARDER_GID={FORWARDER_GID}\nWORKLOAD_LISTEN_PORT={WORKLOAD_LISTEN_PORT}\nWORKLOAD_FORWARD_PORT={WORKLOAD_FORWARD_PORT}", + identity.uid, identity.gid + ), + Role::Guard => writeln!( + params, + "SUPERVISOR_UID={SUPERVISOR_UID}\nSUPERVISOR_GID={SUPERVISOR_GID}\nSUPERVISOR_RUN_DIR={SUPERVISOR_RUN_DIR}\nTUNNEL_UID={TUNNEL_UID}\nTUNNEL_GID={TUNNEL_GID}\nTUNNEL_RUN_DIR={TUNNEL_RUN_DIR}" + ), + } + .expect("writing to a String cannot fail"); + archive.directory(".openshell/launch", 0o700, ROOT)?; + archive.file(LAUNCH_PARAMS_PATH, 0o600, ROOT, params.as_bytes()) +} + +#[derive(Clone, Copy)] +struct Owner { + uid: u32, + gid: u32, +} + +impl Owner { + const fn new(uid: u32, gid: u32) -> Self { + Self { uid, gid } + } +} + +#[derive(Default)] +struct Archive { + builder: Option>>, +} + +impl Archive { + fn builder(&mut self) -> &mut tar::Builder> { + self.builder + .get_or_insert_with(|| tar::Builder::new(Vec::new())) + } + + fn directory(&mut self, path: &str, mode: u32, owner: Owner) -> Result<(), String> { + self.append(path, mode, owner, tar::EntryType::Directory, &[]) + } + + fn file(&mut self, path: &str, mode: u32, owner: Owner, content: &[u8]) -> Result<(), String> { + self.append(path, mode, owner, tar::EntryType::Regular, content) + } + + fn append( + &mut self, + path: &str, + mode: u32, + owner: Owner, + kind: tar::EntryType, + content: &[u8], + ) -> Result<(), String> { + let mut header = tar::Header::new_gnu(); + header.set_entry_type(kind); + header.set_mode(mode); + header.set_uid(u64::from(owner.uid)); + header.set_gid(u64::from(owner.gid)); + header.set_size(content.len() as u64); + header.set_mtime(0); + header.set_cksum(); + self.builder() + .append_data(&mut header, path.trim_start_matches('/'), content) + .map_err(invalid) + } + + fn finish(mut self) -> Result, String> { + self.builder().finish().map_err(invalid)?; + self.builder + .take() + .expect("builder was created above") + .into_inner() + .map_err(invalid) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::compute::v1::{DriverSandboxSpec, WorkloadIdentityRequest}; + use std::io::Read; + + fn sandbox_with_identity(user: &str, group: &str) -> DriverSandbox { + DriverSandbox { + id: "sb-1".into(), + name: "demo".into(), + spec: Some(DriverSandboxSpec { + workload_identity: Some(WorkloadIdentityRequest { + user: user.into(), + group: group.into(), + }), + ..DriverSandboxSpec::default() + }), + ..DriverSandbox::default() + } + } + + #[test] + fn identity_defaults_to_openshell_sandbox_user() { + let identity = resolve_identity(&sandbox_with_identity("", ""), "img").unwrap(); + assert_eq!((identity.uid, identity.gid), (1000, 1000)); + assert_eq!(identity.source, "default"); + } + + #[test] + fn identity_accepts_numeric_selectors() { + let identity = resolve_identity(&sandbox_with_identity("2000", "3000"), "img").unwrap(); + assert_eq!((identity.uid, identity.gid), (2000, 3000)); + assert_eq!(identity.source, "policy"); + } + + #[test] + fn identity_rejects_names_root_and_guard() { + assert!(resolve_identity(&sandbox_with_identity("sandbox", ""), "img").is_err()); + assert!(resolve_identity(&sandbox_with_identity("0", ""), "img").is_err()); + assert!(resolve_identity(&sandbox_with_identity("65534", ""), "img").is_err()); + } + + #[test] + fn provisioning_evidence_binds_generation() { + let evidence = provisioning_evidence("tl-1", "tl-1-guard", "gen-1").unwrap(); + assert!(evidence.validate("gen-1").is_ok()); + assert!(evidence.validate("gen-2").is_err()); + let other = provisioning_evidence("tl-2", "tl-2-guard", "gen-1").unwrap(); + assert_ne!(evidence.evidence_digest, other.evidence_digest); + assert!(provisioning_evidence("", "tl-1-guard", "gen-1").is_err()); + assert!(provisioning_evidence("tl-1", "", "gen-1").is_err()); + assert!(provisioning_evidence("tl-1", "tl-1-guard", "").is_err()); + } + + #[test] + fn child_environment_strips_control_keys() { + let mut sandbox = sandbox_with_identity("", ""); + let spec = sandbox.spec.as_mut().unwrap(); + spec.environment.insert( + openshell_core::sandbox_env::SANDBOX_TOKEN.into(), + "x".into(), + ); + spec.environment.insert("FOO".into(), "bar".into()); + let environment = child_environment(&sandbox); + assert_eq!(environment.get("FOO").map(String::as_str), Some("bar")); + assert!(!environment.contains_key(openshell_core::sandbox_env::SANDBOX_TOKEN)); + } + + #[test] + fn bundle_requires_launch_authentication() { + let sandbox = sandbox_with_identity("", ""); + let identity = resolve_identity(&sandbox, "img").unwrap(); + let config = crate::config::tests::test_config(); + let result = build_launch_bundles(LaunchBundleInput { + sandbox: &sandbox, + config: &config, + tensorlake_sandbox_id: "tl-1", + guard_tensorlake_id: "tl-1-guard", + identity: &identity, + gateway_ca_pem: None, + }); + assert!(result.unwrap_err().contains("launch-scoped")); + } + + fn launch_authentication() -> Vec { + use openshell_core::jwt::{ + CredentialEpoch, SandboxLaunchAuthentication, SecretJwt, SessionVerificationKey, + SupervisorAuthBundle, + }; + 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, + ocsf_otlp_headers: 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() + } + + fn read_entries(bytes: &[u8]) -> HashMap)> { + let mut reader = tar::Archive::new(bytes); + let mut entries = HashMap::new(); + for entry in reader.entries().unwrap() { + let mut entry = entry.unwrap(); + let header = entry.header().clone(); + let mut content = Vec::new(); + entry.read_to_end(&mut content).unwrap(); + entries.insert( + entry.path().unwrap().display().to_string(), + (header.mode().unwrap(), header.uid().unwrap(), content), + ); + } + entries + } + + fn launch_sandbox() -> DriverSandbox { + let mut sandbox = sandbox_with_identity("", ""); + let spec = sandbox.spec.as_mut().unwrap(); + spec.launch_authentication = launch_authentication(); + spec.sandbox_token = "sandbox.jwt.value".into(); + spec.environment.insert("FOO".into(), "bar".into()); + sandbox + } + + fn entry<'a>( + entries: &'a HashMap)>, + path: &str, + ) -> &'a (u32, u64, Vec) { + entries + .get(path.trim_start_matches('/')) + .unwrap_or_else(|| panic!("{path} missing from bundle")) + } + + #[test] + fn split_bundles_keep_every_secret_out_of_the_workload_vm() { + let sandbox = launch_sandbox(); + let identity = resolve_identity(&sandbox, "img").unwrap(); + let mut config = crate::config::tests::test_config(); + config.api_key = "tl_secret_key".into(); + config.api_url = "https://sandbox.example.test".into(); + config.platform_api_url = "https://api.example.test".into(); + let bundles = build_launch_bundles(LaunchBundleInput { + sandbox: &sandbox, + config: &config, + tensorlake_sandbox_id: "tl-1", + guard_tensorlake_id: "tl-1-guard", + identity: &identity, + gateway_ca_pem: Some(b"ca"), + }) + .unwrap(); + + // Workload VM: channel files and the workload role only. + let workload = read_entries(&bundles.workload); + let workload_text = String::from_utf8_lossy(&bundles.workload); + for secret in ["gateway.token.value", "sandbox.jwt.value", "tl_secret_key"] { + assert!( + !workload_text.contains(secret), + "{secret} leaked to the workload VM" + ); + } + for path in [ + AUTH_BUNDLE_PATH, + SANDBOX_TOKEN_PATH, + SUPERVISOR_DIR, + TUNNEL_ENV_PATH, + ] { + assert!( + !workload.contains_key(path.trim_start_matches('/')), + "{path}" + ); + } + let bootstrap = String::from_utf8_lossy(&entry(&workload, BOOTSTRAP_PATH).2); + assert!(bootstrap.contains("\"kind\":\"tls-tcp\"")); + assert!(bootstrap.contains(&format!("0.0.0.0:{WORKLOAD_LISTEN_PORT}"))); + assert!(bootstrap.contains("tl-1-guard")); + let params = String::from_utf8_lossy(&entry(&workload, LAUNCH_PARAMS_PATH).2); + assert!(params.contains("ROLE=workload\n")); + assert!(params.contains("WORKLOAD_UID=1000\n")); + assert!(params.contains("FORWARDER_UID=65533\n")); + assert!(params.contains("WORKLOAD_LISTEN_PORT=8444\n")); + assert!(params.contains("WORKLOAD_FORWARD_PORT=8443\n")); + assert!(!params.contains("SUPERVISOR_UID")); + + // Guard VM: credentials for the guard, the key for the tunnel, no + // channel server key. + let guard = read_entries(&bundles.guard); + assert!(!guard.contains_key(SERVER_KEY_PATH.trim_start_matches('/'))); + assert!(!guard.contains_key(BOOTSTRAP_PATH.trim_start_matches('/'))); + let descriptor = String::from_utf8_lossy(&entry(&guard, RUNTIME_DESCRIPTOR_PATH).2); + assert!(descriptor.contains(&format!("127.0.0.1:{GUARD_TUNNEL_PORT}"))); + assert!(descriptor.contains(&format!("tl-1:{WORKLOAD_LISTEN_PORT}"))); + let (mode, uid, env) = entry(&guard, TUNNEL_ENV_PATH); + assert_eq!((*mode, *uid), (0o600, u64::from(TUNNEL_UID))); + assert_eq!( + env, + b"TENSORLAKE_API_KEY=tl_secret_key\0TENSORLAKE_SANDBOX_API_URL=https://sandbox.example.test\0TENSORLAKE_API_URL=https://api.example.test\0" + ); + let (mode, uid, _) = entry(&guard, TUNNEL_DIR); + assert_eq!((*mode, *uid), (0o700, u64::from(TUNNEL_UID))); + let args = String::from_utf8_lossy(&entry(&guard, TUNNEL_ARGS_PATH).2); + assert_eq!( + args, + format!( + "sbx\0tunnel\0tl-1\0{WORKLOAD_FORWARD_PORT}\0--listen-port\0{GUARD_TUNNEL_PORT}\0" + ) + ); + let (mode, uid, _) = entry(&guard, AUTH_BUNDLE_PATH); + assert_eq!((*mode, *uid), (0o600, u64::from(SUPERVISOR_UID))); + let params = String::from_utf8_lossy(&entry(&guard, LAUNCH_PARAMS_PATH).2); + assert!(params.contains("ROLE=guard\n")); + assert!(params.contains("TUNNEL_UID=65533\n")); + assert!(params.contains("SUPERVISOR_UID=65534\n")); + assert!(!params.contains("WORKLOAD_UID")); + } + + #[test] + fn archive_sets_owner_and_mode() { + let mut archive = Archive::default(); + archive + .directory( + SUPERVISOR_DIR, + 0o700, + Owner::new(SUPERVISOR_UID, SUPERVISOR_GID), + ) + .unwrap(); + archive + .file( + AUTH_BUNDLE_PATH, + 0o600, + Owner::new(SUPERVISOR_UID, SUPERVISOR_GID), + b"{}", + ) + .unwrap(); + let bytes = archive.finish().unwrap(); + let mut reader = tar::Archive::new(bytes.as_slice()); + let mut entries = Vec::new(); + for entry in reader.entries().unwrap() { + let mut entry = entry.unwrap(); + let header = entry.header().clone(); + let mut content = Vec::new(); + entry.read_to_end(&mut content).unwrap(); + entries.push(( + entry.path().unwrap().display().to_string(), + header.mode().unwrap(), + header.uid().unwrap(), + content, + )); + } + assert_eq!(entries[0].0, ".openshell/supervisor"); + assert_eq!(entries[0].1, 0o700); + assert_eq!(entries[1].0, ".openshell/supervisor/auth.json"); + assert_eq!(entries[1].1, 0o600); + assert_eq!(entries[1].2, u64::from(SUPERVISOR_UID)); + assert_eq!(entries[1].3, b"{}"); + } + + #[test] + fn nul_list_terminates_each_entry() { + assert_eq!(nul_list(["a=1".to_string(), "b".to_string()]), b"a=1\0b\0"); + } +} diff --git a/crates/openshell-driver-tensorlake/src/lib.rs b/crates/openshell-driver-tensorlake/src/lib.rs new file mode 100644 index 0000000000..b031de3d31 --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/lib.rs @@ -0,0 +1,13 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +pub mod client; +pub mod config; +pub mod driver; +pub mod grpc; +pub mod launch; +pub mod state; + +pub use config::TensorlakeComputeConfig; +pub use driver::TensorlakeComputeDriver; +pub use grpc::ComputeDriverService; diff --git a/crates/openshell-driver-tensorlake/src/main.rs b/crates/openshell-driver-tensorlake/src/main.rs new file mode 100644 index 0000000000..796b8c06e8 --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/main.rs @@ -0,0 +1,196 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::path::PathBuf; +use std::time::Duration; + +use clap::Parser; +use miette::{IntoDiagnostic, Result}; +use tracing::info; + +use openshell_core::VERSION; +use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; +use openshell_driver_tensorlake::config::{ + DEFAULT_API_URL, DEFAULT_CPUS, DEFAULT_GUARD_CPUS, DEFAULT_GUARD_MEMORY_MB, DEFAULT_MEMORY_MB, + DEFAULT_PLATFORM_API_URL, +}; +use openshell_driver_tensorlake::{ + ComputeDriverService, TensorlakeComputeConfig, TensorlakeComputeDriver, +}; + +const TRACING: openshell_otel::ComputeDriverTracing = openshell_otel::compute_driver_tracing!(); + +#[derive(Parser)] +#[command(name = "openshell-driver-tensorlake")] +#[command(version = VERSION)] +struct Args { + /// Operator-owned JSON policy; omitted means driver config disabled. + #[arg( + long, + env = "OPENSHELL_DRIVER_ADMISSION_CONFIG_JSON", + default_value = "{}" + )] + admission_config_json: openshell_core::resource_admission::DriverAdmissionConfig, + + /// Unix socket that the gateway connects to. + #[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_SOCKET")] + bind_socket: PathBuf, + + #[arg(long, env = "OPENSHELL_LOG_LEVEL", default_value = "info")] + log_level: String, + + #[arg(long, env = "OPENSHELL_OTLP_ENDPOINT")] + otlp_endpoint: Option, + + #[arg(long, env = "OPENSHELL_GATEWAY_NAME")] + gateway_name: Option, + + /// Public gateway gRPC endpoint that guards in Tensorlake VMs dial. + #[arg(long, env = "OPENSHELL_GRPC_ENDPOINT")] + grpc_endpoint: String, + + /// PEM CA bundle that guards trust for the gateway. Required for https. + #[arg(long, env = "OPENSHELL_TENSORLAKE_GATEWAY_TLS_CA")] + gateway_tls_ca: Option, + + #[arg(long, env = "TENSORLAKE_API_URL", default_value = DEFAULT_API_URL)] + tensorlake_api_url: String, + + /// Tensorlake platform API. The tunnel in each guard VM checks its key + /// there, so `--allow-out` adds this host. + #[arg( + long, + env = "TENSORLAKE_PLATFORM_API_URL", + default_value = DEFAULT_PLATFORM_API_URL + )] + tensorlake_platform_api_url: String, + + #[arg(long, env = "TENSORLAKE_API_KEY", hide_env_values = true)] + tensorlake_api_key: String, + + /// Registered Tensorlake image with the `OpenShell` runtime and launcher. + #[arg(long, env = "OPENSHELL_SANDBOX_IMAGE")] + sandbox_image: String, + + /// Registered Tensorlake image for guard VMs. Defaults to the sandbox + /// image, which contains the guard and the Tensorlake CLI. + #[arg(long, env = "OPENSHELL_TENSORLAKE_GUARD_IMAGE")] + guard_image: Option, + + #[arg(long, env = "OPENSHELL_TENSORLAKE_GUARD_CPUS", default_value_t = DEFAULT_GUARD_CPUS)] + guard_cpus: f64, + + #[arg(long, env = "OPENSHELL_TENSORLAKE_GUARD_MEMORY_MB", default_value_t = DEFAULT_GUARD_MEMORY_MB)] + guard_memory_mb: i64, + + #[arg(long, env = "OPENSHELL_TENSORLAKE_CPUS", default_value_t = DEFAULT_CPUS)] + cpus: f64, + + #[arg(long, env = "OPENSHELL_TENSORLAKE_MEMORY_MB", default_value_t = DEFAULT_MEMORY_MB)] + memory_mb: i64, + + #[arg(long, env = "OPENSHELL_TENSORLAKE_DISK_MB")] + disk_mb: Option, + + /// Tensorlake idle timeout in seconds. 0 uses the plan maximum. Guard + /// traffic to the gateway is outbound, so Tensorlake counts a working + /// sandbox as idle; a short timeout suspends it. + #[arg(long, env = "OPENSHELL_TENSORLAKE_TIMEOUT_SECS", default_value_t = 0)] + timeout_secs: i64, + + /// Tensorlake `allow_out` entry (repeatable, or comma-separated in the + /// environment). The gateway host is added automatically. Empty keeps + /// Tensorlake internet access on and relies on the `OpenShell` guard. + #[arg(long, env = "OPENSHELL_TENSORLAKE_ALLOW_OUT", value_delimiter = ',')] + allow_out: Vec, + + #[arg( + long, + env = "OPENSHELL_TENSORLAKE_POLL_INTERVAL_SECS", + default_value_t = 3 + )] + poll_interval_secs: u64, + + /// Directory for a copy of each sandbox request. After a restart the + /// driver reads it to report recovered sandboxes under their names. + #[arg( + long, + env = "OPENSHELL_TENSORLAKE_STATE_DIR", + default_value = "target/openshell-tensorlake-driver" + )] + state_dir: PathBuf, +} + +#[tokio::main] +async fn main() -> Result<()> { + let args = Args::parse(); + let _tracing = openshell_otel::install_driver_tracing( + TRACING, + openshell_otel::DriverTracingConfig { + endpoint: args.otlp_endpoint.as_deref(), + gateway_name: args.gateway_name.as_deref(), + service_version: VERSION, + log_level: &args.log_level, + }, + ); + + let config = TensorlakeComputeConfig { + api_url: args.tensorlake_api_url, + platform_api_url: args.tensorlake_platform_api_url, + api_key: args.tensorlake_api_key, + default_image: args.sandbox_image, + grpc_endpoint: args.grpc_endpoint, + gateway_tls_ca: args.gateway_tls_ca, + default_cpus: args.cpus, + default_memory_mb: args.memory_mb, + default_disk_mb: args.disk_mb, + timeout_secs: Some(args.timeout_secs), + allow_out: args + .allow_out + .into_iter() + .map(|entry| entry.trim().to_string()) + .filter(|entry| !entry.is_empty()) + .collect(), + poll_interval: Duration::from_secs(args.poll_interval_secs.max(1)), + log_level: args.log_level, + guard_image: args.guard_image, + guard_cpus: args.guard_cpus, + guard_memory_mb: args.guard_memory_mb, + state_dir: args.state_dir, + }; + let driver = TensorlakeComputeDriver::new(config, args.admission_config_json) + .await + .map_err(|error| miette::miette!("{error}"))?; + + let service = ComputeDriverServer::new(ComputeDriverService::new(driver)); + 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 Tensorlake 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() +} + +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-tensorlake/src/state.rs b/crates/openshell-driver-tensorlake/src/state.rs new file mode 100644 index 0000000000..078596a799 --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/state.rs @@ -0,0 +1,224 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! On-disk copy of each sandbox request. +//! +//! Tensorlake keeps no labels, so a restarted driver can find its VMs by +//! name but not the `OpenShell` name, namespace, and spec the gateway gave +//! them. The gateway copies the name from every driver snapshot into its own +//! record and refuses a name change, so a recovered record without the name +//! can never update its status. This store keeps the request so recovery +//! can report it as it was. +//! +//! Files hold no secrets. Save clears the sandbox token and the launch +//! authentication, and the directory and files are owner-only. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; + +use openshell_core::proto::compute::v1::DriverSandbox; +use prost::Message as _; + +const SANDBOXES_DIR: &str = "sandboxes"; +const FILE_SUFFIX: &str = ".pb"; + +#[derive(Debug, Clone)] +pub struct StateStore { + dir: PathBuf, +} + +impl StateStore { + /// A store under `dir`. The directory is created on the first save. + pub fn new(dir: impl Into) -> Self { + Self { dir: dir.into() } + } + + fn sandboxes_dir(&self) -> PathBuf { + self.dir.join(SANDBOXES_DIR) + } + + fn path(&self, sandbox_id: &str) -> PathBuf { + self.sandboxes_dir() + .join(format!("{}{FILE_SUFFIX}", file_stem(sandbox_id))) + } + + /// Keep the request without its secrets. + pub async fn save(&self, sandbox: &DriverSandbox) -> Result<(), String> { + let mut stored = sandbox.clone(); + if let Some(spec) = stored.spec.as_mut() { + spec.sandbox_token.clear(); + spec.launch_authentication.clear(); + } + let dir = self.sandboxes_dir(); + ensure_private_dir(&dir) + .await + .map_err(|error| format!("create {}: {error}", dir.display()))?; + let destination = self.path(&sandbox.id); + let temporary = dir.join(format!( + ".{}.{}.tmp", + file_stem(&sandbox.id), + std::process::id() + )); + let result = write_private_file(&temporary, stored.encode_to_vec()).await; + let result = match result { + Ok(()) => tokio::fs::rename(&temporary, &destination).await, + Err(error) => Err(error), + }; + if let Err(error) = result { + let _ = tokio::fs::remove_file(&temporary).await; + return Err(format!("write {}: {error}", destination.display())); + } + Ok(()) + } + + /// The saved request, or `None` when there is no file for this ID. + pub async fn load(&self, sandbox_id: &str) -> Result, String> { + let path = self.path(sandbox_id); + 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(format!("read {}: {error}", path.display())), + }; + DriverSandbox::decode(bytes.as_slice()) + .map(Some) + .map_err(|error| format!("decode {}: {error}", path.display())) + } + + /// IDs of every saved request. An absent directory holds none. + pub async fn saved_ids(&self) -> Result, String> { + let dir = self.sandboxes_dir(); + let mut entries = match tokio::fs::read_dir(&dir).await { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(format!("read {}: {error}", dir.display())), + }; + let mut ids = Vec::new(); + while let Some(entry) = entries + .next_entry() + .await + .map_err(|error| format!("read {}: {error}", dir.display()))? + { + let name = entry.file_name(); + if let Some(id) = name + .to_str() + .and_then(|name| name.strip_suffix(FILE_SUFFIX)) + { + ids.push(id.to_string()); + } + } + Ok(ids) + } + + /// Delete the saved request. A missing file is not an error. + pub async fn remove(&self, sandbox_id: &str) -> Result<(), String> { + let path = self.path(sandbox_id); + match tokio::fs::remove_file(&path).await { + Ok(()) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(format!("remove {}: {error}", path.display())), + } + } +} + +/// A file name for a sandbox ID. IDs are UUIDs, but keep every other +/// character out of the path anyway. +fn file_stem(sandbox_id: &str) -> String { + sandbox_id + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect() +} + +async fn ensure_private_dir(dir: &Path) -> Result<(), std::io::Error> { + tokio::fs::create_dir_all(dir).await?; + tokio::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).await +} + +async fn write_private_file(path: &Path, bytes: Vec) -> Result<(), std::io::Error> { + tokio::fs::write(path, bytes).await?; + tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).await +} + +#[cfg(test)] +mod tests { + use super::*; + + use openshell_core::proto::compute::v1::DriverSandboxSpec; + + fn temp_store(label: &str) -> StateStore { + let dir = std::env::temp_dir().join(format!( + "openshell-tensorlake-state-{label}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + StateStore::new(dir) + } + + #[tokio::test] + async fn save_load_remove_round_trip() { + let store = temp_store("round-trip"); + let sandbox = DriverSandbox { + id: "aaaaaaaa-0000-4000-8000-000000000001".into(), + name: "demo".into(), + namespace: "default".into(), + workspace: "ws".into(), + spec: Some(DriverSandboxSpec { + log_level: "debug".into(), + sandbox_token: "secret-token".into(), + launch_authentication: b"{\"secret\":true}".to_vec(), + ..DriverSandboxSpec::default() + }), + ..DriverSandbox::default() + }; + + assert_eq!(store.load(&sandbox.id).await.unwrap(), None); + assert!(store.saved_ids().await.unwrap().is_empty()); + store.save(&sandbox).await.unwrap(); + + let loaded = store.load(&sandbox.id).await.unwrap().unwrap(); + assert_eq!(loaded.id, sandbox.id); + assert_eq!(loaded.name, "demo"); + assert_eq!(loaded.namespace, "default"); + assert_eq!(loaded.workspace, "ws"); + let spec = loaded.spec.unwrap(); + assert_eq!(spec.log_level, "debug"); + assert!(spec.sandbox_token.is_empty()); + assert!(spec.launch_authentication.is_empty()); + + let path = store.path(&sandbox.id); + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + let dir_mode = std::fs::metadata(store.sandboxes_dir()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(dir_mode, 0o700); + assert!( + !std::fs::read(&path) + .unwrap() + .windows(12) + .any(|window| window == b"secret-token") + ); + + assert_eq!(store.saved_ids().await.unwrap(), vec![sandbox.id.clone()]); + store.remove(&sandbox.id).await.unwrap(); + assert_eq!(store.load(&sandbox.id).await.unwrap(), None); + assert!(store.saved_ids().await.unwrap().is_empty()); + // Removing twice is fine. + store.remove(&sandbox.id).await.unwrap(); + } + + #[test] + fn file_stem_keeps_ids_inside_the_directory() { + let store = StateStore::new("/state"); + assert_eq!( + store.path("../etc/passwd"), + PathBuf::from("/state/sandboxes/---etc-passwd.pb") + ); + assert_eq!( + store.path("aaaaaaaa-0000-4000-8000-000000000001"), + PathBuf::from("/state/sandboxes/aaaaaaaa-0000-4000-8000-000000000001.pb") + ); + } +} diff --git a/docs/extensibility/drivers.mdx b/docs/extensibility/drivers.mdx index f3f5a6d42d..8610c7fb7b 100644 --- a/docs/extensibility/drivers.mdx +++ b/docs/extensibility/drivers.mdx @@ -30,6 +30,7 @@ to each driver crate: | MicroVM | [`openshell-driver-vm`](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-vm/README.md) | | Kubernetes | [`openshell-driver-kubernetes`](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-kubernetes/README.md) | | Windows MXC | [`openshell-driver-mxc`](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-mxc/README.md) | +| Tensorlake (extension driver) | [`openshell-driver-tensorlake`](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-tensorlake/README.md) | External compute drivers implement [`compute_driver.proto`](https://github.com/NVIDIA/OpenShell/blob/main/proto/compute_driver.proto). diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 430e90c92f..06f011c5d8 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -1091,7 +1091,7 @@ apply their own restart policy. The gateway's configured compute driver determines how OpenShell creates each sandbox. The CLI workflow stays the same across drivers: you create, connect to, inspect, and delete sandboxes through the gateway API. -For Docker, Podman, MicroVM, and Kubernetes behavior, refer to [Sandbox Runtimes](/how-it-works/sandboxes/runtimes). +For Docker, Podman, MicroVM, and Kubernetes behavior, refer to [Sandbox Runtimes](/how-it-works/sandboxes/runtimes). For remote microVMs on Tensorlake, refer to [Tensorlake Runtime](/how-it-works/sandboxes/tensorlake). ## Next Steps diff --git a/docs/how-it-works/sandboxes/runtimes.mdx b/docs/how-it-works/sandboxes/runtimes.mdx index f56d194d63..647f16463b 100644 --- a/docs/how-it-works/sandboxes/runtimes.mdx +++ b/docs/how-it-works/sandboxes/runtimes.mdx @@ -21,6 +21,7 @@ the sandbox record and driver-supported persistent storage. | [Podman](#podman-driver) | `podman` | Rootless Linux workstations without a Docker daemon. | | [MicroVM](#microvm-driver) | `vm` | Workloads need a VM boundary instead of a container boundary. | | [Kubernetes](#kubernetes-driver) | `kubernetes` | Shared clusters, remote compute, and GPU scheduling. | +| [Tensorlake](/how-it-works/sandboxes/tensorlake) | `tensorlake` | Remote microVMs without local virtualization. Experimental. | | Windows MXC | `mxc` | Coming soon. | ## Select a Compute Driver @@ -73,7 +74,7 @@ compute_driver = "kyma" socket_path = "/run/openshell/kyma.sock" ``` -The gateway does not start or supervise extension drivers. Restrict the socket so only the gateway user can access it. +The gateway does not start or supervise extension drivers. Restrict the socket so only the gateway user can access it. The [Tensorlake](/how-it-works/sandboxes/tensorlake) driver is an extension driver that ships in this repository. ## Size Sandboxes diff --git a/docs/how-it-works/sandboxes/tensorlake.mdx b/docs/how-it-works/sandboxes/tensorlake.mdx new file mode 100644 index 0000000000..77365e060b --- /dev/null +++ b/docs/how-it-works/sandboxes/tensorlake.mdx @@ -0,0 +1,220 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "Tensorlake Runtime" +sidebar-title: "Tensorlake" +description: "Run OpenShell sandboxes in Tensorlake microVMs without local virtualization." +keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Tensorlake, MicroVM, Remote Compute" +position: 5 +--- + +The Tensorlake driver runs each OpenShell sandbox in its own +[Tensorlake](https://tensorlake.ai) sandbox, a small virtual machine that +Tensorlake creates and deletes for you. Use it when you want a VM boundary but +have no local virtualization, or when you want sandboxes to run away from the +gateway host. + +The driver is an extension driver. It runs as its own process next to the +gateway and serves the compute driver API on a Unix socket. The CLI workflow +does not change: you create, connect to, exec into, and delete sandboxes +through the gateway as with any other runtime. + +The driver is experimental. Read [Trust model](#trust-model) before you attach +real credentials. + +## How It Works + +Each OpenShell sandbox maps to two Tensorlake VMs. The workload VM runs +`openshell-sandbox` and the agent, with a Tensorlake network policy that turns +off every outbound connection. The guard VM runs `openshell-supervisor`, which +holds the gateway session and the provider credentials, and a Tensorlake tunnel +that carries the guard's connection to the workload VM. Every connection the +agent makes travels over that channel to the guard, and the guard applies the +policy. The agent's VM never holds a credential. + +`openshell sandbox stop` suspends both VMs. Tensorlake keeps their disks, so +the workspace stays. `openshell sandbox start` resumes them with fresh +credentials and starts the main process again. + +The guard dials the gateway from inside Tensorlake. The gateway must therefore +be reachable from the internet, or at least from Tensorlake. A gateway on a +laptop behind NAT does not work. The supported setup runs the gateway and the +driver together in one long-lived Tensorlake sandbox, the control plane, and +protects it with OpenID Connect (OIDC) login. + +## Prerequisites + +- A Tensorlake account and API key. +- The `tl` CLI, logged in to the project that will run the sandboxes: + + ```shell + curl -fsSL https://tensorlake.ai/install | sh + tl login + ``` + +- For a production control plane, an OIDC provider that puts roles in the + token. See [OIDC](/how-it-works/gateways/authentication#oidc). + +## Run the Control Plane on Tensorlake + +The control plane is one Tensorlake sandbox that runs the gateway and the +driver. Guards in sandbox VMs reach it through the Tensorlake port proxy on a +public URL. The proxy terminates TLS. + +1. Choose an image pair. Use a published pair, or build your own from a + source checkout with `crates/openshell-driver-tensorlake/build-images.sh`. + A published pair is named after the OpenShell version it holds, for + example `openshell-control-0-1-6` and `openshell-tensorlake-0-1-6` for + v0.1.6. Pick the pair that matches your CLI version. The control image + records the name of its sandbox image, so the two always match. + +2. Deploy. The script creates the control sandbox, exposes port 8080, uploads + the settings, and starts the control plane as a managed process that + restarts on failure: + + ```shell + export TENSORLAKE_API_KEY=... + export CONTROL_IMAGE=openshell-control- + export OPENSHELL_OIDC_ISSUER=https://idp.example.com/realms/openshell + export OPENSHELL_OIDC_AUDIENCE=openshell-cli + crates/openshell-driver-tensorlake/control/deploy.sh + ``` + + The script prints the public URL and the sandbox ID. Run it again to change + settings. Gateway state stays in the sandbox. Set `OPENSHELL_DB_URL` to use + an external database. + +3. Register the gateway with the CLI. The CLI opens a browser for the login + and renews the token on its own: + + ```shell + openshell gateway add https://8080-.sandbox.tensorlake.ai \ + --oidc-issuer https://idp.example.com/realms/openshell \ + --oidc-client-id openshell-cli \ + --oidc-audience openshell-cli + ``` + +4. Create a sandbox: + + ```shell + openshell sandbox create --name demo -- bash + ``` + + The first boot takes 30 to 60 seconds. The CLI shows the launch steps: + the VM request, the VM start, the launch bundle upload, and the wait for + the guard session. + +### Why Login Is Required + +Guards in sandbox VMs cannot hold a Tensorlake key, so the control-plane port +must accept connections from anyone. The public URL cannot be hidden. The +gateway makes this safe by checking every call for a valid OIDC token. A call +without one gets `Unauthenticated`. A user who holds only the user role must +also be a member of the workspace. Add members with +`openshell workspace member add`. + + +The Tensorlake port proxy drops the gRPC status from error responses. A +denied or unauthenticated call through the public URL reaches the CLI as +`protocol error: missing grpc-status trailer`. When you see that message, +run `openshell gateway login` first. If it persists, run the same command +through a Tensorlake tunnel to read the real status. Successful calls are +not affected. + + +For a short test without an identity provider, set +`OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1` before you deploy, and reach the +gateway through a Tensorlake tunnel instead of the public URL: + +```shell +tl sbx tunnel openshell-control 8080 --listen-port 18080 +openshell gateway add http://127.0.0.1:18080 --name tensorlake +``` + +With this setting, anyone who has the public URL controls the gateway. Use it +only with test credentials. + +## Run the Driver Next to Your Own Gateway + +If you already run a gateway that Tensorlake VMs can reach, run the driver on +the same host as the same Unix user, and point the gateway at its socket. The +gateway needs launch signing (`[openshell.gateway.gateway_jwt]`). + +```shell +export TENSORLAKE_API_KEY=... +openshell-driver-tensorlake \ + --bind-socket /run/openshell/tensorlake.sock \ + --grpc-endpoint https://gateway.example.com:8080 \ + --gateway-tls-ca /etc/openshell/gateway-ca.pem \ + --sandbox-image openshell-tensorlake- +``` + +```toml +[openshell.gateway] +compute_driver = "tensorlake" + +[openshell.drivers.tensorlake] +socket_path = "/run/openshell/tensorlake.sock" +``` + +| Flag | Environment | Default | +|---|---|---| +| `--grpc-endpoint` | `OPENSHELL_GRPC_ENDPOINT` | Required. The URL guards dial. | +| `--gateway-tls-ca` | `OPENSHELL_TENSORLAKE_GATEWAY_TLS_CA` | Required for `https`. Guards trust only this bundle. | +| `--sandbox-image` | `OPENSHELL_SANDBOX_IMAGE` | Required. A registered Tensorlake image with the OpenShell runtime, the Tensorlake CLI, and the launcher. | +| `--guard-image` | `OPENSHELL_TENSORLAKE_GUARD_IMAGE` | The sandbox image. | +| `--guard-cpus`, `--guard-memory-mb` | `OPENSHELL_TENSORLAKE_GUARD_*` | 1, 1024 | +| `--cpus`, `--memory-mb`, `--disk-mb` | `OPENSHELL_TENSORLAKE_*` | 2, 4096, Tensorlake default | +| `--timeout-secs` | `OPENSHELL_TENSORLAKE_TIMEOUT_SECS` | `0`, the plan maximum | +| `--allow-out` | `OPENSHELL_TENSORLAKE_ALLOW_OUT` | Empty. Internet on for the guard VM; the guard enforces policy. | +| `--tensorlake-platform-api-url` | `TENSORLAKE_PLATFORM_API_URL` | `https://api.tensorlake.ai`. Where the tunnel checks its key. | +| `--state-dir` | `OPENSHELL_TENSORLAKE_STATE_DIR` | `target/openshell-tensorlake-driver`. Holds a copy of each sandbox request for recovery after a restart. | + +Keep `--timeout-secs` at `0`, the longest idle timeout your plan allows. A +shorter timeout can suspend a sandbox that is still working. + +`--allow-out` adds a second fence at the Tensorlake network for the VM that +runs the guard. That VM can then connect only to the hosts you list, the +gateway host, and the two Tensorlake hosts the tunnel uses. The workload VM +always has all outbound traffic off. + +## Images + +Sandbox images must contain the guard, the workload runtime, the Tensorlake +CLI, and the launch script. One image serves both VMs of a sandbox. Build them +on Tensorlake; no local Docker is needed: + +```shell +crates/openshell-driver-tensorlake/build-images.sh +``` + +To add agent tools, build a derived image whose Dockerfile starts +`FROM openshell-tensorlake-`, register it with `tl sbx image create`, +and pass its name to `openshell sandbox create --from`. The image must not +contain `/.openshell`. + +Tensorlake has no image tags, so a version is part of the image name. Do not +replace a published version. Publish a new one. + +## Trust Model + +The agent runs in a VM that holds only its own channel key. The gateway +session, the provider credentials, and the policy live in the guard VM. An agent that gains root in its VM gets no credential, and still has +no outbound path, because the Tensorlake network policy blocks every +connection that does not go through the guard. This is the same separation +the Kubernetes driver gives with a guard pod and a NetworkPolicy. + +Two things to know: + +- Each guard VM holds a Tensorlake API key for its tunnel. That key can open + tunnels to any sandbox in the same project. Run the control plane and its + sandboxes in a Tensorlake project of their own. +- Anyone with access to that project can run `tl sbx exec --user root` in a + guard VM and read its credentials. Project access is the trust boundary. + +## Scope + +A single team with its own Tensorlake project can run it today. + +For build details, test results, and the design notes, see the +[driver README](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-tensorlake/README.md). diff --git a/docs/index.yml b/docs/index.yml index 596ac87172..5eedb74f31 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -44,6 +44,8 @@ navigation: path: how-it-works/sandboxes/templates.mdx - page: "Runtimes" path: how-it-works/sandboxes/runtimes.mdx + - page: "Tensorlake" + path: how-it-works/sandboxes/tensorlake.mdx - section: "Providers" slug: providers contents: @@ -113,6 +115,9 @@ navigation: path: tutorials/github-push-access.mdx - page: "Microsoft Graph Provider Refresh" path: tutorials/microsoft-graph-provider-refresh.mdx + - page: "OpenCode on Tensorlake" + path: tutorials/run-opencode-on-tensorlake.mdx + slug: run-opencode-on-tensorlake - section: "SDK Reference" slug: sdk contents: diff --git a/docs/tutorials/index.mdx b/docs/tutorials/index.mdx index 22e9647f69..e6219e84c0 100644 --- a/docs/tutorials/index.mdx +++ b/docs/tutorials/index.mdx @@ -31,4 +31,9 @@ Launch Claude Code in a sandbox, diagnose a policy denial, and iterate on a cust Configure a Microsoft Graph provider profile with gateway-managed OAuth2 refresh-token rotation. + + +Build an OpenCode image on Tensorlake, run it in a two-VM sandbox with no local virtualization, and watch the guard mediate every connection. + + diff --git a/docs/tutorials/run-opencode-on-tensorlake.mdx b/docs/tutorials/run-opencode-on-tensorlake.mdx new file mode 100644 index 0000000000..bdb1e1f508 --- /dev/null +++ b/docs/tutorials/run-opencode-on-tensorlake.mdx @@ -0,0 +1,275 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "Run OpenCode on Tensorlake" +sidebar-title: "OpenCode on Tensorlake" +description: "Build an OpenCode image on Tensorlake, run it in an OpenShell sandbox with no local virtualization, and watch the guard mediate every connection." +keywords: "Generative AI, Cybersecurity, Tutorial, OpenCode, OpenRouter, Tensorlake, MicroVM, Sandbox, Provider Profile" +--- + +In this tutorial, you'll run [OpenCode](https://opencode.ai), a terminal +coding agent, inside an OpenShell sandbox on the +[Tensorlake runtime](/how-it-works/sandboxes/tensorlake). Each sandbox gets two +small virtual machines (VMs). The agent runs in one VM with no outbound +network. The guard runs in the other VM, holds your API key, and applies the +policy to every connection the agent makes. + +You'll build the image on Tensorlake, give OpenCode access to +[OpenRouter](https://openrouter.ai), start the agent, and then confirm four +things: + +- The agent VM has no network of its own. +- The API key never enters the agent VM. +- A denied request becomes an approved rule without a restart. +- Stop and start keep the agent's files. + +The example uses a free OpenRouter model, so it works without credits. + + +The Tensorlake driver is experimental. Read its +[trust model](/how-it-works/sandboxes/tensorlake#trust-model) before you attach +a credential you care about. + + +## Prerequisites + +You'll need: + +- A Tensorlake account and the `tl` CLI, logged in to your project: + + ```shell + curl -fsSL https://tensorlake.ai/install | sh + tl login + ``` + +- An OpenShell control plane on Tensorlake, added to your CLI as the current + gateway. Refer to + [Run the Control Plane on Tensorlake](/how-it-works/sandboxes/tensorlake#run-the-control-plane-on-tensorlake). + Note the name of its sandbox image. The default is `openshell-tensorlake`. +- An OpenRouter API key. + +You don't need Docker. Tensorlake builds the image for you. + + + +## Build the OpenCode Image + +A Tensorlake sandbox image for OpenShell must start from the sandbox image of +your control plane, because the agent VM needs the OpenShell launcher and +runtime from it. This Dockerfile adds the OpenCode binary on top. Save it as +`Dockerfile`: + +```dockerfile +FROM openshell-tensorlake + +ARG OPENCODE_VERSION=1.19.3 +RUN curl -fsSL "https://github.com/anomalyco/opencode/releases/download/v${OPENCODE_VERSION}/opencode-linux-x64.tar.gz" \ + | tar -xz -C /usr/local/bin opencode \ + && chmod 0755 /usr/local/bin/opencode \ + && /usr/local/bin/opencode --version +``` + +If your control plane uses another sandbox image name, change the `FROM` +line to match. Tensorlake does not expand variables in `FROM`. + +Two details matter here: + +- The binary goes at `/usr/local/bin/opencode`, because that's the only path + the OpenRouter provider profile allows. +- The Dockerfile downloads the glibc release from GitHub. The official + `ghcr.io/anomalyco/opencode` image is Alpine, and its binary needs the musl + loader, which the Ubuntu-based sandbox image doesn't have. + +Build the image on Tensorlake: + +```shell +tl sbx image create Dockerfile \ + --registered-name openshell-tensorlake-opencode --cas +``` + +The build takes about a minute and ends with the registered image name. + +## Give OpenCode Access to OpenRouter + +A sandbox has no network access until you grant it. To let OpenCode reach +OpenRouter, create a provider, which stores your API key and opens access to +the service. OpenCode only ever sees a placeholder for the key. The guard +swaps in the real key when OpenCode calls OpenRouter, and sends it nowhere +else. + +Import the +[OpenRouter profile](https://github.com/NVIDIA/OpenShell/blob/main/providers/openrouter.yaml) +and create a provider named `openrouter`: + +```shell +openshell profile import \ + --url https://raw.githubusercontent.com/NVIDIA/OpenShell/main/providers/openrouter.yaml + +OPENROUTER_API_KEY=your-key \ + openshell provider create \ + --name openrouter \ + --type openrouter \ + --from-existing +``` + +Replace `your-key` with your OpenRouter API key, or drop that prefix if +`OPENROUTER_API_KEY` is already set in your shell. The profile allows only +`/usr/local/bin/opencode` to reach `openrouter.ai`. + +## Start OpenCode in a Sandbox + +Create a sandbox from the image, attach the provider, and start OpenCode with +the free model: + +```shell +openshell sandbox create \ + --name opencode \ + --from openshell-tensorlake-opencode \ + --provider openrouter \ + -- opencode -m openrouter/nvidia/nemotron-3.5-lightning:free +``` + +The CLI shows each launch step: the VM request, the VM start, the launch bundle +upload, and the wait for the guard. The first boot takes 30 to 60 seconds. +Then OpenCode opens, and everything after `--` runs inside the agent VM. + +Send OpenCode a prompt: + +```text +Reply with exactly: OK from the sandbox +``` + +The guard VM forwards the request to OpenRouter and returns the answer over +the channel. The agent VM never opens a connection of its own. + +## Confirm the Agent VM Is Isolated + +Leave OpenCode running and open another terminal. Three checks show what the +agent VM can reach, what it knows about your key, and how Tensorlake sees it. +First, show that the agent VM has no network of its own: + +```shell +openshell sandbox exec -n opencode -- curl -sS --max-time 5 https://example.com +``` + +The connection fails at once. The Tensorlake network policy on the agent VM +turns off every outbound connection. The agent VM can only reach the guard. + +Next, show what the agent sees of your key: + +```shell +openshell sandbox exec -n opencode -- \ + sh -c 'printf "%.10s\n" "$OPENROUTER_API_KEY"' +``` + +The value starts with `openshell:`. It's a placeholder. The guard VM stores +the real key in a directory the agent VM can't read. + +Finally, look at the two VMs from the Tensorlake side: + +```shell +tl sbx ls +``` + +You'll see one VM named `openshell-` for the agent and one named +`openshell--guard` for the guard, plus your control plane. + +## Grant Access When OpenCode Needs It + +Back in OpenCode, ask it to reach a host the policy doesn't allow: + +```text +Run this shell command and report its output: curl -sS https://pypi.org/simple/requests/ +``` + +OpenCode runs the command and reports that the connection failed. OpenShell +denied it and drafted a rule for it. From the other terminal, list the +proposals: + +```shell +openshell rule get opencode --status pending +``` + +You'll see a narrow rule that allows `/usr/bin/curl` to reach `pypi.org:443`. +You may also see rules for hosts OpenCode tried on its own, such as +`registry.npmjs.org` and `models.opencode.ai`. Each proposal shows the result +of the [policy prover](/how-it-works/policies/prover), which checks the rule +against the current policy. Approve the PyPI rule with its chunk ID: + +```shell +openshell rule approve opencode --chunk-id +``` + +The gateway pushes the rule to the running sandbox within 30 seconds, without +a restart. Ask OpenCode to run the same command again, and this time it +returns the page. Leave the other proposals pending, or reject them: + +```shell +openshell rule reject opencode --chunk-id --reason "Not needed." +``` + +## Stop and Start the Sandbox + +A stopped sandbox keeps its disks, so OpenCode's files and the approved rule +survive a restart. To show this, ask OpenCode to write a file: + +```text +Write the text "hello" to a file named keep.txt +``` + +Then stop the sandbox from the other terminal: + +```shell +openshell sandbox stop opencode +``` + +Both VMs suspend in about 10 seconds. Tensorlake keeps their disks. Start the +sandbox again: + +```shell +openshell sandbox start opencode +``` + +The sandbox is ready in about 10 seconds, with fresh credentials and the same +disks. OpenCode starts again as the main process. Check that the file and the +approved rule are still there: + +```shell +openshell sandbox exec -n opencode -- cat /sandbox/keep.txt +openshell sandbox exec -n opencode -- \ + curl -sS --max-time 5 https://pypi.org/simple/requests/ +``` + +## Clean Up + +When you're finished, delete the sandbox. OpenShell deletes both VMs: + +```shell +openshell sandbox delete opencode +``` + + + +## Troubleshooting + +- If the sandbox fails with `LaunchFailed` and `No such file or directory`, + the image doesn't start from your control plane's sandbox image. Check the + `FROM` line. An image from `tl sbx image import` fails the same way, because + it lacks the OpenShell launcher. +- If `opencode` fails with `cannot execute: required file not found`, the + binary targets Alpine. Use the glibc release as the Dockerfile above does. +- If the guard denies OpenCode's requests to OpenRouter, make sure the binary + is at `/usr/local/bin/opencode`, the path the profile allows. +- If the guard still denies a request after you approve its rule, wait 30 + seconds and try again. The gateway pushes the new policy to the guard on its + next sync. + +## Next Steps + +- To understand the two-VM layout, the tunnel, and what each party can reach, + refer to [Tensorlake Runtime](/how-it-works/sandboxes/tensorlake). +- To let OpenCode propose its own rules, or to approve proposals automatically + when the prover finds no new risk, refer to + [Policy Advisor](/how-it-works/policies/advisor). +- To give OpenCode your own code, upload a directory with `--upload`. Refer to + [Transfer Files](/how-it-works/sandboxes/overview#transfer-files).