From 46f706d1d2671483e2aece8f404910ac6acb7622 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Thu, 15 Oct 2026 09:45:16 -0500 Subject: [PATCH 01/31] feat(driver-tensorlake): add initial Tensorlake compute driver Add a standalone ComputeDriver subprocess that runs each sandbox in a Tensorlake microVM. Include the launch image and register the crate in AGENTS.md. Signed-off-by: Shanshan Wang --- AGENTS.md | 1 + Cargo.lock | 25 + crates/openshell-driver-tensorlake/Cargo.toml | 42 + crates/openshell-driver-tensorlake/README.md | 120 +++ .../image/Dockerfile | 41 + .../image/openshell-tensorlake-launch.sh | 114 +++ .../openshell-driver-tensorlake/src/client.rs | 314 +++++++ .../openshell-driver-tensorlake/src/config.rs | 158 ++++ .../openshell-driver-tensorlake/src/driver.rs | 888 ++++++++++++++++++ .../openshell-driver-tensorlake/src/grpc.rs | 171 ++++ .../openshell-driver-tensorlake/src/launch.rs | 720 ++++++++++++++ crates/openshell-driver-tensorlake/src/lib.rs | 12 + .../openshell-driver-tensorlake/src/main.rs | 157 ++++ 13 files changed, 2763 insertions(+) create mode 100644 crates/openshell-driver-tensorlake/Cargo.toml create mode 100644 crates/openshell-driver-tensorlake/README.md create mode 100644 crates/openshell-driver-tensorlake/image/Dockerfile create mode 100755 crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh create mode 100644 crates/openshell-driver-tensorlake/src/client.rs create mode 100644 crates/openshell-driver-tensorlake/src/config.rs create mode 100644 crates/openshell-driver-tensorlake/src/driver.rs create mode 100644 crates/openshell-driver-tensorlake/src/grpc.rs create mode 100644 crates/openshell-driver-tensorlake/src/launch.rs create mode 100644 crates/openshell-driver-tensorlake/src/lib.rs create mode 100644 crates/openshell-driver-tensorlake/src/main.rs 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..5180584bf4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4610,6 +4610,30 @@ dependencies = [ "uuid", ] +[[package]] +name = "openshell-driver-tensorlake" +version = "0.0.0" +dependencies = [ + "clap", + "futures", + "miette", + "openshell-core", + "openshell-isolation-interface", + "openshell-otel", + "openshell-sandbox-backend", + "reqwest 0.12.28", + "rustls", + "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 +8248,7 @@ dependencies = [ "futures-core", "pin-project-lite", "tokio", + "tokio-util", ] [[package]] diff --git a/crates/openshell-driver-tensorlake/Cargo.toml b/crates/openshell-driver-tensorlake/Cargo.toml new file mode 100644 index 0000000000..e759320514 --- /dev/null +++ b/crates/openshell-driver-tensorlake/Cargo.toml @@ -0,0 +1,42 @@ +# 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-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"] } +futures = { workspace = true } +tokio-stream = { workspace = true, features = ["sync"] } +reqwest = { workspace = true } +rustls = { 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..54f9ed39bc --- /dev/null +++ b/crates/openshell-driver-tensorlake/README.md @@ -0,0 +1,120 @@ +# openshell-driver-tensorlake + +Out-of-process compute driver that runs each OpenShell sandbox in its own +[Tensorlake](https://tensorlake.ai) sandbox (a Firecracker microVM). + +This is the basic, combined topology: the guard (`openshell-supervisor`) and +the workload runtime (`openshell-sandbox`) run in the same Tensorlake VM. The +guard holds gateway and provider credentials inside that VM. Use it with +non-production credentials only. A later split topology moves the guard into +its own VM. + +## How it works + +``` +openshell CLI ──► gateway ──UDS──► openshell-driver-tensorlake ──HTTPS──► Tensorlake API + ▲ + │ guard dials the gateway (outbound only) + ┌──────────────────┴───── Tensorlake VM ────────────────────┐ + │ openshell-supervisor (uid 65534, holds credentials) │ + │ ▲ TLS over /.openshell/channel/sandbox/control.sock│ + │ openshell-sandbox (uid 1000, own network namespace with │ + │ only loopback) ──► agent processes │ + └───────────────────────────────────────────────────────────┘ +``` + +1. `CreateSandbox` calls `POST /sandboxes` with `wait: false` and returns. +2. A background task waits until the VM is `running`. +3. The driver builds a launch bundle (tar) with owners and modes set per file, + uploads it with the Tensorlake file API, and starts + `/opt/openshell/bin/openshell-tensorlake-launch` as root with the + Tensorlake process API. +4. The launcher extracts the bundle, deletes it, starts the workload runtime in + a loopback-only network namespace, and starts the guard as uid 65534. +5. The driver reports `Ready=True` when the launcher starts. The gateway marks + the sandbox ready when the guard session connects. + +A poll loop reads `GET /sandboxes` because Tensorlake has no watch API. + +### Credential layout in the VM + +| Path | Owner | Contents | +|---|---|---| +| `/.openshell/channel/sandbox/` | workload | boundary bootstrap and boundary TLS key | +| `/.openshell/supervisor/` (0700) | guard | auth bundle, sandbox JWT, gateway CA, runtime descriptor | +| `/.openshell/supervisor/env`, `args` | root | guard environment and arguments | + +The workload identity cannot read the guard's files. Root in the VM can. + +### Outer fence + +The launcher runs the workload in a new network namespace that has only +loopback, so the workload has no network path except the boundary channel. +The driver reports all four outer-fence guarantees based on this launch +recipe. It cannot inspect the VM to confirm them. + +Tensorlake `allow_out` is an optional second wall for the guard's own egress. + +## Build the image + +```shell +docker build -f crates/openshell-driver-tensorlake/image/Dockerfile \ + --build-arg OPENSHELL_TAG= -t openshell-tensorlake . +``` + +Register the image with Tensorlake (`tl sbx image create`). The image must +not contain `/.openshell`. Derive from it to add agent tools. + +## Run + +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 its +gRPC endpoint must be reachable from Tensorlake VMs. + +```shell +export TENSORLAKE_API_KEY=... +openshell-driver-tensorlake \ + --bind-socket /run/openshell/tensorlake.sock \ + --grpc-endpoint https://gateway.example.com:8080 \ + --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` | none | +| `--tensorlake-api-url` | `TENSORLAKE_API_URL` | `https://sandbox.tensorlake.ai` | +| `--tensorlake-api-key` | `TENSORLAKE_API_KEY` | required | +| `--sandbox-image` | `OPENSHELL_SANDBOX_IMAGE` | required | +| `--cpus` / `--memory-mb` / `--disk-mb` | `OPENSHELL_TENSORLAKE_*` | 2 / 4096 / Tensorlake default | +| `--timeout-secs` | `OPENSHELL_TENSORLAKE_TIMEOUT_SECS` | Tensorlake default | +| `--allow-out` | `OPENSHELL_TENSORLAKE_ALLOW_OUT` | empty (internet on) | +| `--poll-interval-secs` | `OPENSHELL_TENSORLAKE_POLL_INTERVAL_SECS` | 3 | + +When `--allow-out` is set, the driver turns off Tensorlake internet access and +adds the gateway host to the list. + +## Limits + +- Stop and start return `Unimplemented`. Delete the sandbox instead. +- Workload identity accepts numeric UID and GID only. The default is 1000:1000. +- No GPU, `driver_config`, `platform_config`, or `agent_socket_path`. +- The driver keeps launch state in memory. After a driver restart, running + sandboxes are recovered from Tensorlake names (`openshell-`). Sandboxes + that had not launched are reported as failed. +- A user with Tensorlake account access can run `tl sbx exec --user root` and + bypass OpenShell. + +## Not yet verified on Tensorlake + +The unit tests cover bundle layout, request mapping, and status mapping. An +end-to-end run on Tensorlake still needs to confirm that: + +- the guest kernel enables Landlock and seccomp, and allows `unshare --net`; +- the file API writes as root, and the process API runs the launcher as root; +- the guard can reach the gateway over a long-lived gRPC connection. diff --git a/crates/openshell-driver-tensorlake/image/Dockerfile b/crates/openshell-driver-tensorlake/image/Dockerfile new file mode 100644 index 0000000000..84def73cba --- /dev/null +++ b/crates/openshell-driver-tensorlake/image/Dockerfile @@ -0,0 +1,41 @@ +# 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), and the launcher to an Ubuntu base. Add agent tools +# (for example Claude Code) in a derived image. +# +# Build from the repository root: +# docker build -f crates/openshell-driver-tensorlake/image/Dockerfile \ +# --build-arg OPENSHELL_TAG= -t openshell-tensorlake . +# Then register the image with Tensorlake (`tl sbx image create`). + +ARG OPENSHELL_TAG=latest +ARG BASE_IMAGE=ubuntu:24.04 + +FROM ghcr.io/nvidia/openshell/supervisor:${OPENSHELL_TAG} AS supervisor +FROM ghcr.io/nvidia/openshell/sandbox:${OPENSHELL_TAG} AS sandbox + +FROM ${BASE_IMAGE} + +# iproute2: loopback in the workload network namespace. +# util-linux: unshare and setpriv. ca-certificates: guard TLS to upstreams. +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates iproute2 util-linux \ + && rm -rf /var/lib/apt/lists/* + +# 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 --chmod=0555 /openshell-supervisor /opt/openshell/bin/openshell-supervisor +COPY --from=sandbox --chmod=0555 /openshell-sandbox /opt/openshell/bin/openshell-sandbox +COPY --chmod=0555 crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh \ + /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..183276e39d --- /dev/null +++ b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh @@ -0,0 +1,114 @@ +#!/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 script: +# +# 1. Extracts the bundle with the owners and modes the driver set, then +# deletes it. +# 2. Starts the workload runtime (openshell-sandbox) in a new network +# namespace that has only loopback. The workload has no network path +# except the authenticated boundary channel to the guard. +# 3. Starts the guard (openshell-supervisor) as an unprivileged identity +# that the workload cannot read. +# +# The script stays in the foreground and exits when either process exits. + +set -euo pipefail + +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 +BOOTSTRAP=/.openshell/channel/sandbox/bootstrap.json +WORKLOAD_RESOLV_CONF=/.openshell/launch/resolv.conf + +log() { + printf '[openshell-tensorlake-launch] %s\n' "$*" >&2 +} + +fatal() { + log "FATAL: $*" + exit 1 +} + +[ "$(id -u)" -eq 0 ] || fatal "must run as root" +[ -f "$BUNDLE" ] || fatal "launch bundle $BUNDLE is missing" + +umask 077 +chmod 0600 "$BUNDLE" +if [ -e /.openshell ]; then + fatal "/.openshell already exists; this sandbox was already launched" +fi +tar --extract --file "$BUNDLE" --directory / --same-owner --same-permissions --numeric-owner +rm -f "$BUNDLE" + +# Read launch parameters (KEY=VALUE, numeric values and absolute paths). +WORKLOAD_UID="" WORKLOAD_GID="" SUPERVISOR_UID="" SUPERVISOR_GID="" +WORKSPACE="" SUPERVISOR_RUN_DIR="" +while IFS='=' read -r key value; do + case "$key" in + WORKLOAD_UID) WORKLOAD_UID="$value" ;; + WORKLOAD_GID) WORKLOAD_GID="$value" ;; + SUPERVISOR_UID) SUPERVISOR_UID="$value" ;; + SUPERVISOR_GID) SUPERVISOR_GID="$value" ;; + WORKSPACE) WORKSPACE="$value" ;; + SUPERVISOR_RUN_DIR) SUPERVISOR_RUN_DIR="$value" ;; + "") ;; + *) fatal "unknown launch parameter $key" ;; + esac +done <"$PARAMS" +for id in "$WORKLOAD_UID" "$WORKLOAD_GID" "$SUPERVISOR_UID" "$SUPERVISOR_GID"; do + [[ "$id" =~ ^[0-9]+$ ]] || fatal "launch identity '$id' is not numeric" +done +[[ "$WORKSPACE" == /* && "$SUPERVISOR_RUN_DIR" == /* ]] || fatal "launch paths must be absolute" + +# Guard runtime directory: proxy TLS material, SSH socket, health socket. +install -d -m 0700 -o "$SUPERVISOR_UID" -g "$SUPERVISOR_GID" "$SUPERVISOR_RUN_DIR" + +# Workload directories. openshell-sandbox makes the workspace owned by the +# workload identity before it drops privileges. +install -d -m 0755 "$WORKSPACE" +install -d -m 0700 -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" + +pids=() +cleanup() { + for pid in "${pids[@]}"; do + kill "$pid" 2>/dev/null || true + done +} +trap cleanup EXIT + +# Workload: private network and mount namespaces. Only loopback exists in +# the network namespace. The resolver points at the sandbox DNS relay. +log "starting workload runtime as ${WORKLOAD_UID}:${WORKLOAD_GID}" +unshare --net --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+=("$!") + +# Guard: unprivileged identity, clean environment, no capabilities. +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+=("$!") + +set +e +wait -n "${pids[@]}" +status=$? +set -e +log "a launched process exited with status $status; stopping the other" +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..4348186a13 --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/client.rs @@ -0,0 +1,314 @@ +// 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`). +//! 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 reqwest::StatusCode; +use serde::{Deserialize, Serialize}; + +const SANDBOX_ID_HEADER: &str = "X-Tensorlake-Sandbox-Id"; +const ROUTE_HINT_HEADER: &str = "X-Tensorlake-Route-Hint"; + +#[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, +} + +#[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 name: String, + pub stdin_mode: &'static str, +} + +#[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 { + let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + let http = reqwest::Client::builder() + .user_agent(format!( + "openshell-driver-tensorlake/{}", + openshell_core::VERSION + )) + .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) + } + + /// 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<(), TensorlakeError> { + let request = self + .proxy_request(sandbox, reqwest::Method::POST, "/api/v1/processes")? + .json(request); + check(request.send().await?).await?; + Ok(()) + } + + 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 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..5b6808342d --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -0,0 +1,158 @@ +// 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 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); + +#[derive(Clone)] +pub struct TensorlakeComputeConfig { + /// Tensorlake sandbox lifecycle API base URL. + pub 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, + /// Optional gateway CA bundle (PEM). Required when the gateway uses a + /// private CA. + pub gateway_tls_ca: Option, + pub default_cpus: f64, + pub default_memory_mb: i64, + pub default_disk_mb: Option, + /// Tensorlake sandbox timeout. `None` uses the Tensorlake default. + 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, +} + +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("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) + .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(), + ); + } + url::Url::parse(&self.grpc_endpoint) + .map_err(|error| format!("invalid gateway gRPC endpoint: {error}"))?; + url::Url::parse(&self.api_url) + .map_err(|error| format!("invalid Tensorlake API URL: {error}"))?; + 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()); + } + Ok(()) + } + + /// Tensorlake `allow_out` with the gateway host added, so the guard can + /// always reach the gateway. + pub fn effective_allow_out(&self) -> Vec { + let mut entries = self.allow_out.clone(); + if entries.is_empty() { + return entries; + } + if let Some(host) = url::Url::parse(&self.grpc_endpoint) + .ok() + .and_then(|url| url.host_str().map(str::to_string)) + && !entries.contains(&host) + { + entries.push(host); + } + entries + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + pub fn test_config() -> TensorlakeComputeConfig { + TensorlakeComputeConfig { + api_url: DEFAULT_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(), + } + } + + #[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"] + ); + } + + #[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_missing_endpoint() { + let mut config = test_config(); + config.grpc_endpoint.clear(); + 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..08397155e6 --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -0,0 +1,888 @@ +// 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 Firecracker VM). +//! Create returns after Tensorlake accepts the request. A background task then +//! waits for the VM to run, uploads the launch bundle, and starts the in-image +//! launcher as root. A poll loop keeps status current because Tensorlake has no +//! watch API. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use futures::{Stream, StreamExt as _}; +use openshell_core::proto::compute::v1::{ + CpuResourceCapabilities, DriverCondition, DriverSandbox, DriverSandboxStatus, + GetCapabilitiesResponse, GpuResourceCapabilities, MemoryResourceCapabilities, + ResolvedWorkloadIdentity as ProtoIdentity, ResourceCapabilities, WatchSandboxesDeletedEvent, + WatchSandboxesEvent, 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, Resources, SandboxInfo, StartProcessRequest, + TensorlakeClient, TensorlakeError, +}; +use crate::config::TensorlakeComputeConfig; +use crate::launch::{self, LaunchBundleInput}; + +/// Prefix for Tensorlake sandbox names created by this driver. +pub const NAME_PREFIX: &str = "openshell-"; + +/// How long a Tensorlake sandbox may stay pending before create fails. +const PROVISION_TIMEOUT: Duration = Duration::from_mins(10); + +const WATCH_BUFFER: usize = 256; + +#[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, + Suspended, + Failed { + reason: String, + message: String, + }, + Deleting, +} + +#[derive(Debug, Clone)] +struct Record { + sandbox: DriverSandbox, + tensorlake_id: String, + tensorlake_name: String, + identity: Option, + phase: Phase, +} + +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: vec![ready_condition(&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 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::Suspended => ( + "False", + "Suspended", + "Tensorlake sandbox is suspended; the Tensorlake driver cannot resume it yet" + .to_string(), + ), + Phase::Failed { reason, message } => ("False", reason.as_str(), message.clone()), + Phase::Deleting => ( + "False", + "Deleting", + "Tensorlake sandbox is being deleted".to_string(), + ), + }; + DriverCondition { + r#type: "Ready".to_string(), + status: status.to_string(), + reason: reason.to_string(), + message, + transition_time: None, + } +} + +/// 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}") +} + +/// 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, +} + +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 driver = Self { + client, + config: Arc::new(config), + admission: Arc::new(admission), + gateway_ca_pem, + records: Arc::new(Mutex::new(HashMap::new())), + events, + }; + 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); + 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, + } + } + + 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", + )); + } + if spec.launch_authentication.is_empty() { + return Err(Status::failed_precondition( + "Tensorlake sandboxes require launch-scoped gateway authentication", + )); + } + 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)?; + if self.records.lock().await.contains_key(&sandbox.id) { + return Err(Status::already_exists("sandbox already exists")); + } + let allow_out = self.config.effective_allow_out(); + let network = (!allow_out.is_empty()).then(|| NetworkPolicy { + allow_internet_access: false, + allow_out, + deny_out: Vec::new(), + }); + let name = tensorlake_name(&sandbox.id); + let request = CreateSandboxRequest { + image: Some(self.image_for(sandbox)), + resources: Some(resources), + timeout_secs: self.config.timeout_secs, + network, + name: Some(name.clone()), + wait: Some(false), + }; + let created = self + .client + .create_sandbox(&request) + .await + .map_err(|error| match error { + TensorlakeError::Api { status, .. } if status.as_u16() == 409 => { + Status::already_exists("Tensorlake sandbox already exists") + } + other => Status::unavailable(other.to_string()), + })?; + info!( + sandbox_id = %sandbox.id, + tensorlake_sandbox_id = %created.sandbox_id, + "Created Tensorlake sandbox" + ); + + // Keep secrets out of the stored record; only the provisioning task + // sees the launch credentials. + let mut stored = sandbox.clone(); + if let Some(spec) = stored.spec.as_mut() { + spec.sandbox_token.clear(); + spec.launch_authentication.clear(); + } + let record = Record { + sandbox: stored, + tensorlake_id: created.sandbox_id.clone(), + tensorlake_name: name, + identity: Some(identity.clone()), + phase: Phase::Pending, + }; + self.records + .lock() + .await + .insert(sandbox.id.clone(), record.clone()); + self.emit_sandbox(&record); + + let driver = self.clone(); + let sandbox = sandbox.clone(); + tokio::spawn(async move { + if let Err(message) = driver + .provision(&sandbox, &created.sandbox_id, &identity) + .await + { + warn!(sandbox_id = %sandbox.id, %message, "Tensorlake sandbox launch failed"); + driver + .set_phase( + &sandbox.id, + Phase::Failed { + reason: "LaunchFailed".into(), + message, + }, + ) + .await; + } + }); + Ok(()) + } + + /// Wait for the VM, upload the launch bundle, and start the launcher. + async fn provision( + &self, + sandbox: &DriverSandbox, + tensorlake_id: &str, + identity: &ResolvedWorkloadIdentity, + ) -> Result<(), String> { + let started = Instant::now(); + let info = loop { + if !self.is_active(&sandbox.id).await { + return Ok(()); + } + let info = self + .client + .get_sandbox(tensorlake_id) + .await + .map_err(|error| error.to_string())?; + match info.status.as_str() { + "running" => break info, + "pending" => {} + other => { + return Err(format!( + "Tensorlake sandbox entered state '{other}' before launch{}", + failure_detail(&info) + )); + } + } + if started.elapsed() > PROVISION_TIMEOUT { + return Err("Tensorlake sandbox did not start within 10 minutes".into()); + } + tokio::time::sleep(self.config.poll_interval).await; + }; + self.set_phase(&sandbox.id, Phase::Launching).await; + + let bundle = launch::build_launch_bundle(LaunchBundleInput { + sandbox, + config: &self.config, + tensorlake_sandbox_id: tensorlake_id, + identity, + gateway_ca_pem: self.gateway_ca_pem.as_deref().map(Vec::as_slice), + })?; + self.client + .write_file(&info, launch::BUNDLE_UPLOAD_PATH, bundle) + .await + .map_err(|error| format!("upload launch bundle: {error}"))?; + 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(), + name: launch::LAUNCHER_PROCESS_NAME.to_string(), + stdin_mode: "closed", + }, + ) + .await + .map_err(|error| format!("start OpenShell launcher: {error}"))?; + info!(sandbox_id = %sandbox.id, "Started OpenShell launcher in Tensorlake sandbox"); + self.set_phase(&sandbox.id, Phase::Running).await; + Ok(()) + } + + 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 = { + 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 + }; + let deleted = self + .client + .delete_sandbox(&tensorlake_id) + .await + .map_err(|error| Status::unavailable(error.to_string()))?; + if !deleted { + 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) + } + + async fn is_active(&self, sandbox_id: &str) -> bool { + self.records + .lock() + .await + .get(sandbox_id) + .is_some_and(|record| record.phase != Phase::Deleting) + } + + 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() { + let _ = self.events.send(WatchSandboxesEvent { + payload: Some(watch_sandboxes_event::Payload::Deleted( + WatchSandboxesDeletedEvent { + sandbox_id: sandbox_id.to_string(), + }, + )), + }); + } + } + + fn emit_sandbox(&self, record: &Record) { + let _ = self.events.send(sandbox_event(record.snapshot())); + } + + /// 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. + async fn recover(&self) -> Result<(), String> { + let sandboxes = self + .client + .list_sandboxes() + .await + .map_err(|error| format!("list Tensorlake sandboxes: {error}"))?; + let mut records = self.records.lock().await; + for info in sandboxes { + let Some(sandbox_id) = info + .name + .as_deref() + .and_then(|name| name.strip_prefix(NAME_PREFIX)) + .filter(|id| !id.is_empty()) + else { + continue; + }; + let phase = match observed_phase(&info) { + Some(Phase::Pending) => Phase::Failed { + reason: "DriverRestarted".into(), + message: "the Tensorlake driver restarted before this sandbox launched; delete and recreate it".into(), + }, + Some(phase) => phase, + None => continue, + }; + records.insert( + sandbox_id.to_string(), + Record { + sandbox: DriverSandbox { + id: sandbox_id.to_string(), + ..DriverSandbox::default() + }, + tensorlake_id: info.sandbox_id.clone(), + tensorlake_name: info.name.clone().unwrap_or_default(), + identity: None, + phase, + }, + ); + } + 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> { + let observed: HashMap = self + .client + .list_sandboxes() + .await? + .into_iter() + .map(|info| (info.sandbox_id.clone(), info)) + .collect(); + let records: Vec<(String, Record)> = self + .records + .lock() + .await + .iter() + .map(|(id, record)| (id.clone(), record.clone())) + .collect(); + for (sandbox_id, record) in records { + let info = observed.get(&record.tensorlake_id); + let phase = info.and_then(observed_phase); + match (&record.phase, phase) { + // Gone from Tensorlake while we delete it: finish the delete. + (Phase::Deleting, None) => self.forget(&sandbox_id).await, + (_, None) => { + let detail = info.map(failure_detail).unwrap_or_default(); + self.set_phase( + &sandbox_id, + Phase::Failed { + reason: "TensorlakeTerminated".into(), + message: format!("Tensorlake sandbox is no longer running{detail}"), + }, + ) + .await; + } + // Keep the current phase while a delete runs, while the + // provisioning task owns launch progress, or after a failed + // launch on a VM that still runs. + (Phase::Deleting, Some(_)) + | (Phase::Pending | Phase::Launching, Some(Phase::Pending | Phase::Running)) + | (Phase::Failed { .. }, Some(Phase::Running)) => {} + (_, Some(next)) => self.set_phase(&sandbox_id, next).await, + } + } + Ok(()) + } +} + +/// 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::Suspended), + _ => 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("; ")) + } +} + +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); + } + + #[test] + fn validate_rejects_unsupported_requests() { + 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_err()); + + 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 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"); + } + + #[test] + fn observed_phase_treats_terminal_states_as_gone() { + let info = |status: &str| 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, + }; + assert_eq!(observed_phase(&info("running")), Some(Phase::Running)); + assert_eq!(observed_phase(&info("suspended")), Some(Phase::Suspended)); + 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..6a5852a597 --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/grpc.rs @@ -0,0 +1,171 @@ +// 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> { + required_id(&request.into_inner().sandbox_id)?; + Err(Status::unimplemented( + "the Tensorlake driver cannot stop a sandbox yet; delete it instead", + )) + } + + async fn start_sandbox( + &self, + _request: Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "the Tensorlake driver cannot restart a sandbox yet", + )) + } + + 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..a345f47d5a --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -0,0 +1,720 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Launch bundle for the combined Tensorlake topology. +//! +//! The guard (`openshell-supervisor`) and the starter (`openshell-sandbox`) +//! run in the same Tensorlake VM. The driver builds one tar archive per +//! sandbox generation. The in-image launcher extracts it as root, so each file +//! keeps the owner and mode set here: +//! +//! - `/.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. +//! +//! The launcher starts the workload in a new network namespace that has only +//! loopback. This is the outer fence: the workload has no network path except +//! the authenticated boundary channel, even if the guard exits. + +use std::collections::{BTreeMap, HashMap}; +use std::path::PathBuf; + +use openshell_core::proto::compute::v1::DriverSandbox; +use openshell_isolation_interface::contract::{ + OuterFenceGuarantee, OuterFenceGuarantees, 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"; +/// Tensorlake process name for the launcher. +pub const LAUNCHER_PROCESS_NAME: &str = "openshell-launch"; + +/// 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; + +const WORKSPACE: &str = "/sandbox"; +const SOCKET_PATH: &str = "/.openshell/channel/sandbox/control.sock"; +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"; + +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 uid == SUPERVISOR_UID || gid == SUPERVISOR_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 that the launcher builds. The driver cannot +/// inspect the VM, so the evidence names the launch recipe it requested. +#[derive(Serialize)] +struct TensorlakeOuterFenceEvidence<'a> { + tensorlake_sandbox_id: &'a str, + workload_network_namespace: &'static str, + launcher: &'static str, +} + +fn outer_fence( + tensorlake_sandbox_id: &str, + generation: &str, +) -> Result { + let evidence = TensorlakeOuterFenceEvidence { + tensorlake_sandbox_id, + workload_network_namespace: "private-loopback-only", + launcher: LAUNCHER_PATH, + }; + // A loopback-only network namespace has no route out. Egress needs a + // mediated decision, revocation takes effect at the guard, and guard loss + // leaves the namespace without a path. + let projection = OuterFenceGuarantees::from_enforcement_evidence( + generation, + [ + OuterFenceGuarantee::DefaultDenyEgress, + OuterFenceGuarantee::NoUnmanagedEgressPath, + OuterFenceGuarantee::RevocationVerified, + OuterFenceGuarantee::ControllerLossFailsClosed, + ], + &serde_json::to_vec(&evidence).map_err(invalid)?, + ) + .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"), + ), + ( + env::NETWORK_RUNTIME_CAPABILITIES.to_string(), + env::POLICY_DNS_TRANSPARENT_TCP_CAPABILITY.to_string(), + ), + ( + 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, + pub tensorlake_sandbox_id: &'a str, + pub identity: &'a ResolvedWorkloadIdentity, + pub gateway_ca_pem: Option<&'a [u8]>, +} + +/// Build the launch bundle tar archive. Paths are relative to `/`. +pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, String> { + let LaunchBundleInput { + sandbox, + config, + tensorlake_sandbox_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 outer_fence = outer_fence(tensorlake_sandbox_id, &generation)?; + let resource_claims = BTreeMap::from([ + ( + "tensorlake.sandbox_id".to_string(), + tensorlake_sandbox_id.to_string(), + ), + ( + "tensorlake.image".to_string(), + identity.resource_digest.clone(), + ), + ]); + let verification_keys = launch_authentication + .verification_keys + .iter() + .map(|key| { + String::from_utf8(key.public_key_pem.clone()) + .map(|public_key_pem| GatewayVerificationKey { + key_id: key.key_id.clone(), + public_key_pem, + }) + .map_err(invalid) + }) + .collect::, _>>()?; + + 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: BoundaryListener::Unix { + socket_path: PathBuf::from(SOCKET_PATH), + tls: SandboxTlsServerConfig { + certificate_chain_path: PathBuf::from(SERVER_CERT_PATH), + private_key_path: PathBuf::from(SERVER_KEY_PATH), + }, + }, + resource_claims: resource_claims.clone(), + resource_claim_files: BTreeMap::new(), + workload_identity: identity.clone(), + outer_fence: outer_fence.clone(), + child_env: child_environment(sandbox), + }; + let runtime_descriptor = SandboxRuntimeDescriptor { + boundary_id: sandbox.id.clone(), + generation, + session_id, + transport: SandboxTransport::Unix { + socket_path: PathBuf::from(SOCKET_PATH), + }, + 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(), + outer_fence, + }; + + let workload = Owner::new(identity.uid, identity.gid); + let guard = Owner::new(SUPERVISOR_UID, SUPERVISOR_GID); + let root = Owner::new(0, 0); + let mut archive = Archive::default(); + archive.directory(".openshell", 0o755, root)?; + 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(), + )?; + + archive.directory(SUPERVISOR_DIR, 0o700, guard)?; + archive.file( + RUNTIME_DESCRIPTOR_PATH, + 0o600, + guard, + &serde_json::to_vec(&runtime_descriptor).map_err(invalid)?, + )?; + archive.file( + AUTH_BUNDLE_PATH, + 0o600, + guard, + &serde_json::to_vec(&launch_authentication.supervisor).map_err(invalid)?, + )?; + if !spec.sandbox_token.is_empty() { + archive.file( + SANDBOX_TOKEN_PATH, + 0o600, + guard, + format!("{}\n", spec.sandbox_token).as_bytes(), + )?; + } + if let Some(ca) = gateway_ca_pem { + archive.file(GATEWAY_CA_PATH, 0o600, guard, ca)?; + } + let environment = supervisor_environment(sandbox, config, gateway_ca_pem.is_some())?; + archive.file( + SUPERVISOR_ENV_PATH, + 0o600, + root, + &nul_list( + environment + .into_iter() + .map(|(key, value)| format!("{key}={value}")), + ), + )?; + archive.file( + SUPERVISOR_ARGS_PATH, + 0o600, + root, + &nul_list(supervisor_args()), + )?; + + archive.directory(".openshell/launch", 0o700, root)?; + let params = format!( + "WORKLOAD_UID={}\nWORKLOAD_GID={}\nSUPERVISOR_UID={SUPERVISOR_UID}\nSUPERVISOR_GID={SUPERVISOR_GID}\nWORKSPACE={WORKSPACE}\nSUPERVISOR_RUN_DIR={SUPERVISOR_RUN_DIR}\n", + identity.uid, identity.gid, + ); + archive.file(LAUNCH_PARAMS_PATH, 0o600, root, params.as_bytes())?; + archive.finish() +} + +#[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 outer_fence_is_complete() { + let fence = outer_fence("tl-1", "gen-1").unwrap(); + assert!(fence.validate("gen-1").is_ok()); + } + + #[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_bundle(LaunchBundleInput { + sandbox: &sandbox, + config: &config, + tensorlake_sandbox_id: "tl-1", + 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, + }, + 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 + } + + #[test] + fn bundle_separates_workload_and_guard_material() { + 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()); + let identity = resolve_identity(&sandbox, "img").unwrap(); + let config = crate::config::tests::test_config(); + let bytes = build_launch_bundle(LaunchBundleInput { + sandbox: &sandbox, + config: &config, + tensorlake_sandbox_id: "tl-1", + identity: &identity, + gateway_ca_pem: Some(b"ca"), + }) + .unwrap(); + let entries = read_entries(&bytes); + + // Workload side: bootstrap and boundary key only, owned by the workload. + let (mode, uid, bootstrap) = &entries[BOOTSTRAP_PATH.trim_start_matches('/')]; + assert_eq!((*mode, *uid), (0o600, 1000)); + let bootstrap = String::from_utf8_lossy(bootstrap); + assert!(bootstrap.contains("\"FOO\"")); + assert!(!bootstrap.contains("gateway.token.value")); + assert!(!bootstrap.contains("sandbox.jwt.value")); + + // Guard side: credentials owned by the guard identity. + for path in [AUTH_BUNDLE_PATH, SANDBOX_TOKEN_PATH, GATEWAY_CA_PATH] { + let (mode, uid, _) = &entries[path.trim_start_matches('/')]; + assert_eq!((*mode, *uid), (0o600, u64::from(SUPERVISOR_UID)), "{path}"); + } + let (mode, uid, _) = &entries[SUPERVISOR_DIR.trim_start_matches('/')]; + assert_eq!((*mode, *uid), (0o700, u64::from(SUPERVISOR_UID))); + + let (_, _, env) = &entries[SUPERVISOR_ENV_PATH.trim_start_matches('/')]; + let env = String::from_utf8_lossy(env); + assert!(env.contains("OPENSHELL_ENDPOINT=https://gateway.example.com:8080\0")); + assert!(env.contains(&format!("OPENSHELL_TLS_CA={GATEWAY_CA_PATH}\0"))); + assert!(env.contains(&format!( + "OPENSHELL_SANDBOX_TOKEN_FILE={SANDBOX_TOKEN_PATH}\0" + ))); + assert!(!env.contains("sandbox.jwt.value")); + + let (_, _, params) = &entries[LAUNCH_PARAMS_PATH.trim_start_matches('/')]; + assert!(String::from_utf8_lossy(params).contains("WORKLOAD_UID=1000\n")); + } + + #[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..77da0d1adc --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/lib.rs @@ -0,0 +1,12 @@ +// 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 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..dad17ed49f --- /dev/null +++ b/crates/openshell-driver-tensorlake/src/main.rs @@ -0,0 +1,157 @@ +// 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_MEMORY_MB}; +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 for the gateway certificate, when it uses a private CA. + #[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, + + #[arg(long, env = "TENSORLAKE_API_KEY", hide_env_values = true)] + tensorlake_api_key: String, + + /// Registered Tensorlake image with the `OpenShell` guard and launcher. + #[arg(long, env = "OPENSHELL_SANDBOX_IMAGE")] + sandbox_image: String, + + #[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 sandbox timeout in seconds. + #[arg(long, env = "OPENSHELL_TENSORLAKE_TIMEOUT_SECS")] + timeout_secs: Option, + + /// 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, +} + +#[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, + 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: 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, + }; + 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"); +} From a130ae1701ac27095551d4321a77a254144b2821 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Fri, 16 Oct 2026 22:56:30 -0500 Subject: [PATCH 02/31] fix(driver-tensorlake): fix status polling and gateway CA checks - Keep sandboxes that are still launching out of poll reconciliation, so a new sandbox is not marked TensorlakeTerminated before it appears in the Tensorlake list. - Keep failed records failed when the Tensorlake VM is still running, so a recovered DriverRestarted sandbox does not go back to Pending. - Require a gateway CA bundle for an https gRPC endpoint, because the guard trusts only that CA, and reject endpoints that are not http or https. - Add the missing ocsf_otlp_headers field to the launch test fixture. Signed-off-by: Shanshan Wang --- .../openshell-driver-tensorlake/src/config.rs | 34 ++++- .../openshell-driver-tensorlake/src/driver.rs | 126 +++++++++++++----- .../openshell-driver-tensorlake/src/launch.rs | 1 + .../openshell-driver-tensorlake/src/main.rs | 2 +- 4 files changed, 126 insertions(+), 37 deletions(-) diff --git a/crates/openshell-driver-tensorlake/src/config.rs b/crates/openshell-driver-tensorlake/src/config.rs index 5b6808342d..190a6bf56f 100644 --- a/crates/openshell-driver-tensorlake/src/config.rs +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -29,8 +29,8 @@ pub struct TensorlakeComputeConfig { pub default_image: String, /// Gateway gRPC endpoint that the guard in each VM dials. pub grpc_endpoint: String, - /// Optional gateway CA bundle (PEM). Required when the gateway uses a - /// private CA. + /// 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, @@ -78,8 +78,23 @@ impl TensorlakeComputeConfig { .into(), ); } - url::Url::parse(&self.grpc_endpoint) + 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}'" + )); + } + } url::Url::parse(&self.api_url) .map_err(|error| format!("invalid Tensorlake API URL: {error}"))?; if self.default_cpus.is_nan() || self.default_cpus <= 0.0 || self.default_memory_mb <= 0 { @@ -155,4 +170,17 @@ pub(crate) mod tests { 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 index 08397155e6..6fb01c5e96 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -669,13 +669,8 @@ impl TensorlakeComputeDriver { } async fn poll_once(&self) -> Result<(), TensorlakeError> { - let observed: HashMap = self - .client - .list_sandboxes() - .await? - .into_iter() - .map(|info| (info.sandbox_id.clone(), info)) - .collect(); + // 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() @@ -683,36 +678,55 @@ impl TensorlakeComputeDriver { .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 phase = info.and_then(observed_phase); - match (&record.phase, phase) { - // Gone from Tensorlake while we delete it: finish the delete. - (Phase::Deleting, None) => self.forget(&sandbox_id).await, - (_, None) => { - let detail = info.map(failure_detail).unwrap_or_default(); - self.set_phase( - &sandbox_id, - Phase::Failed { - reason: "TensorlakeTerminated".into(), - message: format!("Tensorlake sandbox is no longer running{detail}"), - }, - ) - .await; - } - // Keep the current phase while a delete runs, while the - // provisioning task owns launch progress, or after a failed - // launch on a VM that still runs. - (Phase::Deleting, Some(_)) - | (Phase::Pending | Phase::Launching, Some(Phase::Pending | Phase::Running)) - | (Phase::Failed { .. }, Some(Phase::Running)) => {} - (_, Some(next)) => self.set_phase(&sandbox_id, next).await, + match reconcile(&record.phase, observed.get(&record.tensorlake_id)) { + Reconcile::Keep => {} + Reconcile::Forget => self.forget(&sandbox_id).await, + Reconcile::Set(next) => self.set_phase(&sandbox_id, next).await, } } Ok(()) } } +#[derive(Debug, PartialEq, Eq)] +enum Reconcile { + Keep, + Forget, + Set(Phase), +} + +/// Decide how one poll observation changes a record. +fn reconcile(current: &Phase, info: Option<&SandboxInfo>) -> Reconcile { + match (current, info.and_then(observed_phase)) { + // Gone from Tensorlake while we delete it: finish the delete. + (Phase::Deleting, None) => Reconcile::Forget, + // The provisioning task owns launch progress and reports its own + // failures. + (Phase::Pending | Phase::Launching, _) + // Keep the current phase while a delete runs. + | (Phase::Deleting, Some(_)) + // A failed launch stays failed while the VM still exists. Nothing + // will launch it again. + | (Phase::Failed { .. }, Some(Phase::Pending | Phase::Running)) => Reconcile::Keep, + (_, None) => Reconcile::Set(Phase::Failed { + reason: "TensorlakeTerminated".into(), + message: format!( + "Tensorlake sandbox is no longer running{}", + info.map(failure_detail).unwrap_or_default() + ), + }), + (_, Some(next)) => Reconcile::Set(next), + } +} + /// Map Tensorlake status to a phase. `None` means the VM is gone. fn observed_phase(info: &SandboxInfo) -> Option { match info.status.as_str() { @@ -867,9 +881,8 @@ mod tests { assert_eq!(failed.reason, "LaunchFailed"); } - #[test] - fn observed_phase_treats_terminal_states_as_gone() { - let info = |status: &str| SandboxInfo { + fn info(status: &str) -> SandboxInfo { + SandboxInfo { sandbox_id: "x".into(), status: status.into(), name: None, @@ -878,7 +891,54 @@ mod tests { 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), Reconcile::Keep); + assert_eq!(reconcile(&Phase::Launching, None), Reconcile::Keep); + assert_eq!( + reconcile(&Phase::Pending, Some(&info("running"))), + Reconcile::Keep + ); + } + + #[test] + fn reconcile_keeps_failed_launch_failed() { + let failed = Phase::Failed { + reason: "DriverRestarted".into(), + message: "m".into(), }; + for status in ["pending", "running"] { + assert_eq!(reconcile(&failed, Some(&info(status))), Reconcile::Keep); + } + } + + #[test] + fn reconcile_tracks_running_sandboxes() { + assert_eq!(reconcile(&Phase::Deleting, None), Reconcile::Forget); + assert_eq!( + reconcile(&Phase::Deleting, Some(&info("running"))), + Reconcile::Keep + ); + assert_eq!( + reconcile(&Phase::Running, Some(&info("suspended"))), + Reconcile::Set(Phase::Suspended) + ); + assert_eq!( + reconcile(&Phase::Suspended, Some(&info("running"))), + Reconcile::Set(Phase::Running) + ); + assert!(matches!( + reconcile(&Phase::Running, Some(&info("terminated"))), + Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" + )); + } + + #[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::Suspended)); for status in ["terminated", "failed", "timeout"] { diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs index a345f47d5a..14e75786ae 100644 --- a/crates/openshell-driver-tensorlake/src/launch.rs +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -598,6 +598,7 @@ mod tests { 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 { diff --git a/crates/openshell-driver-tensorlake/src/main.rs b/crates/openshell-driver-tensorlake/src/main.rs index dad17ed49f..3baf47e5bd 100644 --- a/crates/openshell-driver-tensorlake/src/main.rs +++ b/crates/openshell-driver-tensorlake/src/main.rs @@ -46,7 +46,7 @@ struct Args { #[arg(long, env = "OPENSHELL_GRPC_ENDPOINT")] grpc_endpoint: String, - /// PEM CA bundle for the gateway certificate, when it uses a private CA. + /// PEM CA bundle that guards trust for the gateway. Required for https. #[arg(long, env = "OPENSHELL_TENSORLAKE_GATEWAY_TLS_CA")] gateway_tls_ca: Option, From 0d9e781c0d808abbd643013874cdf08f69b5b7c4 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Fri, 16 Oct 2026 22:56:30 -0500 Subject: [PATCH 03/31] feat(driver-tensorlake): run the control plane in a Tensorlake sandbox - Add a control image with the gateway and the Tensorlake driver, a start script that runs both in one long-lived sandbox, and deploy.sh to create and start it. Guards reach the gateway through the Tensorlake port proxy. - Add build-images.sh to build the sandbox and control images on Tensorlake without local Docker. PUBLIC=1 publishes both images for all Tensorlake projects from a clean checkout, with the version in the image name. - The control image records its paired sandbox image and source commit. - Pin upstream OpenShell images to the base commit, because Tensorlake builds do not expand variables in FROM, and use a build context that contains the launcher script. - Document the control-plane setup, user authentication, and publishing. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 115 ++++++++++++++- .../build-images.sh | 82 +++++++++++ .../control/Dockerfile | 41 ++++++ .../control/deploy.sh | 88 +++++++++++ .../control/openshell-control-start.sh | 138 ++++++++++++++++++ .../image/Dockerfile | 26 ++-- 6 files changed, 470 insertions(+), 20 deletions(-) create mode 100755 crates/openshell-driver-tensorlake/build-images.sh create mode 100644 crates/openshell-driver-tensorlake/control/Dockerfile create mode 100755 crates/openshell-driver-tensorlake/control/deploy.sh create mode 100755 crates/openshell-driver-tensorlake/control/openshell-control-start.sh diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 54f9ed39bc..94230e8a41 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -55,15 +55,49 @@ recipe. It cannot inspect the VM to confirm them. Tensorlake `allow_out` is an optional second wall for the guard's own egress. -## Build the image +## Build the images + +`build-images.sh` builds two images on Tensorlake. A Tensorlake builder +sandbox runs each build, so local Docker is not needed. + +| Image | Default name | Contents | +|---|---|---| +| Sandbox | `openshell-tensorlake` | guard, workload runtime, launcher | +| Control | `openshell-control` | gateway, this driver, start script | ```shell -docker build -f crates/openshell-driver-tensorlake/image/Dockerfile \ - --build-arg OPENSHELL_TAG= -t openshell-tensorlake . +crates/openshell-driver-tensorlake/build-images.sh ``` -Register the image with Tensorlake (`tl sbx image create`). The image must -not contain `/.openshell`. Derive from it to add agent tools. +The control image records the sandbox image name. The driver uses that +sandbox image unless `OPENSHELL_SANDBOX_IMAGE` is set, 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 context. Tensorlake uses the Dockerfile +directory as the context, and 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. + +The sandbox image must not contain `/.openshell`. Derive from it to add agent +tools. + +### Publish for all Tensorlake users + +Build from a clean checkout, in the project that owns the public images: + +```shell +PUBLIC=1 VERSION=0-1-5 crates/openshell-driver-tensorlake/build-images.sh +``` + +This registers `openshell-tensorlake-0-1-5` and `openshell-control-0-1-5` +with `--public`. Any Tensorlake project can then use them without a build. +Public names must be unique across Tensorlake, and Tensorlake has no image +tags, so put the version in the name. Do not replace a published version; +publish a new one. + +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. ## Run @@ -76,6 +110,7 @@ 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 @@ -87,7 +122,7 @@ openshell-gateway --compute-driver tensorlake \ |---|---|---| | `--bind-socket` | `OPENSHELL_COMPUTE_DRIVER_SOCKET` | required | | `--grpc-endpoint` | `OPENSHELL_GRPC_ENDPOINT` | required | -| `--gateway-tls-ca` | `OPENSHELL_TENSORLAKE_GATEWAY_TLS_CA` | none | +| `--gateway-tls-ca` | `OPENSHELL_TENSORLAKE_GATEWAY_TLS_CA` | required for an `https` endpoint | | `--tensorlake-api-url` | `TENSORLAKE_API_URL` | `https://sandbox.tensorlake.ai` | | `--tensorlake-api-key` | `TENSORLAKE_API_KEY` | required | | `--sandbox-image` | `OPENSHELL_SANDBOX_IMAGE` | required | @@ -96,9 +131,73 @@ openshell-gateway --compute-driver tensorlake \ | `--allow-out` | `OPENSHELL_TENSORLAKE_ALLOW_OUT` | empty (internet on) | | `--poll-interval-secs` | `OPENSHELL_TENSORLAKE_POLL_INTERVAL_SECS` | 3 | +The guard trusts only the `--gateway-tls-ca` bundle, not public roots. For a +gateway with a public certificate, pass the root CA that signed it. + When `--allow-out` is set, the driver turns off Tensorlake internet access and adds the gateway host to the list. +## Run the control plane on Tensorlake + +`control/` runs the gateway and this driver together in one long-lived +Tensorlake sandbox. + +``` + your machine Tensorlake +┌──────────────┐ tl tunnel ┌───────────────────────────────────┐ +│ openshell CLI│ ────────────► │ control sandbox │ +└──────────────┘ │ gateway :8080 (plaintext HTTP/2) │ + │ ▲ UDS │ + │ driver ──► Tensorlake API │ + └────▲──────────────────────────────┘ + │ https://8080-.sandbox.tensorlake.ai + guards in sandbox VMs (public port, TLS at proxy) +``` + +The Tensorlake port proxy terminates TLS. Guards trust the public CA bundle +of the control image for that certificate. + +1. Build the images (see [Build the images](#build-the-images)), or use + published ones. + +2. Create the sandbox and start the control plane: + + ```shell + export TENSORLAKE_API_KEY=... + export OPENSHELL_OIDC_ISSUER=https://issuer.example.com + export CONTROL_IMAGE=openshell-control-0-1-5 # or your own build + crates/openshell-driver-tensorlake/control/deploy.sh + ``` + + The script stores settings in `/etc/openshell-control/control.env` (mode + 0600) and starts a managed process with `--restart always`. Run it again + to change settings. Gateway state stays in `/var/lib/openshell`. Set + `OPENSHELL_DB_URL` to use an external database. + +3. Connect the CLI. With OIDC, use the public URL: + + ```shell + openshell gateway add https://8080-openshell-control.sandbox.tensorlake.ai \ + --oidc-issuer https://issuer.example.com + ``` + + Without OIDC, use a Tensorlake tunnel: + + ```shell + tl sbx tunnel openshell-control 8080 --listen-port 18080 + openshell gateway add http://127.0.0.1:18080 --name tensorlake + ``` + +Guards cannot hold a Tensorlake key, so port 8080 accepts anonymous +requests. The gateway must authenticate users itself. The start script +refuses to run without `OPENSHELL_OIDC_ISSUER`, unless you set +`OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1`. With that setting, anyone with +the URL controls the gateway. Use it only for a short test with +non-production credentials. + +The control sandbox holds the Tensorlake API key. Do not run other workloads +in it. + ## Limits - Stop and start return `Unimplemented`. Delete the sandbox instead. @@ -117,4 +216,6 @@ end-to-end run on Tensorlake still needs to confirm that: - the guest kernel enables Landlock and seccomp, and allows `unshare --net`; - the file API writes as root, and the process API runs the launcher as root; -- the guard can reach the gateway over a long-lived gRPC connection. +- the guard can reach the gateway over a long-lived gRPC connection; +- the port proxy sends gRPC to a plaintext HTTP/2 backend, and keeps + long-lived streams open. diff --git a/crates/openshell-driver-tensorlake/build-images.sh b/crates/openshell-driver-tensorlake/build-images.sh new file mode 100755 index 0000000000..23f6c5eb91 --- /dev/null +++ b/crates/openshell-driver-tensorlake/build-images.sh @@ -0,0 +1,82 @@ +#!/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. A Tensorlake builder sandbox runs each build, so no local +# Docker is needed. +# +# The control image records the sandbox image name, so the two images always +# work as a pair. +# +# Optional: +# VERSION added to both names as `-` (for example 0-1-5) +# SANDBOX_IMAGE sandbox image name (default: openshell-tensorlake) +# CONTROL_IMAGE control image name (default: openshell-control) +# PUBLIC=1 publish both images to all Tensorlake projects. The +# checkout must be clean, so the images match a commit. + +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "${HERE}/../.." && pwd)" +SUFFIX="${VERSION:+-${VERSION}}" +SANDBOX_IMAGE="${SANDBOX_IMAGE:-openshell-tensorlake}${SUFFIX}" +CONTROL_IMAGE="${CONTROL_IMAGE:-openshell-control}${SUFFIX}" +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 + +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}" \ + --docker_compat ${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}" \ + --docker_compat --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 tl sbx describe "${NAME}" >/dev/null 2>&1; then + echo "==> Using existing sandbox ${NAME}" + tl sbx kill "${NAME}" "${PROCESS}" >/dev/null 2>&1 || true +else + echo "==> Creating sandbox ${NAME} from image ${IMAGE}" + tl sbx create "${NAME}" --image "${IMAGE}" --cpus 2 --memory 4096 +fi + +# Guards in other sandboxes dial this port without a Tensorlake key. +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}" & +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/image/Dockerfile b/crates/openshell-driver-tensorlake/image/Dockerfile index 84def73cba..5988c5f10b 100644 --- a/crates/openshell-driver-tensorlake/image/Dockerfile +++ b/crates/openshell-driver-tensorlake/image/Dockerfile @@ -7,18 +7,17 @@ # (openshell-sandbox), and the launcher to an Ubuntu base. Add agent tools # (for example Claude Code) in a derived image. # -# Build from the repository root: -# docker build -f crates/openshell-driver-tensorlake/image/Dockerfile \ -# --build-arg OPENSHELL_TAG= -t openshell-tensorlake . -# Then register the image with Tensorlake (`tl sbx image create`). - -ARG OPENSHELL_TAG=latest -ARG BASE_IMAGE=ubuntu:24.04 +# 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:${OPENSHELL_TAG} AS supervisor -FROM ghcr.io/nvidia/openshell/sandbox:${OPENSHELL_TAG} AS sandbox +FROM ghcr.io/nvidia/openshell/supervisor:a4c848adbddd0b4732fd70ddcf8a563a5b1e9317 AS supervisor +FROM ghcr.io/nvidia/openshell/sandbox:a4c848adbddd0b4732fd70ddcf8a563a5b1e9317 AS sandbox -FROM ${BASE_IMAGE} +FROM ubuntu:24.04 # iproute2: loopback in the workload network namespace. # util-linux: unshare and setpriv. ca-certificates: guard TLS to upstreams. @@ -33,9 +32,10 @@ RUN if ! getent group 1000 >/dev/null; then groupadd --gid 1000 sandbox; fi \ fi \ && install -d -m 0755 /sandbox /var/lib/openshell -COPY --from=supervisor --chmod=0555 /openshell-supervisor /opt/openshell/bin/openshell-supervisor -COPY --from=sandbox --chmod=0555 /openshell-sandbox /opt/openshell/bin/openshell-sandbox -COPY --chmod=0555 crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh \ +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 From 16bb35bff23f4f34cc20c8fb24cf0f57b5673093 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 10:18:04 -0500 Subject: [PATCH 04/31] fix(driver-tensorlake): require launch authentication only at create The gateway calls ValidateSandboxCreate before it mints launch authentication, so the driver rejected every sandbox create. Check for launch authentication in CreateSandbox only, as the Docker driver does. Signed-off-by: Shanshan Wang --- .../openshell-driver-tensorlake/src/driver.rs | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs index 6fb01c5e96..b0ca19c8b6 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -356,11 +356,6 @@ impl TensorlakeComputeDriver { "the Tensorlake driver does not support GPU sandboxes yet", )); } - if spec.launch_authentication.is_empty() { - return Err(Status::failed_precondition( - "Tensorlake sandboxes require launch-scoped gateway authentication", - )); - } let resources = self .resources_for(sandbox) .map_err(Status::invalid_argument)?; @@ -371,6 +366,17 @@ impl TensorlakeComputeDriver { 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")); } @@ -822,8 +828,8 @@ mod tests { assert_eq!(resources.memory_mb, crate::config::DEFAULT_MEMORY_MB); } - #[test] - fn validate_rejects_unsupported_requests() { + #[tokio::test] + async fn only_create_requires_launch_authentication() { let driver = driver(); let mut missing_auth = sandbox(DriverSandboxTemplate::default()); missing_auth @@ -832,8 +838,14 @@ mod tests { .unwrap() .launch_authentication .clear(); - assert!(driver.validate_sandbox_create(&missing_auth).is_err()); + 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() From cb2751309409820f806be33fae54299455ce821c Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 10:18:18 -0500 Subject: [PATCH 05/31] fix(driver-tensorlake): use the plan maximum idle timeout Tensorlake suspends a sandbox after its idle timeout (600 seconds by default), and only incoming traffic resets the timer. Guard traffic to the gateway is outgoing, so working sandboxes were suspended after 10 minutes. - Default the driver timeout to 0, which uses the plan maximum. - Create the control-plane sandbox with --timeout 0. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/control/deploy.sh | 8 ++++++-- crates/openshell-driver-tensorlake/src/config.rs | 3 ++- crates/openshell-driver-tensorlake/src/main.rs | 10 ++++++---- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/crates/openshell-driver-tensorlake/control/deploy.sh b/crates/openshell-driver-tensorlake/control/deploy.sh index 2e22cc8dfd..6c6060d59a 100755 --- a/crates/openshell-driver-tensorlake/control/deploy.sh +++ b/crates/openshell-driver-tensorlake/control/deploy.sh @@ -13,6 +13,7 @@ # Optional: # CONTROL_NAME sandbox name (default: openshell-control) # CONTROL_IMAGE registered control-plane image (default: openshell-control) +# CONTROL_TIMEOUT_SECS Tensorlake idle timeout (default: 0, the plan maximum) # OPENSHELL_SANDBOX_IMAGE sandbox image (default: the one built with CONTROL_IMAGE) # OPENSHELL_OIDC_ISSUER, OPENSHELL_OIDC_AUDIENCE, ... # gateway OIDC settings for user authentication @@ -35,11 +36,14 @@ REMOTE_ENV=/etc/openshell-control/control.env command -v tl >/dev/null || { echo "error: the tl CLI is not installed" >&2; exit 1; } if tl sbx describe "${NAME}" >/dev/null 2>&1; then - echo "==> Using existing sandbox ${NAME}" + echo "==> Using existing sandbox ${NAME}. To use a new image, terminate it first." tl sbx kill "${NAME}" "${PROCESS}" >/dev/null 2>&1 || true else echo "==> Creating sandbox ${NAME} from image ${IMAGE}" - tl sbx create "${NAME}" --image "${IMAGE}" --cpus 2 --memory 4096 + # 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. diff --git a/crates/openshell-driver-tensorlake/src/config.rs b/crates/openshell-driver-tensorlake/src/config.rs index 190a6bf56f..45f018c5b2 100644 --- a/crates/openshell-driver-tensorlake/src/config.rs +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -35,7 +35,8 @@ pub struct TensorlakeComputeConfig { pub default_cpus: f64, pub default_memory_mb: i64, pub default_disk_mb: Option, - /// Tensorlake sandbox timeout. `None` uses the Tensorlake default. + /// 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. diff --git a/crates/openshell-driver-tensorlake/src/main.rs b/crates/openshell-driver-tensorlake/src/main.rs index 3baf47e5bd..845e8d9358 100644 --- a/crates/openshell-driver-tensorlake/src/main.rs +++ b/crates/openshell-driver-tensorlake/src/main.rs @@ -69,9 +69,11 @@ struct Args { #[arg(long, env = "OPENSHELL_TENSORLAKE_DISK_MB")] disk_mb: Option, - /// Tensorlake sandbox timeout in seconds. - #[arg(long, env = "OPENSHELL_TENSORLAKE_TIMEOUT_SECS")] - timeout_secs: 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 @@ -109,7 +111,7 @@ async fn main() -> Result<()> { default_cpus: args.cpus, default_memory_mb: args.memory_mb, default_disk_mb: args.disk_mb, - timeout_secs: args.timeout_secs, + timeout_secs: Some(args.timeout_secs), allow_out: args .allow_out .into_iter() From 92e0e8b66a2f43054007b2759402618084b77ac4 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 10:18:18 -0500 Subject: [PATCH 06/31] build(driver-tensorlake): build CAS images and keep explicit image names - Build the sandbox and control images as CAS images (--cas). - Apply VERSION only to the default image names. Names set in SANDBOX_IMAGE or CONTROL_IMAGE are used as they are, so an exported CONTROL_IMAGE no longer gets a second version suffix. - Document CAS, the idle timeout, and the checks still to run on the CAS dataplane. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 17 ++++++++++++---- .../build-images.sh | 20 ++++++++++--------- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 94230e8a41..1c17411709 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -57,8 +57,9 @@ Tensorlake `allow_out` is an optional second wall for the guard's own egress. ## Build the images -`build-images.sh` builds two images on Tensorlake. A Tensorlake builder -sandbox runs each build, so local Docker is not needed. +`build-images.sh` builds two CAS images on Tensorlake (`--cas`). Tensorlake +runs each build, so local Docker is not needed. CAS images start fast and +run on the Tensorlake CAS dataplane. | Image | Default name | Contents | |---|---|---| @@ -127,13 +128,17 @@ openshell-gateway --compute-driver tensorlake \ | `--tensorlake-api-key` | `TENSORLAKE_API_KEY` | required | | `--sandbox-image` | `OPENSHELL_SANDBOX_IMAGE` | required | | `--cpus` / `--memory-mb` / `--disk-mb` | `OPENSHELL_TENSORLAKE_*` | 2 / 4096 / Tensorlake default | -| `--timeout-secs` | `OPENSHELL_TENSORLAKE_TIMEOUT_SECS` | Tensorlake default | +| `--timeout-secs` | `OPENSHELL_TENSORLAKE_TIMEOUT_SECS` | 0 (plan maximum) | | `--allow-out` | `OPENSHELL_TENSORLAKE_ALLOW_OUT` | empty (internet on) | | `--poll-interval-secs` | `OPENSHELL_TENSORLAKE_POLL_INTERVAL_SECS` | 3 | The guard trusts only the `--gateway-tls-ca` bundle, not public roots. For a gateway with a public certificate, pass the root CA that signed it. +The Tensorlake timeout counts idle time, and only incoming traffic resets +it. Guard traffic to the gateway is outgoing, so a short timeout suspends a +working sandbox. Keep the default `0`, which uses the plan maximum. + When `--allow-out` is set, the driver turns off Tensorlake internet access and adds the gateway host to the list. @@ -218,4 +223,8 @@ end-to-end run on Tensorlake still needs to confirm that: - the file API writes as root, and the process API runs the launcher as root; - the guard can reach the gateway over a long-lived gRPC connection; - the port proxy sends gRPC to a plaintext HTTP/2 backend, and keeps - long-lived streams open. + long-lived streams open; +- CAS builds accept the multi-stage Dockerfiles and `--public`; +- the CAS dataplane enables Landlock, seccomp, and `unshare --net`, and + supports the file and process APIs, exposed ports, and long-lived managed + processes. diff --git a/crates/openshell-driver-tensorlake/build-images.sh b/crates/openshell-driver-tensorlake/build-images.sh index 23f6c5eb91..2e63cb643f 100755 --- a/crates/openshell-driver-tensorlake/build-images.sh +++ b/crates/openshell-driver-tensorlake/build-images.sh @@ -3,16 +3,16 @@ # SPDX-License-Identifier: Apache-2.0 # Build and register the sandbox image and the control-plane image on -# Tensorlake. A Tensorlake builder sandbox runs each build, so no local -# Docker is needed. +# 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: -# VERSION added to both names as `-` (for example 0-1-5) -# SANDBOX_IMAGE sandbox image name (default: openshell-tensorlake) -# CONTROL_IMAGE control image name (default: openshell-control) +# VERSION added to the default names as `-` (for example 0-1-5) +# SANDBOX_IMAGE full sandbox image name (default: openshell-tensorlake[-VERSION]) +# CONTROL_IMAGE full control image name (default: openshell-control[-VERSION]) # PUBLIC=1 publish both images to all Tensorlake projects. The # checkout must be clean, so the images match a commit. @@ -20,9 +20,11 @@ set -euo pipefail HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$(cd "${HERE}/../.." && pwd)" +# 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}" +SANDBOX_IMAGE="${SANDBOX_IMAGE:-openshell-tensorlake${SUFFIX}}" +CONTROL_IMAGE="${CONTROL_IMAGE:-openshell-control${SUFFIX}}" 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; } @@ -62,12 +64,12 @@ printf '%s\n' "${COMMIT}" >"${CONTEXT}/share/source-commit" echo "==> Building sandbox image ${SANDBOX_IMAGE}" tl sbx image create "${HERE}/image/Dockerfile" \ --registered-name "${SANDBOX_IMAGE}" \ - --docker_compat ${PUBLIC_FLAG[@]+"${PUBLIC_FLAG[@]}"} + --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}" \ - --docker_compat --cpus 8 --memory 16384 --builder_disk_mb 40960 \ + --cas --cpus 8 --memory 16384 --builder_disk_mb 40960 \ ${PUBLIC_FLAG[@]+"${PUBLIC_FLAG[@]}"} cat < Date: Mon, 19 Oct 2026 10:18:18 -0500 Subject: [PATCH 07/31] docs(driver-tensorlake): add control-plane authentication design Propose mTLS user authentication through Tensorlake tunnels, with guards reaching the gateway through a local gRPC proxy behind the public port. This removes the need for unauthenticated users without an identity provider. Signed-off-by: Shanshan Wang --- .../docs/control-plane-auth.md | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 crates/openshell-driver-tensorlake/docs/control-plane-auth.md diff --git a/crates/openshell-driver-tensorlake/docs/control-plane-auth.md b/crates/openshell-driver-tensorlake/docs/control-plane-auth.md new file mode 100644 index 0000000000..245ded7044 --- /dev/null +++ b/crates/openshell-driver-tensorlake/docs/control-plane-auth.md @@ -0,0 +1,117 @@ +# Control-plane authentication on Tensorlake + +Status: proposed. The current `control/` setup uses OIDC, or no user +authentication for tests. + +## Problem + +The control plane (gateway and driver) runs in a Tensorlake sandbox. Guards +in other sandboxes reach the gateway through the Tensorlake port proxy: + +``` +https://8080-.sandbox.tensorlake.ai +``` + +Guards cannot hold a Tensorlake key, so this port must accept anonymous +requests at the proxy. The gateway must then authenticate users itself. + +Today there are two choices: + +- OIDC: safe, but needs an identity provider. +- `OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1`: anyone with the URL controls + the gateway. Test only. + +We need a production setup without an identity provider. + +## Facts from the code + +1. **Guard calls reject anonymous callers.** A guard calls 17 gateway + methods. 14 accept only a sandbox principal (sandbox JWT). 3 are dual + (`GetSandboxConfig`, `UpdateConfig`, `GetDraftPolicy`) and also accept a + user. With `allow_unauthenticated_users = false` and a configured + authenticator, a caller without credentials gets `Unauthenticated` on + all of them (`crates/openshell-server/src/multiplex.rs`, `AuthGrpcRouter`). +2. **Client certificates are optional at the TLS handshake.** With a client + CA, the gateway accepts connections without a certificate + (`allow_unauthenticated()` in `crates/openshell-server/src/tls.rs`). A + verified certificate becomes a user only when `mtls_auth.enabled` is set. + So one TLS port serves mTLS users and guards with sandbox JWTs. +3. **A Tensorlake tunnel is raw TCP to `127.0.0.1:`** in the sandbox, + and every connection needs a Tensorlake credential. The port does not + need to be exposed. TLS stays end to end, so the client certificate + reaches the gateway. +4. The gateway has one gRPC listener and no per-listener auth settings. + +## Design + +``` + CONTROL SANDBOX + ┌────────────────────────────────────────────┐ + guards ── HTTPS ──► │ :8080 (exposed) local gRPC proxy │ + (sandbox JWT) │ re-encrypts ─────────┐ │ + │ ▼ │ + users ── tl tunnel ───────────────────► 127.0.0.1:8443 gateway │ + (Tensorlake key + │ TLS, mTLS users on, │ + client cert) │ anonymous users off │ + └────────────────────────────────────────────┘ +``` + +| Caller | Path | Checks | +|---|---|---| +| Guard | port proxy → local proxy → gateway | sandbox JWT | +| User (CLI) | `tl sbx tunnel 8443` → gateway | Tensorlake credential (tunnel), then client certificate (mTLS) | +| Anyone else | port proxy → local proxy → gateway | no credential, so `Unauthenticated` | + +### Components + +- **Gateway**: binds `127.0.0.1:8443` with TLS. Settings: + `mtls_auth.enabled = true`, `allow_unauthenticated_users = false`, sandbox + JWT signing as today. Server certificate SANs include `127.0.0.1` and + `localhost`, for the tunnel. +- **Local gRPC proxy** (nginx `grpc_pass grpcs://127.0.0.1:8443`): listens on + `:8080` with plaintext HTTP/2 behind the Tensorlake port proxy. It + forwards all gRPC to the gateway over TLS, without a client certificate. + Long timeouts keep supervisor streams open. +- **Certificates**: `openshell-gateway generate-certs` creates the CA, the + server certificate, and a client certificate on first start. The user + downloads the client bundle once with `tl sbx cp`. Treat it as a secret. +- **Driver**: no change. `--grpc-endpoint` stays the public URL, and + `--gateway-tls-ca` stays the public CA bundle, because guards still go + through the Tensorlake port proxy. + +### User setup + +```shell +tl sbx cp openshell-control:/var/lib/openshell/keys/client/ ~/.config/openshell/... +tl sbx tunnel openshell-control 8443 --listen-port 18443 +openshell gateway add https://127.0.0.1:18443 --local --name tensorlake +``` + +The exact CLI registration and certificate paths need confirmation during +implementation. + +## Security notes + +- Two checks for users: Tensorlake project access and the client + certificate. +- Anyone with Tensorlake project access can already run + `tl sbx exec --user root` in the control sandbox and read its keys. The + client certificate does not protect against project members. Use a + separate Tensorlake project for the control plane. +- The public port exposes only what a sandbox JWT can call. The 3 dual + methods still need a user or sandbox principal. +- Health endpoints stay unauthenticated, as today. + +## Later: OIDC with Tensorlake identity + +If the Tensorlake login system is an OIDC provider, the gateway can trust +Tensorlake accounts directly (`OPENSHELL_OIDC_ISSUER`). Users then log in +with their Tensorlake identity, and no client certificate is needed. This +needs Tensorlake-side setup. + +## Open questions + +- Does the Tensorlake port proxy keep long-lived gRPC streams open? +- Does `openshell gateway add` support a tunneled mTLS endpoint without an + SSH remote? If not, which registration fits best? +- nginx or another small proxy (for example Envoy) in the control image? From 6e83445a95d62071b49deb64dba6e66f8a3e84a3 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 14:43:35 -0500 Subject: [PATCH 08/31] fix(driver-tensorlake): report launcher failures instead of hanging The driver reported a sandbox as running once the launcher started and never checked it again. When the launcher exited, the guard never connected and sandbox create waited until the gateway timed out. - Keep the launcher PID and check it on each status poll. A stopped launcher marks the sandbox failed (LauncherExited) with its exit status and the tl sbx logs command to run. - Stop sending the undocumented process name. With it, Tensorlake treated the launcher as a managed process and restarted it, and each restart failed because the launch bundle is deleted after the first run. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 3 + .../openshell-driver-tensorlake/src/client.rs | 75 ++++++++++++++++- .../openshell-driver-tensorlake/src/driver.rs | 81 +++++++++++++++++-- .../openshell-driver-tensorlake/src/launch.rs | 3 - 4 files changed, 150 insertions(+), 12 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 1c17411709..598971d32c 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -33,6 +33,9 @@ openshell CLI ──► gateway ──UDS──► openshell-driver-tensorlake a loopback-only network namespace, and starts the guard as uid 65534. 5. The driver reports `Ready=True` when the launcher starts. The gateway marks the sandbox ready when the guard session connects. +6. Each poll checks the launcher process. If it stopped, the driver marks the + sandbox failed (`LauncherExited`) with its exit status. Tensorlake does + not restart the launcher. A poll loop reads `GET /sandboxes` because Tensorlake has no watch API. diff --git a/crates/openshell-driver-tensorlake/src/client.rs b/crates/openshell-driver-tensorlake/src/client.rs index 4348186a13..0006350455 100644 --- a/crates/openshell-driver-tensorlake/src/client.rs +++ b/crates/openshell-driver-tensorlake/src/client.rs @@ -99,10 +99,37 @@ pub struct StartProcessRequest { #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub env: BTreeMap, pub user: String, - pub name: 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, @@ -196,12 +223,29 @@ impl TensorlakeClient { &self, sandbox: &SandboxInfo, request: &StartProcessRequest, - ) -> Result<(), TensorlakeError> { + ) -> Result { let request = self .proxy_request(sandbox, reqwest::Method::POST, "/api/v1/processes")? .json(request); - check(request.send().await?).await?; - Ok(()) + 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( @@ -304,6 +348,29 @@ mod tests { ); } + #[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 = diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs index b0ca19c8b6..9612e52a84 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -27,7 +27,7 @@ use tonic::Status; use tracing::{info, warn}; use crate::client::{ - CreateSandboxRequest, NetworkPolicy, Resources, SandboxInfo, StartProcessRequest, + CreateSandboxRequest, NetworkPolicy, ProcessInfo, Resources, SandboxInfo, StartProcessRequest, TensorlakeClient, TensorlakeError, }; use crate::config::TensorlakeComputeConfig; @@ -64,6 +64,8 @@ struct Record { tensorlake_name: String, identity: Option, phase: Phase, + /// PID of the launcher in the VM. `None` for recovered records. + launcher_pid: Option, } impl Record { @@ -424,6 +426,7 @@ impl TensorlakeComputeDriver { tensorlake_name: name, identity: Some(identity.clone()), phase: Phase::Pending, + launcher_pid: None, }; self.records .lock() @@ -498,7 +501,8 @@ impl TensorlakeComputeDriver { .write_file(&info, launch::BUNDLE_UPLOAD_PATH, bundle) .await .map_err(|error| format!("upload launch bundle: {error}"))?; - self.client + let launcher = self + .client .start_process( &info, &StartProcessRequest { @@ -506,13 +510,19 @@ impl TensorlakeComputeDriver { args: vec![launch::BUNDLE_UPLOAD_PATH.to_string()], env: std::collections::BTreeMap::new(), user: "root".to_string(), - name: launch::LAUNCHER_PROCESS_NAME.to_string(), stdin_mode: "closed", }, ) .await .map_err(|error| format!("start OpenShell launcher: {error}"))?; - info!(sandbox_id = %sandbox.id, "Started OpenShell launcher in Tensorlake sandbox"); + info!( + sandbox_id = %sandbox.id, + launcher_pid = launcher.pid, + "Started OpenShell launcher in Tensorlake sandbox" + ); + if let Some(record) = self.records.lock().await.get_mut(&sandbox.id) { + record.launcher_pid = Some(launcher.pid); + } self.set_phase(&sandbox.id, Phase::Running).await; Ok(()) } @@ -658,6 +668,7 @@ impl TensorlakeComputeDriver { tensorlake_name: info.name.clone().unwrap_or_default(), identity: None, phase, + launcher_pid: None, }, ); } @@ -692,14 +703,35 @@ impl TensorlakeComputeDriver { .map(|info| (info.sandbox_id.clone(), info)) .collect(); for (sandbox_id, record) in records { - match reconcile(&record.phase, observed.get(&record.tensorlake_id)) { + let info = observed.get(&record.tensorlake_id); + match reconcile(&record.phase, info) { Reconcile::Keep => {} Reconcile::Forget => self.forget(&sandbox_id).await, Reconcile::Set(next) => self.set_phase(&sandbox_id, next).await, } + if let (Some(info), Some(pid)) = (info, record.launcher_pid) + && record.phase == Phase::Running + && observed_phase(info) == Some(Phase::Running) + { + self.check_launcher(&sandbox_id, info, pid).await; + } } Ok(()) } + + /// Mark the sandbox failed when its 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) { + match self.client.get_process(info, pid).await { + Ok(process) => { + if let Some(failed) = launcher_failure(&info.sandbox_id, process.as_ref()) { + warn!(%sandbox_id, ?failed, "OpenShell launcher stopped"); + self.set_phase(sandbox_id, failed).await; + } + } + Err(error) => warn!(%sandbox_id, %error, "Tensorlake launcher status check failed"), + } + } } #[derive(Debug, PartialEq, Eq)] @@ -733,6 +765,21 @@ fn reconcile(current: &Phase, info: Option<&SandboxInfo>) -> Reconcile { } } +/// The failed phase for a launcher that is no longer running. +fn launcher_failure(tensorlake_id: &str, process: Option<&ProcessInfo>) -> 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 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() { @@ -949,6 +996,30 @@ mod tests { )); } + 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))), + None + ); + let Some(Phase::Failed { reason, message }) = + launcher_failure("tl1", Some(&process("exited", Some(1)))) + else { + panic!("an exited launcher must fail the sandbox"); + }; + assert_eq!(reason, "LauncherExited"); + assert!(message.contains("exited with status 1")); + assert!(message.contains("tl sbx logs tl1")); + assert!(launcher_failure("tl1", None).is_some()); + } + #[test] fn observed_phase_treats_terminal_states_as_gone() { assert_eq!(observed_phase(&info("running")), Some(Phase::Running)); diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs index 14e75786ae..aae704d34c 100644 --- a/crates/openshell-driver-tensorlake/src/launch.rs +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -37,9 +37,6 @@ use crate::config::TensorlakeComputeConfig; 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"; -/// Tensorlake process name for the launcher. -pub const LAUNCHER_PROCESS_NAME: &str = "openshell-launch"; - /// 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; From c1cc2b2f4b6fb26949fd217ff61957207a7fd78e Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 14:43:36 -0500 Subject: [PATCH 09/31] fix(driver-tensorlake): use the sandbox ID in the guards' gateway URL The Tensorlake port proxy resolves sandbox names only for authenticated requests. Guards call the gateway anonymously, so a name-based URL returned SANDBOX_NOT_FOUND. deploy.sh now reads the control sandbox ID and builds the public URL from it. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 7 ++++--- crates/openshell-driver-tensorlake/control/deploy.sh | 8 ++++++-- .../docs/control-plane-auth.md | 2 +- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 598971d32c..3c95f9bae2 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -158,7 +158,7 @@ Tensorlake sandbox. │ ▲ UDS │ │ driver ──► Tensorlake API │ └────▲──────────────────────────────┘ - │ https://8080-.sandbox.tensorlake.ai + │ https://8080-.sandbox.tensorlake.ai guards in sandbox VMs (public port, TLS at proxy) ``` @@ -185,7 +185,7 @@ of the control image for that certificate. 3. Connect the CLI. With OIDC, use the public URL: ```shell - openshell gateway add https://8080-openshell-control.sandbox.tensorlake.ai \ + openshell gateway add https://8080-.sandbox.tensorlake.ai \ --oidc-issuer https://issuer.example.com ``` @@ -197,7 +197,8 @@ of the control image for that certificate. ``` Guards cannot hold a Tensorlake key, so port 8080 accepts anonymous -requests. The gateway must authenticate users itself. The start script +requests. The port proxy resolves sandbox names only for authenticated +requests, so the guards' URL uses the sandbox ID (`deploy.sh` prints it). The gateway must authenticate users itself. The start script refuses to run without `OPENSHELL_OIDC_ISSUER`, unless you set `OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1`. With that setting, anyone with the URL controls the gateway. Use it only for a short test with diff --git a/crates/openshell-driver-tensorlake/control/deploy.sh b/crates/openshell-driver-tensorlake/control/deploy.sh index 6c6060d59a..d459dc5f12 100755 --- a/crates/openshell-driver-tensorlake/control/deploy.sh +++ b/crates/openshell-driver-tensorlake/control/deploy.sh @@ -28,7 +28,6 @@ set -euo pipefail NAME="${CONTROL_NAME:-openshell-control}" IMAGE="${CONTROL_IMAGE:-openshell-control}" PORT=8080 -PUBLIC_URL="https://${PORT}-${NAME}.sandbox.tensorlake.ai" PROCESS=openshell-control REMOTE_ENV=/etc/openshell-control/control.env @@ -46,7 +45,12 @@ else --timeout "${CONTROL_TIMEOUT_SECS:-0}" fi -# Guards in other sandboxes dial this port without a Tensorlake key. +# 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}" diff --git a/crates/openshell-driver-tensorlake/docs/control-plane-auth.md b/crates/openshell-driver-tensorlake/docs/control-plane-auth.md index 245ded7044..6b06ccb522 100644 --- a/crates/openshell-driver-tensorlake/docs/control-plane-auth.md +++ b/crates/openshell-driver-tensorlake/docs/control-plane-auth.md @@ -9,7 +9,7 @@ The control plane (gateway and driver) runs in a Tensorlake sandbox. Guards in other sandboxes reach the gateway through the Tensorlake port proxy: ``` -https://8080-.sandbox.tensorlake.ai +https://8080-.sandbox.tensorlake.ai ``` Guards cannot hold a Tensorlake key, so this port must accept anonymous From 75d3d8deca1c20f8de09d043a6318db7648f56fe Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 15:06:52 -0500 Subject: [PATCH 10/31] fix(driver-tensorlake): make the supervisor CA directory traversable The launcher created /run/openshell-supervisor-ca with mode 0700. openshell-sandbox requires that directory to be traversable by every workload identity before it installs the public supervisor CA, so the boundary process failed and the sandbox never became ready. Create it with mode 0755, as the other drivers do. It holds only public certificates. Signed-off-by: Shanshan Wang --- .../image/openshell-tensorlake-launch.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh index 183276e39d..8b3aa0cf19 100755 --- a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh +++ b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh @@ -73,7 +73,10 @@ install -d -m 0700 -o "$SUPERVISOR_UID" -g "$SUPERVISOR_GID" "$SUPERVISOR_RUN_DI # Workload directories. openshell-sandbox makes the workspace owned by the # workload identity before it drops privileges. install -d -m 0755 "$WORKSPACE" -install -d -m 0700 -o "$WORKLOAD_UID" -g "$WORKLOAD_GID" /run/openshell-supervisor-ca +# 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" From f4dc0729d2faf04e11eeb4c2e04700992808b722 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 15:45:21 -0500 Subject: [PATCH 11/31] fix(driver-tensorlake): migrate launch bundles to provisioning evidence The isolation contract replaced the outer fence projection with ProvisioningEvidence. Build the launch bundle with the new type, bind the launch recipe to the sandbox generation, and set provisioning_evidence on the boundary config and runtime descriptor. Repin the supervisor, sandbox, and gateway images to the branch base commit, so the runtime binaries accept the new descriptor schema. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 5 +- .../control/Dockerfile | 2 +- .../image/Dockerfile | 4 +- .../openshell-driver-tensorlake/src/launch.rs | 50 +++++++++---------- 4 files changed, 31 insertions(+), 30 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 3c95f9bae2..10b737946a 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -53,8 +53,9 @@ The workload identity cannot read the guard's files. Root in the VM can. The launcher runs the workload in a new network namespace that has only loopback, so the workload has no network path except the boundary channel. -The driver reports all four outer-fence guarantees based on this launch -recipe. It cannot inspect the VM to confirm them. +The driver binds this launch recipe to the sandbox generation as the +provisioning evidence in the boundary config and runtime descriptor. It +cannot inspect the VM to confirm the recipe. Tensorlake `allow_out` is an optional second wall for the guard's own egress. diff --git a/crates/openshell-driver-tensorlake/control/Dockerfile b/crates/openshell-driver-tensorlake/control/Dockerfile index f290f89fbb..5abe8a5857 100644 --- a/crates/openshell-driver-tensorlake/control/Dockerfile +++ b/crates/openshell-driver-tensorlake/control/Dockerfile @@ -12,7 +12,7 @@ # expand variables in FROM, so the image tags are fixed here. Pin the # upstream commit this branch is based on, the same as image/Dockerfile. -FROM ghcr.io/nvidia/openshell/gateway:a4c848adbddd0b4732fd70ddcf8a563a5b1e9317 AS gateway +FROM ghcr.io/nvidia/openshell/gateway:1cb9ef8ab469354a641893f8e26957e988f5c7ef AS gateway FROM rust:1.95-trixie AS driver WORKDIR /src diff --git a/crates/openshell-driver-tensorlake/image/Dockerfile b/crates/openshell-driver-tensorlake/image/Dockerfile index 5988c5f10b..6611422c3c 100644 --- a/crates/openshell-driver-tensorlake/image/Dockerfile +++ b/crates/openshell-driver-tensorlake/image/Dockerfile @@ -14,8 +14,8 @@ # 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:a4c848adbddd0b4732fd70ddcf8a563a5b1e9317 AS supervisor -FROM ghcr.io/nvidia/openshell/sandbox:a4c848adbddd0b4732fd70ddcf8a563a5b1e9317 AS sandbox +FROM ghcr.io/nvidia/openshell/supervisor:1cb9ef8ab469354a641893f8e26957e988f5c7ef AS supervisor +FROM ghcr.io/nvidia/openshell/sandbox:1cb9ef8ab469354a641893f8e26957e988f5c7ef AS sandbox FROM ubuntu:24.04 diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs index aae704d34c..4103fe996a 100644 --- a/crates/openshell-driver-tensorlake/src/launch.rs +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -21,9 +21,7 @@ use std::collections::{BTreeMap, HashMap}; use std::path::PathBuf; use openshell_core::proto::compute::v1::DriverSandbox; -use openshell_isolation_interface::contract::{ - OuterFenceGuarantee, OuterFenceGuarantees, ResolvedWorkloadIdentity, -}; +use openshell_isolation_interface::contract::{ProvisioningEvidence, ResolvedWorkloadIdentity}; use openshell_sandbox_backend::boundary_protocol::{ BoundaryConfig, BoundaryListener, GatewayVerificationKey, SandboxRuntimeDescriptor, SandboxTlsClientConfig, SandboxTlsServerConfig, SandboxTransport, @@ -111,6 +109,10 @@ pub fn resolve_identity( /// Evidence for the outer fence that the launcher builds. The driver cannot /// inspect the VM, so the evidence names the launch recipe it requested. +/// +/// A loopback-only network namespace has no route out. Egress needs a +/// mediated decision, revocation takes effect at the guard, and guard loss +/// leaves the namespace without a path. #[derive(Serialize)] struct TensorlakeOuterFenceEvidence<'a> { tensorlake_sandbox_id: &'a str, @@ -118,29 +120,22 @@ struct TensorlakeOuterFenceEvidence<'a> { launcher: &'static str, } -fn outer_fence( +/// Bind the launch recipe to one generation as provisioning evidence. +fn provisioning_evidence( tensorlake_sandbox_id: &str, generation: &str, -) -> Result { +) -> Result { + if tensorlake_sandbox_id.is_empty() { + return Err("Tensorlake sandbox ID is required for provisioning evidence".to_string()); + } let evidence = TensorlakeOuterFenceEvidence { tensorlake_sandbox_id, workload_network_namespace: "private-loopback-only", launcher: LAUNCHER_PATH, }; - // A loopback-only network namespace has no route out. Egress needs a - // mediated decision, revocation takes effect at the guard, and guard loss - // leaves the namespace without a path. - let projection = OuterFenceGuarantees::from_enforcement_evidence( - generation, - [ - OuterFenceGuarantee::DefaultDenyEgress, - OuterFenceGuarantee::NoUnmanagedEgressPath, - OuterFenceGuarantee::RevocationVerified, - OuterFenceGuarantee::ControllerLossFailsClosed, - ], - &serde_json::to_vec(&evidence).map_err(invalid)?, - ) - .map_err(invalid)?; + 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) } @@ -298,7 +293,7 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri .runtime_generation .to_string(); let tls = generate_sandbox_tls_material(session_id).map_err(invalid)?; - let outer_fence = outer_fence(tensorlake_sandbox_id, &generation)?; + let provisioning_evidence = provisioning_evidence(tensorlake_sandbox_id, &generation)?; let resource_claims = BTreeMap::from([ ( "tensorlake.sandbox_id".to_string(), @@ -340,7 +335,7 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri resource_claims: resource_claims.clone(), resource_claim_files: BTreeMap::new(), workload_identity: identity.clone(), - outer_fence: outer_fence.clone(), + provisioning_evidence: provisioning_evidence.clone(), child_env: child_environment(sandbox), }; let runtime_descriptor = SandboxRuntimeDescriptor { @@ -357,7 +352,7 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri host_gateway_ip: None, resource_claims, workload_identity: identity.clone(), - outer_fence, + provisioning_evidence, }; let workload = Owner::new(identity.uid, identity.gid); @@ -542,9 +537,14 @@ mod tests { } #[test] - fn outer_fence_is_complete() { - let fence = outer_fence("tl-1", "gen-1").unwrap(); - assert!(fence.validate("gen-1").is_ok()); + fn provisioning_evidence_binds_generation() { + let evidence = provisioning_evidence("tl-1", "gen-1").unwrap(); + assert!(evidence.validate("gen-1").is_ok()); + assert!(evidence.validate("gen-2").is_err()); + let other = provisioning_evidence("tl-2", "gen-1").unwrap(); + assert_ne!(evidence.evidence_digest, other.evidence_digest); + assert!(provisioning_evidence("", "gen-1").is_err()); + assert!(provisioning_evidence("tl-1", "").is_err()); } #[test] From fd6cbad6e20f75ae9db222c46a9cf7cac144f338 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 16:27:11 -0500 Subject: [PATCH 12/31] docs(driver-tensorlake): document a stable image rebuild loop Tensorlake replaces a CAS image when it is built again under the same name, and cannot delete CAS images yet. Tell contributors to keep one pair of development image names, and describe the one-command rebuild paths for sandbox-only and driver changes. Add RECREATE=1 to deploy.sh, which terminates the existing control sandbox before creating it from a new control image. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 28 +++++++++++++++++++ .../control/deploy.sh | 8 +++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 10b737946a..43793474a1 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -84,6 +84,34 @@ directory as the context, and 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. +Tensorlake cannot delete CAS images yet, so every new name stays in the +project forever. + +### Rebuild loop + +For a change to the launcher or `image/Dockerfile`, rebuild only the sandbox +image. The driver resolves the image name on every sandbox create, so the +control plane needs no restart: + +```shell +tl sbx image create crates/openshell-driver-tensorlake/image/Dockerfile \ + --registered-name openshell-tensorlake-test --cas +``` + +For a change to the driver, rebuild both images and recreate the control +sandbox. Recreating discards 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`. Derive from it to add agent tools. diff --git a/crates/openshell-driver-tensorlake/control/deploy.sh b/crates/openshell-driver-tensorlake/control/deploy.sh index d459dc5f12..0664c6c31b 100755 --- a/crates/openshell-driver-tensorlake/control/deploy.sh +++ b/crates/openshell-driver-tensorlake/control/deploy.sh @@ -14,6 +14,8 @@ # CONTROL_NAME sandbox name (default: openshell-control) # CONTROL_IMAGE registered control-plane image (default: openshell-control) # CONTROL_TIMEOUT_SECS Tensorlake idle timeout (default: 0, the plan maximum) +# RECREATE=1 terminate an existing control sandbox first, so a +# new CONTROL_IMAGE takes effect (discards gateway state) # OPENSHELL_SANDBOX_IMAGE sandbox image (default: the one built with CONTROL_IMAGE) # OPENSHELL_OIDC_ISSUER, OPENSHELL_OIDC_AUDIENCE, ... # gateway OIDC settings for user authentication @@ -34,8 +36,12 @@ REMOTE_ENV=/etc/openshell-control/control.env [ -n "${TENSORLAKE_API_KEY:-}" ] || { echo "error: set TENSORLAKE_API_KEY" >&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}. To use a new image, terminate it first." + 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}" From 830b43bfe89111258af5b2f6062fa05c09f7c77a Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Mon, 19 Oct 2026 16:33:34 -0500 Subject: [PATCH 13/31] fix(driver-tensorlake): bound HTTP requests and use the crypto facade The Tensorlake client had no request deadline, so one stalled API or proxy connection froze status and delete reconciliation for every sandbox. Set the Tensorlake SDK default of 300 seconds per request, send the SDK's X-Tensorlake-Request-Timeout-Ms header so the server stops at the same deadline, and add a 10 second connect timeout. Initialize TLS through openshell_crypto::tls::ensure_default_provider instead of installing AWS-LC directly, drop the direct rustls dependency, and list the client with the other Reqwest transports in the crypto README exclusions table. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- Cargo.lock | 2 +- crates/openshell-crypto/README.md | 2 +- crates/openshell-driver-tensorlake/Cargo.toml | 2 +- .../openshell-driver-tensorlake/src/client.rs | 33 ++++++++++++++++++- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5180584bf4..4abc57a15f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4618,11 +4618,11 @@ dependencies = [ "futures", "miette", "openshell-core", + "openshell-crypto", "openshell-isolation-interface", "openshell-otel", "openshell-sandbox-backend", "reqwest 0.12.28", - "rustls", "serde", "serde_json", "tar", 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 index e759320514..6d30e307b0 100644 --- a/crates/openshell-driver-tensorlake/Cargo.toml +++ b/crates/openshell-driver-tensorlake/Cargo.toml @@ -16,6 +16,7 @@ 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" } @@ -26,7 +27,6 @@ tonic = { workspace = true, features = ["transport"] } futures = { workspace = true } tokio-stream = { workspace = true, features = ["sync"] } reqwest = { workspace = true } -rustls = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } clap = { workspace = true } diff --git a/crates/openshell-driver-tensorlake/src/client.rs b/crates/openshell-driver-tensorlake/src/client.rs index 0006350455..d2e4c54db4 100644 --- a/crates/openshell-driver-tensorlake/src/client.rs +++ b/crates/openshell-driver-tensorlake/src/client.rs @@ -8,12 +8,29 @@ //! `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 { @@ -139,12 +156,26 @@ pub struct TensorlakeClient { impl TensorlakeClient { pub fn new(api_url: &str, api_key: &str) -> Result { - let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); + // 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, From 034684a1f7973c2309ae9d5dc6f85446f4764e78 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 11:22:56 -0500 Subject: [PATCH 14/31] feat(driver-tensorlake): emit launch progress events Publish platform events with the shared progress metadata while a sandbox is accepted, pending, running, and while the launch bundle is uploaded and started. The CLI renders these as the requesting, pulling, and starting steps during sandbox creation. Signed-off-by: Shanshan Wang --- .../openshell-driver-tensorlake/src/driver.rs | 237 +++++++++++++++++- 1 file changed, 232 insertions(+), 5 deletions(-) diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs index 9612e52a84..eea752aecc 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -14,11 +14,16 @@ 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, DriverSandbox, DriverSandboxStatus, - GetCapabilitiesResponse, GpuResourceCapabilities, MemoryResourceCapabilities, - ResolvedWorkloadIdentity as ProtoIdentity, ResourceCapabilities, WatchSandboxesDeletedEvent, - WatchSandboxesEvent, WatchSandboxesSandboxEvent, watch_sandboxes_event, + 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; @@ -41,6 +46,9 @@ const PROVISION_TIMEOUT: Duration = Duration::from_mins(10); 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. @@ -433,6 +441,7 @@ impl TensorlakeComputeDriver { .await .insert(sandbox.id.clone(), record.clone()); self.emit_sandbox(&record); + self.publish_progress(&sandbox.id, LaunchProgress::Accepted); let driver = self.clone(); let sandbox = sandbox.clone(); @@ -442,6 +451,7 @@ impl TensorlakeComputeDriver { .await { warn!(sandbox_id = %sandbox.id, %message, "Tensorlake sandbox launch failed"); + driver.publish_progress(&sandbox.id, LaunchProgress::Failed(&message)); driver .set_phase( &sandbox.id, @@ -464,6 +474,7 @@ impl TensorlakeComputeDriver { identity: &ResolvedWorkloadIdentity, ) -> Result<(), String> { let started = Instant::now(); + let mut last_pending_reason: Option = None; let info = loop { if !self.is_active(&sandbox.id).await { return Ok(()); @@ -475,7 +486,22 @@ impl TensorlakeComputeDriver { .map_err(|error| error.to_string())?; match info.status.as_str() { "running" => break info, - "pending" => {} + "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 sandbox entered state '{other}' before launch{}", @@ -489,6 +515,8 @@ impl TensorlakeComputeDriver { tokio::time::sleep(self.config.poll_interval).await; }; self.set_phase(&sandbox.id, Phase::Launching).await; + self.publish_progress(&sandbox.id, LaunchProgress::VmRunning); + self.publish_progress(&sandbox.id, LaunchProgress::UploadingBundle); let bundle = launch::build_launch_bundle(LaunchBundleInput { sandbox, @@ -501,6 +529,7 @@ impl TensorlakeComputeDriver { .write_file(&info, launch::BUNDLE_UPLOAD_PATH, bundle) .await .map_err(|error| format!("upload launch bundle: {error}"))?; + self.publish_progress(&sandbox.id, LaunchProgress::StartingLauncher); let launcher = self .client .start_process( @@ -524,6 +553,7 @@ impl TensorlakeComputeDriver { record.launcher_pid = Some(launcher.pid); } self.set_phase(&sandbox.id, Phase::Running).await; + self.publish_progress(&sandbox.id, LaunchProgress::LauncherStarted); Ok(()) } @@ -630,6 +660,20 @@ impl TensorlakeComputeDriver { 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. @@ -805,6 +849,114 @@ fn failure_detail(info: &SandboxInfo) -> String { } } +/// 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, + /// 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::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::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 + } +} + fn sandbox_event(sandbox: DriverSandbox) -> WatchSandboxesEvent { WatchSandboxesEvent { payload: Some(watch_sandboxes_event::Payload::Sandbox( @@ -1020,6 +1172,81 @@ mod tests { assert!(launcher_failure("tl1", None).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)); From c48d0a143fe70d2bc1379f51f7d7924e7dc2c81b Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 11:23:07 -0500 Subject: [PATCH 15/31] docs: add the Tensorlake runtime page Describe how the Tensorlake compute driver works, how to run the control plane on Tensorlake, how to run the driver next to your own gateway, and its trust model and limits. Link the page from the runtimes, overview, and drivers pages and add it to the navigation. Signed-off-by: Shanshan Wang --- docs/extensibility/drivers.mdx | 1 + docs/how-it-works/sandboxes/overview.mdx | 2 +- docs/how-it-works/sandboxes/runtimes.mdx | 3 +- docs/how-it-works/sandboxes/tensorlake.mdx | 197 +++++++++++++++++++++ docs/index.yml | 2 + 5 files changed, 203 insertions(+), 2 deletions(-) create mode 100644 docs/how-it-works/sandboxes/tensorlake.mdx 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..2ce9e0e242 --- /dev/null +++ b/docs/how-it-works/sandboxes/tensorlake.mdx @@ -0,0 +1,197 @@ +--- +# 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 one Tensorlake VM. The guard +(`openshell-supervisor`) and the workload (`openshell-sandbox`) run inside that +VM. The guard holds the gateway session and the provider credentials. The +workload runs in a private network namespace with only loopback, so every +connection it makes goes through the guard, and the guard applies the policy. + +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`. + 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`. + +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 guard and launcher. | +| `--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; the guard enforces policy. | + +Keep `--timeout-secs` at `0`. Tensorlake counts idle time from incoming +traffic only, and the guard's traffic is outgoing, so a short timeout suspends +a sandbox that is still working. + +`--allow-out` adds a second fence at the Tensorlake network. The driver turns +off internet access for the VM and allows only the hosts you list plus the +gateway host. + +## Images + +Sandbox images must contain the guard, the workload runtime, and the launch +script. 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 guard and the workload share one VM. The guard runs as an unprivileged +user that the workload cannot read, and the workload has no network path +except the channel to the guard. But a root user in the VM can read the +guard's credentials, and anyone with access to the Tensorlake project can run +`tl sbx exec --user root`. Until the guard moves to its own VM, use test +credentials only, and keep the control plane in a Tensorlake project of its +own. + +## Limits + +- Stop and start are not supported. Delete the sandbox instead. +- Workload identity accepts numeric user and group IDs only. The default is + `1000:1000`. +- No GPU, `driver_config`, `platform_config`, or `agent_socket_path`. +- The driver polls Tensorlake every few seconds. Status changes can lag by + that much. +- After a driver restart, sandboxes that had not finished launching are + reported as failed. Running sandboxes are recovered by name. + +For build details, the test runbook, 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..99dcdf3eb5 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: From a8d1aaef31c5b19079a882fa181bda945cc38afc Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 11:23:07 -0500 Subject: [PATCH 16/31] ci(driver-tensorlake): add a manual image publish workflow Run build-images.sh on demand with a version and a public flag so the control-plane and sandbox image pair can be published from CI. Signed-off-by: Shanshan Wang --- .github/workflows/tensorlake-images.yml | 92 +++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 .github/workflows/tensorlake-images.yml diff --git a/.github/workflows/tensorlake-images.yml b/.github/workflows/tensorlake-images.yml new file mode 100644 index 0000000000..3bc53a936c --- /dev/null +++ b/.github/workflows/tensorlake-images.yml @@ -0,0 +1,92 @@ +# 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. Public names are permanent, so +# pick a version that is not registered yet. +# +# Required secret: TENSORLAKE_API_KEY, a key for the Tensorlake project that +# owns the images. + +on: + workflow_dispatch: + inputs: + version: + description: "Image version suffix, for example 0-1-5. Required for a public build." + 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 + + - name: Check inputs + env: + VERSION: ${{ inputs.version }} + PUBLIC: ${{ inputs.public }} + run: | + set -euo pipefail + if [ "${PUBLIC}" = "true" ] && [ -z "${VERSION}" ]; then + echo "::error::a public build needs a version" >&2 + exit 1 + fi + 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}" From e34ca64afe2efba68da57cffea6b5796554060ce Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 11:23:07 -0500 Subject: [PATCH 17/31] docs(driver-tensorlake): record the split topology and auth decision Add the split-topology design for moving the guard out of the workload VM and name the Tensorlake capability it needs. Mark the public gateway with OIDC as the decided control-plane auth. Rewrite the README in plain language, link the new docs, and fix the stale note about image deletion. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 615 ++++++++++++++---- .../docs/control-plane-auth.md | 22 +- .../docs/split-topology.md | 156 +++++ 3 files changed, 660 insertions(+), 133 deletions(-) create mode 100644 crates/openshell-driver-tensorlake/docs/split-topology.md diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 43793474a1..c623350187 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -1,109 +1,141 @@ # openshell-driver-tensorlake -Out-of-process compute driver that runs each OpenShell sandbox in its own -[Tensorlake](https://tensorlake.ai) sandbox (a Firecracker microVM). +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. -This is the basic, combined topology: the guard (`openshell-supervisor`) and -the workload runtime (`openshell-sandbox`) run in the same Tensorlake VM. The -guard holds gateway and provider credentials inside that VM. Use it with -non-production credentials only. A later split topology moves the guard into -its own VM. +## 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. + +In this version, the guard and the workload share one VM. The guard keeps +the gateway and provider credentials inside that VM, so a root user in the +VM could read them. Use test credentials only. The plan to move the guard +out of the workload VM, and the one Tensorlake capability it needs, is in +[docs/split-topology.md](docs/split-topology.md). + +The user-facing page is +[Tensorlake Runtime](../../docs/how-it-works/sandboxes/tensorlake.mdx). ## How it works ``` -openshell CLI ──► gateway ──UDS──► openshell-driver-tensorlake ──HTTPS──► Tensorlake API +openshell CLI ──► gateway ──Unix socket──► openshell-driver-tensorlake ──HTTPS──► Tensorlake API ▲ - │ guard dials the gateway (outbound only) - ┌──────────────────┴───── Tensorlake VM ────────────────────┐ - │ openshell-supervisor (uid 65534, holds credentials) │ - │ ▲ TLS over /.openshell/channel/sandbox/control.sock│ - │ openshell-sandbox (uid 1000, own network namespace with │ - │ only loopback) ──► agent processes │ - └───────────────────────────────────────────────────────────┘ + │ the guard calls the gateway (outbound only) + ┌──────────────────┴──────── Tensorlake sandbox (VM) ───────────────────┐ + │ ┌───────────────── OpenShell sandbox ───────────────────────────────┐ │ + │ │ guard: openshell-supervisor (uid 65534, holds credentials) │ │ + │ │ ▲ TLS over /.openshell/channel/sandbox/control.sock │ │ + │ │ workload: openshell-sandbox (uid 1000, private network with │ │ + │ │ only loopback) ──► agent processes │ │ + │ └───────────────────────────────────────────────────────────────────┘ │ + └───────────────────────────────────────────────────────────────────────┘ ``` -1. `CreateSandbox` calls `POST /sandboxes` with `wait: false` and returns. -2. A background task waits until the VM is `running`. -3. The driver builds a launch bundle (tar) with owners and modes set per file, - uploads it with the Tensorlake file API, and starts +When the gateway asks for a new sandbox: + +1. The driver asks Tensorlake to create a VM and returns at once. It does + not wait for the VM. +2. In the background, the driver waits until the VM reports `running`. +3. The driver packs the files the guard and the workload need into one + archive. Each file in the archive has its owner and permissions set. + The driver uploads the archive with the Tensorlake file API and starts `/opt/openshell/bin/openshell-tensorlake-launch` as root with the Tensorlake process API. -4. The launcher extracts the bundle, deletes it, starts the workload runtime in - a loopback-only network namespace, and starts the guard as uid 65534. -5. The driver reports `Ready=True` when the launcher starts. The gateway marks - the sandbox ready when the guard session connects. -6. Each poll checks the launcher process. If it stopped, the driver marks the - sandbox failed (`LauncherExited`) with its exit status. Tensorlake does - not restart the launcher. - -A poll loop reads `GET /sandboxes` because Tensorlake has no watch API. - -### Credential layout in the VM +4. The launch script unpacks the archive and deletes it. It starts the + workload in a private network that has only loopback. Then it starts + the guard as user 65534, with no special rights. +5. The driver reports the sandbox as ready when the launch script starts. + 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 the launch script is still + running. If it stopped, the driver marks the sandbox as failed with + reason `LauncherExited` and the exit status. 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. + +### Where the files live in the VM | Path | Owner | Contents | |---|---|---| -| `/.openshell/channel/sandbox/` | workload | boundary bootstrap and boundary TLS key | -| `/.openshell/supervisor/` (0700) | guard | auth bundle, sandbox JWT, gateway CA, runtime descriptor | -| `/.openshell/supervisor/env`, `args` | root | guard environment and arguments | +| `/.openshell/channel/sandbox/` | workload | bootstrap file and TLS key for the channel to the guard | +| `/.openshell/supervisor/` (mode 0700) | guard | auth bundle, sandbox token, gateway CA, runtime descriptor | +| `/.openshell/supervisor/env`, `args` | root | the guard's environment and arguments | -The workload identity cannot read the guard's files. Root in the VM can. +The workload user cannot read the guard's files. Root in the VM can. -### Outer fence +### The outer fence -The launcher runs the workload in a new network namespace that has only -loopback, so the workload has no network path except the boundary channel. -The driver binds this launch recipe to the sandbox generation as the -provisioning evidence in the boundary config and runtime descriptor. It -cannot inspect the VM to confirm the recipe. +The launch script runs the workload in a network that has only loopback. +The only way out is the channel to the guard. The driver writes this launch +recipe into the sandbox's config, so the gateway knows which fence this +sandbox got. The driver cannot look inside the VM to confirm that the fence +is in place. -Tensorlake `allow_out` is an optional second wall for the guard's own egress. +You can add a second wall with `--allow-out`. It limits where the guard +itself can connect. See [Run the driver](#run-the-driver). ## Build the images -`build-images.sh` builds two CAS images on Tensorlake (`--cas`). Tensorlake -runs each build, so local Docker is not needed. CAS images start fast and -run on the Tensorlake CAS dataplane. +`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 runtime, launcher | +| Sandbox | `openshell-tensorlake` | guard, workload, launch script | | Control | `openshell-control` | gateway, this driver, start script | ```shell crates/openshell-driver-tensorlake/build-images.sh ``` -The control image records the sandbox image name. The driver uses that -sandbox image unless `OPENSHELL_SANDBOX_IMAGE` is set, so the two images +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 context. Tensorlake uses the Dockerfile -directory as the context, and 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. +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. -Tensorlake cannot delete CAS images yet, so every new name stays in the -project forever. +Delete a name you no longer need with `tl sbx image rm `. -### Rebuild loop +### Rebuild after a change -For a change to the launcher or `image/Dockerfile`, rebuild only the sandbox -image. The driver resolves the image name on every sandbox create, so the -control plane needs no restart: +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 ``` -For a change to the driver, rebuild both images and recreate the control -sandbox. Recreating discards gateway state and changes the sandbox ID, so -add the gateway to the CLI again afterwards: +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 \ @@ -112,8 +144,8 @@ RECREATE=1 CONTROL_IMAGE=openshell-control-test \ crates/openshell-driver-tensorlake/control/deploy.sh ``` -The sandbox image must not contain `/.openshell`. Derive from it to add agent -tools. +The sandbox image must not contain `/.openshell`. To add agent tools, build +a new image on top of it. ### Publish for all Tensorlake users @@ -124,19 +156,24 @@ PUBLIC=1 VERSION=0-1-5 crates/openshell-driver-tensorlake/build-images.sh ``` This registers `openshell-tensorlake-0-1-5` and `openshell-control-0-1-5` -with `--public`. Any Tensorlake project can then use them without a build. -Public names must be unique across Tensorlake, and Tensorlake has no image -tags, so put the version in the name. Do not replace a published version; -publish a new one. +as public images. Any Tensorlake project can use them 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. 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. -## Run +The same build runs in CI from the `Tensorlake Images` workflow +(`.github/workflows/tensorlake-images.yml`). Start it by hand with a version +and 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 its -gRPC endpoint must be reachable from Tensorlake VMs. +The gateway needs launch signing (`[openshell.gateway.gateway_jwt]`), and +Tensorlake VMs must be able to reach its address. ```shell export TENSORLAKE_API_KEY=... @@ -164,100 +201,416 @@ openshell-gateway --compute-driver tensorlake \ | `--allow-out` | `OPENSHELL_TENSORLAKE_ALLOW_OUT` | empty (internet on) | | `--poll-interval-secs` | `OPENSHELL_TENSORLAKE_POLL_INTERVAL_SECS` | 3 | -The guard trusts only the `--gateway-tls-ca` bundle, not public roots. For a -gateway with a public certificate, pass the root CA that signed it. +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, and only incoming traffic resets -it. Guard traffic to the gateway is outgoing, so a short timeout suspends a -working sandbox. Keep the default `0`, which uses the plan maximum. +it. The guard's traffic to the gateway is outgoing. So a short timeout can +pause a sandbox that is still working. Keep the default `0`, which uses the +longest timeout your plan allows. -When `--allow-out` is set, the driver turns off Tensorlake internet access and -adds the gateway host to the list. +When you set `--allow-out`, the driver turns off internet access for the +VM and allows only the hosts you listed plus the gateway host. ## Run the control plane on Tensorlake -`control/` runs the gateway and this driver together in one long-lived -Tensorlake sandbox. +The control plane is the gateway and this driver. The `control/` folder +runs both in one long-lived Tensorlake sandbox. ``` your machine Tensorlake -┌──────────────┐ tl tunnel ┌───────────────────────────────────┐ +┌──────────────┐ login + TLS ┌───────────────────────────────────┐ │ openshell CLI│ ────────────► │ control sandbox │ -└──────────────┘ │ gateway :8080 (plaintext HTTP/2) │ - │ ▲ UDS │ +└──────────────┘ │ gateway :8080 (plain HTTP/2) │ + │ ▲ Unix socket │ │ driver ──► Tensorlake API │ └────▲──────────────────────────────┘ - │ https://8080-.sandbox.tensorlake.ai - guards in sandbox VMs (public port, TLS at proxy) + │ https://8080-.sandbox.tensorlake.ai + guards in sandbox VMs (public port, TLS at the proxy) ``` -The Tensorlake port proxy terminates TLS. Guards trust the public CA bundle -of the control image for that certificate. +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 - published ones. + the published ones. -2. Create the sandbox and start the control plane: +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 OPENSHELL_OIDC_ISSUER=https://issuer.example.com 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 stores settings in `/etc/openshell-control/control.env` (mode - 0600) and starts a managed process with `--restart always`. Run it again - to change settings. Gateway state stays in `/var/lib/openshell`. Set - `OPENSHELL_DB_URL` to use an external database. + The script copies every `OPENSHELL_OIDC_*` variable into + `/etc/openshell-control/control.env` (mode 0600). Then it 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. -3. Connect the CLI. With OIDC, use the public URL: +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://issuer.example.com + 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 ``` - Without OIDC, use a Tensorlake tunnel: - - ```shell - tl sbx tunnel openshell-control 8080 --listen-port 18080 - openshell gateway add http://127.0.0.1:18080 --name tensorlake - ``` + 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. +The decision and the fallback for deployments without an identity provider +are in [docs/control-plane-auth.md](docs/control-plane-auth.md). + +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: -Guards cannot hold a Tensorlake key, so port 8080 accepts anonymous -requests. The port proxy resolves sandbox names only for authenticated -requests, so the guards' URL uses the sandbox ID (`deploy.sh` prints it). The gateway must authenticate users itself. The start script -refuses to run without `OPENSHELL_OIDC_ISSUER`, unless you set -`OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1`. With that setting, anyone with -the URL controls the gateway. Use it only for a short test with -non-production credentials. +```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. +The control sandbox holds the Tensorlake API key. Do not run other +workloads in it. ## Limits -- Stop and start return `Unimplemented`. Delete the sandbox instead. -- Workload identity accepts numeric UID and GID only. The default is 1000:1000. +- Stop and start are not supported. Delete the sandbox instead. +- The workload identity accepts a numeric user ID and group ID only. The + default is 1000:1000. - No GPU, `driver_config`, `platform_config`, or `agent_socket_path`. -- The driver keeps launch state in memory. After a driver restart, running - sandboxes are recovered from Tensorlake names (`openshell-`). Sandboxes - that had not launched are reported as failed. -- A user with Tensorlake account access can run `tl sbx exec --user root` and - bypass OpenShell. - -## Not yet verified on Tensorlake - -The unit tests cover bundle layout, request mapping, and status mapping. An -end-to-end run on Tensorlake still needs to confirm that: - -- the guest kernel enables Landlock and seccomp, and allows `unshare --net`; -- the file API writes as root, and the process API runs the launcher as root; -- the guard can reach the gateway over a long-lived gRPC connection; -- the port proxy sends gRPC to a plaintext HTTP/2 backend, and keeps - long-lived streams open; -- CAS builds accept the multi-stage Dockerfiles and `--public`; -- the CAS dataplane enables Landlock, seccomp, and `unshare --net`, and - supports the file and process APIs, exposed ports, and long-lived managed - processes. +- The driver keeps launch state in memory. After a driver restart, it finds + running sandboxes again by their Tensorlake names (`openshell-`). + Sandboxes that had not finished launching are reported as failed. +- Anyone with access to your Tensorlake account can run + `tl sbx exec --user root` and get around OpenShell. + +## Verified on Tensorlake + +The unit tests cover the archive layout, request mapping, and status +mapping. An end-to-end run (create a sandbox, run a command, read its +output) confirmed that: + +- the VM kernel supports Landlock and seccomp, and allows `unshare --net`; +- 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, which forwards the + calls to the plain HTTP/2 backend; +- image builds accept the multi-stage Dockerfiles and the `--public` flag; +- the Tensorlake dataplane supports the file and process APIs, exposed + ports, and managed processes. + +## Still to confirm + +- The port proxy keeps a long-lived connection open, and the idle timeout + does not pause a sandbox whose only traffic is the guard's outgoing + session. +- The conformance suite in `tests/suites/conformance` passes: lifecycle, + file transfer, and policy enforcement. +- A launch script exit is reported as `LauncherExited`, and a driver + restart recovers running sandboxes. + +## Test runbook + +This section is a temporary checklist for the items in +[Still to confirm](#still-to-confirm). Remove it once they are confirmed. + +Use two shells. Shell A keeps the tunnel open. Shell B runs everything +else. The later steps run `deploy.sh` again, so keep the exported +variables in shell B for the whole run. The steps assume the control +sandbox is `openshell-control`, the CLI gateway is named `tensorlake`, and +the tunnel listens on port 18080. + +### 0. Build and deploy the control plane + +Build the two images. Skip this if you already have a pair you trust: + +```shell +cd ~/Documents/work/OpenShell +SANDBOX_IMAGE=openshell-tensorlake-test CONTROL_IMAGE=openshell-control-test \ + crates/openshell-driver-tensorlake/build-images.sh +``` + +Export the deploy settings. For a test gateway without a login service: + +```shell +export TENSORLAKE_API_KEY=your_api_key +export CONTROL_IMAGE=openshell-control-test +export OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1 +``` + +With a login service, replace the last line with +`export OPENSHELL_OIDC_ISSUER=https://issuer.example.com`. + +Deploy. Use `RECREATE=1` if a control sandbox already exists and you want +the new image: + +```shell +RECREATE=1 crates/openshell-driver-tensorlake/control/deploy.sh +``` + +The script prints the public URL and the sandbox ID. Check that the +control plane came up: + +```shell +tl sbx logs openshell-control | tail -20 +``` + +Expected: a line `control plane started at https://8080-...` and no +`error` lines. + +Open the tunnel in shell A: + +```shell +tl sbx tunnel openshell-control 8080 --listen-port 18080 +``` + +Back in shell B, build the CLI, register the gateway, and check it: + +```shell +cargo build -p openshell-cli +export OPENSHELL_BIN=$PWD/target/debug/openshell +$OPENSHELL_BIN gateway add http://127.0.0.1:18080 --name tensorlake +export OPENSHELL_GATEWAY=tensorlake +$OPENSHELL_BIN gateway list +$OPENSHELL_BIN status +``` + +If the gateway name is already registered from an earlier run, the add +fails. Remove the old entry first with +`$OPENSHELL_BIN gateway remove tensorlake`, or pick a new name and export +that instead. Both commands must succeed before you go on. + +### 1. Conformance suite + +Allow up to an hour. Each scenario creates its own sandboxes and deletes +them. Save the output: + +```shell +cargo test --locked \ + --manifest-path tests/suites/conformance/Cargo.toml \ + --package openshell-test-conformance-cli \ + --no-fail-fast -- --test-threads=1 --nocapture 2>&1 \ + | tee ~/tensorlake-conformance.log +``` + +The policy scenario opens a TCP connection to `1.1.1.1:443` from bash +inside the sandbox and expects `DENIED`. That line is the one to look for. + +### 2. Launch script death + +```shell +$OPENSHELL_BIN sandbox create --name kill-test --detach +$OPENSHELL_BIN sandbox get kill-test +``` + +Repeat the get until it shows Ready. Then find the sandbox ID and kill the +launch script as root: + +```shell +$OPENSHELL_BIN sandbox get kill-test --output json | grep '"id"' +tl sbx exec --user root openshell- pkill -f openshell-tensorlake-launch +sleep 10 +$OPENSHELL_BIN sandbox get kill-test +``` + +Expected: Ready is False and the reason is `LauncherExited`. Keep this +sandbox for step 5. + +### 3. Driver restart + +Create one sandbox and wait for Ready. Then create a second and do not +wait: + +```shell +$OPENSHELL_BIN sandbox create --name restart-a --detach +$OPENSHELL_BIN sandbox get restart-a +$OPENSHELL_BIN sandbox create --name restart-b --detach +``` + +Restart the control plane by running the deploy script again with the +same variables. Without `RECREATE=1`, it keeps the sandbox and the gateway +state and only restarts the process: + +```shell +crates/openshell-driver-tensorlake/control/deploy.sh +``` + +If the tunnel in shell A dropped, start it again. Then check: + +```shell +tl sbx logs openshell-control | grep -i recovered +$OPENSHELL_BIN sandbox list +$OPENSHELL_BIN sandbox exec --name restart-a --no-tty -- echo hello +$OPENSHELL_BIN sandbox get restart-b +``` + +Expected: a `Recovered Tensorlake sandboxes` log line, `restart-a` still +Ready with the exec printing `hello`, and `restart-b` Failed with reason +`DriverRestarted` if it was still pending at restart time. If `restart-b` +had already reached Ready, it should also work. + +### 4. Idle timeout + +Read the timeout that the control sandbox got from the default of `0`: + +```shell +tl sbx describe openshell-control +``` + +Note the timeout value. That is the plan maximum. Then run a bounded test +with a 3 minute timeout: + +```shell +OPENSHELL_TENSORLAKE_TIMEOUT_SECS=180 crates/openshell-driver-tensorlake/control/deploy.sh +$OPENSHELL_BIN sandbox create --name idle-test --detach +$OPENSHELL_BIN sandbox get idle-test +``` + +Wait for Ready, then leave it alone for 5 minutes and check: + +```shell +sleep 300 +$OPENSHELL_BIN sandbox get idle-test +$OPENSHELL_BIN sandbox get idle-test --output json | grep '"id"' +tl sbx describe openshell- +``` + +Expected: the sandbox shows Suspended, because the guard's outgoing +session did not reset the idle clock. That confirms the plan maximum must +be long enough for a user session. Afterwards, deploy again without the +variable to restore the default: + +```shell +crates/openshell-driver-tensorlake/control/deploy.sh +``` + +### 5. Delete + +```shell +$OPENSHELL_BIN sandbox delete kill-test +$OPENSHELL_BIN sandbox delete restart-a +$OPENSHELL_BIN sandbox delete restart-b +$OPENSHELL_BIN sandbox delete idle-test +sleep 10 +$OPENSHELL_BIN sandbox list +tl sbx list +``` + +Expected: no sandboxes in the first list, and no names starting with +`openshell-` in the second, apart from `openshell-control`. + +### What to collect + +- The conformance log file. +- The output of each `get` and `list` command. +- The last 50 lines of `tl sbx logs openshell-control`. + +## After the runbook passes + +This section is a temporary plan. Remove it once the work is done. + +### 1. Case study: run Claude Code on Tensorlake through OpenShell + +The hello test proves the plumbing. The case study proves the three things +a real user needs: the guard injects a real provider credential, the policy +blocks a real agent's stray traffic, and a custom agent image works. The +`--from` flag on sandbox create maps to a Tensorlake image name, so the +driver already supports this. + +Build a derived image on Tensorlake. Its Dockerfile starts +`FROM openshell-tensorlake-test` and installs Claude Code. Register it: + +```shell +tl sbx image create path/to/Dockerfile \ + --registered-name openshell-tensorlake-claude --cas +``` + +Import the provider profile and create the provider. The API key stays in +the gateway and never enters the workload: + +```shell +openshell profile import --file providers/claude-code.yaml +export ANTHROPIC_API_KEY=your_api_key +openshell provider create --name anthropic --type anthropic --from-existing +``` + +Run the agent: + +```shell +openshell sandbox create --name demo \ + --from openshell-tensorlake-claude \ + --provider anthropic \ + -- claude -p "write a hello world in python and run it" +``` + +Then show one denied request, for example the agent reaching PyPI. Approve +the drafted policy rule and run again. + +The output is a tutorial page under `docs/tutorials/`, modeled on +"Run your first agent", plus a section in the design doc. The first run +will hit denials for npm or PyPI. Budget time to settle the policy before +you record the final run. + +### 2. Publish the first public image pair + +Run the `Tensorlake Images` workflow with a version and `public: true`, or +run `PUBLIC=1 VERSION= build-images.sh` from a clean checkout in +the project that owns the public images. Do this only after the runbook +passes, because a published version cannot be replaced. + +### 3. Later + +- Stop and start. +- GPU. +- The split topology in [docs/split-topology.md](docs/split-topology.md), + so production credentials never enter a workload VM. It is blocked on a + raw TCP path between Tensorlake sandboxes. diff --git a/crates/openshell-driver-tensorlake/docs/control-plane-auth.md b/crates/openshell-driver-tensorlake/docs/control-plane-auth.md index 6b06ccb522..7e215f136d 100644 --- a/crates/openshell-driver-tensorlake/docs/control-plane-auth.md +++ b/crates/openshell-driver-tensorlake/docs/control-plane-auth.md @@ -1,7 +1,25 @@ # Control-plane authentication on Tensorlake -Status: proposed. The current `control/` setup uses OIDC, or no user -authentication for tests. +Status: decided. The control plane runs on Tensorlake behind a public URL and +authenticates users with OIDC. The mTLS design below stays as the fallback +for deployments that have no identity provider. + +## Decision + +A public gateway endpoint is inherent to a remote sandbox provider. Guards in +sandbox VMs must dial the gateway, they cannot hold a Tensorlake key, and +Tensorlake offers no inbound tunnel to a user's machine. So the gateway must +accept connections from the internet, and the gateway itself must +authenticate every user call. + +OIDC is the supported way to do that. The gateway already validates tokens, +checks roles, and refreshes keys, and the CLI already logs in through a +browser or a device code. The `control/` scripts refuse to start without an +issuer unless the operator sets the test-only +`OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1`. + +The mTLS-over-tunnel design below is not implemented. Use it if a deployment +has no identity provider and cannot get one. ## Problem diff --git a/crates/openshell-driver-tensorlake/docs/split-topology.md b/crates/openshell-driver-tensorlake/docs/split-topology.md new file mode 100644 index 0000000000..098e1ff4d2 --- /dev/null +++ b/crates/openshell-driver-tensorlake/docs/split-topology.md @@ -0,0 +1,156 @@ +# Split topology: the guard outside the workload VM + +Status: design. Not implemented. It needs one Tensorlake capability that is +not confirmed yet, listed under [What Tensorlake must provide](#what-tensorlake-must-provide). + +## Problem + +Today the guard (`openshell-supervisor`) and the workload (`openshell-sandbox`) +share one Tensorlake VM. The guard holds the gateway session token and the +provider credentials. A root user in that VM can read them, and anyone with +access to the Tensorlake project can become root with `tl sbx exec --user +root`. So the driver is safe for test credentials only. + +The VM driver (`openshell-driver-vm`) does not have this gap. Its guard runs +on the gateway host and reaches the guest over a vsock channel. Credentials +never enter the VM. This document describes how to get the same property on +Tensorlake. + +## What the protocol already supports + +The sandbox protocol between the guard and the workload is TLS with keys that +the driver creates for each sandbox generation. It does not depend on a Unix +socket. The shared types in `openshell-sandbox-backend` and `openshell-core` +offer three transports: + +| Side | Type | Variants | +|---|---|---| +| Workload listens | `BoundaryListener` | `Unix`, `TlsTcp { address }`, `Vsock` | +| Guard connects | `SandboxTransport` | `Unix`, `Tcp { authority, addresses }`, `Vsock` | + +The VM driver uses `Vsock`. The Tensorlake driver uses `Unix` today. The +split topology uses `TlsTcp` on the workload side and `Tcp` on the guard side. +`Tcp.addresses` must be concrete `IP:port` pairs; a hostname is not accepted. +No change to `openshell-supervisor` or `openshell-sandbox` is needed. + +## Two placements + +Both placements move the guard out of the workload VM. They differ in how +many guard processes share one VM. + +### A. Guard in the control sandbox (recommended first) + +The control sandbox already runs the gateway and the driver. It holds the +Tensorlake key, so it is already the trusted component. Run one +`openshell-supervisor` process per sandbox inside it, the same way the VM +driver runs one supervisor per sandbox on the gateway host. + +``` + control sandbox (trusted) workload sandbox (untrusted) +┌─────────────────────────────────┐ ┌──────────────────────────┐ +│ gateway ◄── loopback ── guard ──┼── TLS/TCP ──► openshell-sandbox │ +│ driver ──► Tensorlake API │ │ └─► agent processes │ +└─────────────────────────────────┘ └──────────────────────────┘ +``` + +- The guard dials the gateway on loopback. The public gateway URL is still + needed for users, but not for guards. The idle-timeout problem in the README + goes away for the workload VM, because the guard's connection to it is + incoming traffic. +- The workload VM gets a Tensorlake network policy with + `allow_internet_access: false` and an empty `allow_out`. It needs no + egress at all: the workload's connections travel over the boundary channel + to the guard, which applies policy and connects upstream. This network + policy is the outer fence, and the driver can record it as fence evidence + from the API response rather than from a launch recipe it cannot inspect. +- One image: the sandbox image keeps only `openshell-sandbox` and a smaller + launch script. The control image already has the gateway and the driver and + gains `openshell-supervisor`. +- The driver spawns and reaps the supervisor processes. The VM driver's + `spawn_host_supervisor` in `crates/openshell-driver-vm/src/driver.rs` is the + model: an environment and argument list, a run directory per sandbox, and a + wait on the child. + +The cost is that the control sandbox concentrates privilege. It does today +already. Keep it in its own Tensorlake project. + +### B. One guard VM per sandbox + +Create two Tensorlake sandboxes per OpenShell sandbox: `openshell-` for +the workload and `openshell--guard` for the guard. The guard VM runs from a +small guard image and dials the gateway over the public URL as today. + +This keeps the control sandbox small and gives each guard its own kernel. It +doubles the VM count and the boot time, needs a second image, and needs +pairwise recovery after a driver restart. Do it only if placement A proves +too concentrated. + +## Driver changes for placement A + +1. **Launch bundle.** Split `launch::build_launch_bundle` into a workload + bundle (bootstrap, server certificate and key, launch parameters) and a + guard bundle (runtime descriptor, auth bundle, sandbox token, gateway CA). + Only the workload bundle is uploaded. The guard bundle is written to a + private directory in the control sandbox, mode 0700, owned by the driver + user. +2. **Listener.** The bootstrap's `BoundaryListener` becomes + `TlsTcp { address: 0.0.0.0: }`. The launch script no longer creates a + network namespace. It starts `openshell-sandbox launch-capability-free` + directly. +3. **Transport.** The runtime descriptor's `SandboxTransport` becomes + `Tcp { authority: "openshell-", addresses: [:] }`. + The driver must know the workload VM's address when the VM reports + `running`. See the next section. +4. **Supervisor process.** After the launcher starts, the driver spawns + `openshell-supervisor` in the control sandbox with the guard bundle. It + records the child in the sandbox `Record` and treats child exit the same as + `LauncherExited` today. +5. **Network policy.** `CreateSandboxRequest.network` is always set for the + workload VM: `allow_internet_access: false`, `allow_out: []`. The + `--allow-out` flag then applies to the control sandbox, not to workload + VMs, and can be removed from the driver. +6. **Fence evidence.** Replace `TensorlakeOuterFenceEvidence.workload_network_namespace` + with the applied Tensorlake network policy. +7. **Recovery.** On restart, the driver finds workload VMs by name as today, + and restarts a supervisor for each one from the saved guard bundle. Guard + bundles therefore must survive a driver restart, which they do in the + control sandbox's `/var/lib/openshell`. +8. **Control image.** Add `openshell-supervisor` from the published + supervisor image and `ca-certificates` for upstream TLS. + +Steps 1 to 3 are pure Rust changes with unit tests. Steps 4 to 8 need a +Tensorlake account to test end to end. + +## What Tensorlake must provide + +The guard must open a raw TCP connection to the workload VM and complete a +TLS handshake with the workload's own certificate. The Tensorlake port proxy +cannot carry this channel, because it terminates TLS and presents its own +certificate. + +The driver needs one of: + +- **Private sandbox-to-sandbox networking.** Sandboxes in one project can + reach each other on a private IP, and the API returns that IP in the + sandbox description. This is the clean answer. `SandboxInfo` today exposes + `sandbox_url` and `routing_hint` only. +- **A raw TCP port forward.** An exposed port that forwards bytes without TLS + termination, reachable from the control sandbox, plus a stable address for + it. + +In both cases the workload VM must be able to accept the connection with +internet access turned off. + +Until one of these exists, the combined topology stays, and the README's +warning about test credentials stands. + +## Open questions + +- Does a Tensorlake network policy with `allow_internet_access: false` block + inbound connections too, or only outbound? +- How many supervisor processes can the control sandbox run with 2 vCPUs and + 4 GiB? The VM driver's supervisor is small, but the limit sets the + per-control-plane sandbox count. +- Can the driver learn the workload VM's address before the launcher starts, + so the guard bundle is complete at launch time, or must it start the + supervisor only after the first poll shows the address? From 55f03fe261a071fe032380d1cd34cee72dc0247e Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 14:41:06 -0500 Subject: [PATCH 18/31] feat(driver-tensorlake): run the guard in its own Tensorlake VM Add the split topology, now the default: each OpenShell sandbox gets a workload VM and a guard VM. The workload VM runs openshell-sandbox in a private network namespace with a veth link, listens on a TLS port, and has every outbound connection turned off by a Tensorlake network policy. The guard VM runs openshell-supervisor and a Tensorlake tunnel that delivers the guard's connection to a forwarder in the workload VM, so OpenShell's TLS runs end to end and no credential enters the agent's VM. The driver creates, provisions, polls, recovers, and deletes the pair. Names are openshell- and openshell--guard, and only UUID-shaped IDs are treated as sandboxes, so the control sandbox is no longer picked up by recovery. New flags: --topology, --guard-image, --guard-cpus, and --guard-memory-mb. --topology combined keeps the one-VM mode. Both topologies now run the workload runtime as PID 1 of its own PID namespace, which network policy needs to resolve binary identity, and no longer grant the transparent TCP capability, which is for guards that share the workload's network namespace. The image gains the Tensorlake CLI and socat. Signed-off-by: Shanshan Wang --- .../image/Dockerfile | 22 +- .../image/openshell-tensorlake-launch.sh | 209 ++++-- .../openshell-driver-tensorlake/src/client.rs | 13 + .../openshell-driver-tensorlake/src/config.rs | 97 ++- .../openshell-driver-tensorlake/src/driver.rs | 655 ++++++++++++++---- .../openshell-driver-tensorlake/src/launch.rs | 467 +++++++++++-- .../openshell-driver-tensorlake/src/main.rs | 28 +- 7 files changed, 1247 insertions(+), 244 deletions(-) diff --git a/crates/openshell-driver-tensorlake/image/Dockerfile b/crates/openshell-driver-tensorlake/image/Dockerfile index 6611422c3c..f1a480f8c7 100644 --- a/crates/openshell-driver-tensorlake/image/Dockerfile +++ b/crates/openshell-driver-tensorlake/image/Dockerfile @@ -4,8 +4,11 @@ # Tensorlake sandbox image for the OpenShell Tensorlake compute driver. # # It adds the OpenShell guard (openshell-supervisor), the workload runtime -# (openshell-sandbox), and the launcher to an Ubuntu base. Add agent tools -# (for example Claude Code) in a derived image. +# (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). @@ -19,12 +22,21 @@ FROM ghcr.io/nvidia/openshell/sandbox:1cb9ef8ab469354a641893f8e26957e988f5c7ef A FROM ubuntu:24.04 -# iproute2: loopback in the workload network namespace. -# util-linux: unshare and setpriv. ca-certificates: guard TLS to upstreams. +# 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 iproute2 util-linux \ + && 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 \ diff --git a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh index 8b3aa0cf19..44b51bfa22 100755 --- a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh +++ b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh @@ -5,17 +5,27 @@ # 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 script: +# as root through the Tensorlake process API. The bundle's launch parameters +# name the role this VM plays: # -# 1. Extracts the bundle with the owners and modes the driver set, then -# deletes it. -# 2. Starts the workload runtime (openshell-sandbox) in a new network -# namespace that has only loopback. The workload has no network path -# except the authenticated boundary channel to the guard. -# 3. Starts the guard (openshell-supervisor) as an unprivileged identity -# that the workload cannot read. +# 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. +# combined Start both in this VM. The workload runs in a network +# namespace that has only loopback, so its only path out is the +# channel to the guard. Test credentials only. # -# The script stays in the foreground and exits when either process exits. +# 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. set -euo pipefail @@ -24,6 +34,13 @@ 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 @@ -48,37 +65,42 @@ tar --extract --file "$BUNDLE" --directory / --same-owner --same-permissions --n rm -f "$BUNDLE" # Read launch parameters (KEY=VALUE, numeric values and absolute paths). -WORKLOAD_UID="" WORKLOAD_GID="" SUPERVISOR_UID="" SUPERVISOR_GID="" -WORKSPACE="" SUPERVISOR_RUN_DIR="" +ROLE=combined +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" -for id in "$WORKLOAD_UID" "$WORKLOAD_GID" "$SUPERVISOR_UID" "$SUPERVISOR_GID"; do - [[ "$id" =~ ^[0-9]+$ ]] || fatal "launch identity '$id' is not numeric" -done -[[ "$WORKSPACE" == /* && "$SUPERVISOR_RUN_DIR" == /* ]] || fatal "launch paths must be absolute" - -# Guard runtime directory: proxy TLS material, SSH socket, health socket. -install -d -m 0700 -o "$SUPERVISOR_UID" -g "$SUPERVISOR_GID" "$SUPERVISOR_RUN_DIR" - -# Workload directories. openshell-sandbox makes the workspace owned by the -# workload identity before it drops privileges. -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" + +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() { @@ -88,30 +110,123 @@ cleanup() { } trap cleanup EXIT -# Workload: private network and mount namespaces. Only loopback exists in -# the network namespace. The resolver points at the sandbox DNS relay. -log "starting workload runtime as ${WORKLOAD_UID}:${WORKLOAD_GID}" -unshare --net --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+=("$!") +# Workload runtime, in private network, mount, and PID namespaces. $1 is +# "loopback" for a network namespace with only loopback (combined role: the +# guard is in this VM and uses a Unix socket), or "veth" for a namespace +# that also has one veth link to this VM (workload role: the guard connects +# over TCP through the forwarder). Either way 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() { + local network="$1" + 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" + local -a enter + local -a unshare_common=(--pid --fork --kill-child --mount-proc --mount --propagation private) + if [ "$network" = veth ]; then + 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 + enter=(ip netns exec "$WORKLOAD_NETNS" unshare "${unshare_common[@]}" --) + else + enter=(unshare --net "${unshare_common[@]}" --) + fi + log "starting workload runtime as ${WORKLOAD_UID}:${WORKLOAD_GID} (${network} network)" + "${enter[@]}" /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. +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" \ + "TCP4:${VETH_WORKLOAD_ADDR}:${WORKLOAD_LISTEN_PORT},bind=${VETH_HOST_ADDR}" & + pids+=("$!") +} # Guard: unprivileged identity, clean environment, no capabilities. -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+=("$!") +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 + combined) + start_workload loopback + start_guard + ;; + workload) + start_workload veth + 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 other" +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 index d2e4c54db4..ce4788a09b 100644 --- a/crates/openshell-driver-tensorlake/src/client.rs +++ b/crates/openshell-driver-tensorlake/src/client.rs @@ -78,6 +78,19 @@ pub struct NetworkPolicy { 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, diff --git a/crates/openshell-driver-tensorlake/src/config.rs b/crates/openshell-driver-tensorlake/src/config.rs index 45f018c5b2..d738dd0d2c 100644 --- a/crates/openshell-driver-tensorlake/src/config.rs +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -18,6 +18,47 @@ 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 in the split topology. +pub const DEFAULT_GUARD_CPUS: f64 = 1.0; + +/// Default memory in MiB for a guard VM in the split topology. The guard +/// uses about 32 MiB and the tunnel about 15 MiB. +pub const DEFAULT_GUARD_MEMORY_MB: i64 = 1024; + +/// Where the guard runs relative to the workload. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Topology { + /// The guard runs in its own Tensorlake VM and reaches the workload VM + /// through a Tensorlake tunnel. Credentials never enter the workload VM. + #[default] + Split, + /// The guard and the workload share one VM. Test credentials only. + Combined, +} + +impl Topology { + pub const fn as_str(self) -> &'static str { + match self { + Self::Split => "split", + Self::Combined => "combined", + } + } +} + +impl std::str::FromStr for Topology { + type Err = String; + + fn from_str(value: &str) -> Result { + match value.trim().to_ascii_lowercase().as_str() { + "split" => Ok(Self::Split), + "combined" => Ok(Self::Combined), + other => Err(format!( + "unknown topology '{other}'; use 'split' or 'combined'" + )), + } + } +} + #[derive(Clone)] pub struct TensorlakeComputeConfig { /// Tensorlake sandbox lifecycle API base URL. @@ -44,6 +85,13 @@ pub struct TensorlakeComputeConfig { pub poll_interval: Duration, /// Default log level for the guard when the sandbox spec sets none. pub log_level: String, + /// Guard placement. + pub topology: Topology, + /// 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, } impl std::fmt::Debug for TensorlakeComputeConfig { @@ -61,6 +109,10 @@ impl std::fmt::Debug for TensorlakeComputeConfig { .field("timeout_secs", &self.timeout_secs) .field("allow_out", &self.allow_out) .field("poll_interval", &self.poll_interval) + .field("topology", &self.topology) + .field("guard_image", &self.guard_image) + .field("guard_cpus", &self.guard_cpus) + .field("guard_memory_mb", &self.guard_memory_mb) .finish() } } @@ -101,22 +153,55 @@ impl TensorlakeComputeConfig { 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(()) } - /// Tensorlake `allow_out` with the gateway host added, so the guard can - /// always reach the gateway. + /// Image for guard VMs in the split topology. + pub fn guard_image(&self) -> &str { + self.guard_image.as_deref().unwrap_or(&self.default_image) + } + + /// Host of the Tensorlake API, which the guard VM's tunnel must reach. + fn tensorlake_host(&self) -> Option { + url::Url::parse(&self.api_url) + .ok() + .and_then(|url| url.host_str().map(str::to_string)) + } + + /// Tensorlake `allow_out` for the VM that runs the guard, with the hosts + /// the guard itself needs added: the gateway, and in the split topology + /// the Tensorlake hosts the tunnel talks to. 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::Url::parse(&self.grpc_endpoint) .ok() .and_then(|url| url.host_str().map(str::to_string)) - && !entries.contains(&host) { - entries.push(host); + push(host); + } + if self.topology == Topology::Split + && let Some(host) = self.tensorlake_host() + { + push(format!("*.{host}")); + push(host); } entries } @@ -140,6 +225,10 @@ pub(crate) mod tests { allow_out: Vec::new(), poll_interval: DEFAULT_POLL_INTERVAL, log_level: "info".into(), + topology: Topology::Combined, + guard_image: None, + guard_cpus: DEFAULT_GUARD_CPUS, + guard_memory_mb: DEFAULT_GUARD_MEMORY_MB, } } diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs index eea752aecc..a15f343e0d 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -3,11 +3,12 @@ //! Tensorlake compute driver. //! -//! Each `OpenShell` sandbox maps to one Tensorlake sandbox (a Firecracker VM). -//! Create returns after Tensorlake accepts the request. A background task then -//! waits for the VM to run, uploads the launch bundle, and starts the in-image -//! launcher as root. A poll loop keeps status current because Tensorlake has no -//! watch API. +//! Each `OpenShell` sandbox maps to one Tensorlake sandbox (a small VM) for +//! the workload and, in the default split topology, 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. use std::collections::HashMap; use std::sync::Arc; @@ -35,12 +36,15 @@ use crate::client::{ CreateSandboxRequest, NetworkPolicy, ProcessInfo, Resources, SandboxInfo, StartProcessRequest, TensorlakeClient, TensorlakeError, }; -use crate::config::TensorlakeComputeConfig; +use crate::config::{TensorlakeComputeConfig, Topology}; use crate::launch::{self, LaunchBundleInput}; /// Prefix for Tensorlake sandbox names created by this driver. pub const NAME_PREFIX: &str = "openshell-"; +/// Suffix of the guard VM's Tensorlake name in the split topology. +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); @@ -68,12 +72,18 @@ enum Phase { #[derive(Debug, Clone)] struct Record { sandbox: DriverSandbox, + /// The workload VM, or the only VM in the combined topology. tensorlake_id: String, tensorlake_name: String, + /// The guard VM in the split topology. + guard_tensorlake_id: Option, identity: Option, phase: Phase, - /// PID of the launcher in the VM. `None` for recovered records. + /// 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 and + /// in the combined topology. + guard_launcher_pid: Option, } impl Record { @@ -151,6 +161,38 @@ pub fn tensorlake_name(sandbox_id: &str) -> String { 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(); @@ -390,36 +432,81 @@ impl TensorlakeComputeDriver { if self.records.lock().await.contains_key(&sandbox.id) { return Err(Status::already_exists("sandbox already exists")); } + let split = self.config.topology == Topology::Split; + // The VM that runs the guard needs the gateway and, with a tunnel, + // the Tensorlake hosts. Empty keeps Tensorlake's default internet. let allow_out = self.config.effective_allow_out(); - let network = (!allow_out.is_empty()).then(|| NetworkPolicy { + let guard_network = (!allow_out.is_empty()).then(|| NetworkPolicy { allow_internet_access: false, allow_out, deny_out: Vec::new(), }); - let name = tensorlake_name(&sandbox.id); - let request = CreateSandboxRequest { - image: Some(self.image_for(sandbox)), - resources: Some(resources), - timeout_secs: self.config.timeout_secs, - network, - name: Some(name.clone()), - wait: Some(false), + // The workload VM in the split topology gets no outbound path at + // all. Its connections travel over the boundary channel to the guard. + let workload_network = if split { + Some(NetworkPolicy::no_egress()) + } else { + guard_network.clone() }; + let name = tensorlake_name(&sandbox.id); let created = self .client - .create_sandbox(&request) + .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 - .map_err(|error| match error { - TensorlakeError::Api { status, .. } if status.as_u16() == 409 => { - Status::already_exists("Tensorlake sandbox already exists") - } - other => Status::unavailable(other.to_string()), - })?; + .map_err(create_error)?; info!( sandbox_id = %sandbox.id, tensorlake_sandbox_id = %created.sandbox_id, "Created Tensorlake sandbox" ); + let guard_tensorlake_id = if split { + 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; + match guard { + Ok(guard) => { + info!( + sandbox_id = %sandbox.id, + tensorlake_sandbox_id = %guard.sandbox_id, + "Created Tensorlake guard sandbox" + ); + Some(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" + ); + } + return Err(create_error(error)); + } + } + } else { + None + }; // Keep secrets out of the stored record; only the provisioning task // sees the launch credentials. @@ -432,9 +519,11 @@ impl TensorlakeComputeDriver { 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, }; self.records .lock() @@ -447,7 +536,12 @@ impl TensorlakeComputeDriver { let sandbox = sandbox.clone(); tokio::spawn(async move { if let Err(message) = driver - .provision(&sandbox, &created.sandbox_id, &identity) + .provision( + &sandbox, + &created.sandbox_id, + guard_tensorlake_id.as_deref(), + &identity, + ) .await { warn!(sandbox_id = %sandbox.id, %message, "Tensorlake sandbox launch failed"); @@ -466,26 +560,92 @@ impl TensorlakeComputeDriver { Ok(()) } - /// Wait for the VM, upload the launch bundle, and start the launcher. + /// Wait for the VMs, upload the launch bundles, and start the launchers. async fn provision( &self, sandbox: &DriverSandbox, tensorlake_id: &str, + guard_tensorlake_id: Option<&str>, identity: &ResolvedWorkloadIdentity, ) -> Result<(), String> { let started = Instant::now(); + let Some(workload_info) = self + .wait_running(sandbox, tensorlake_id, "workload", started) + .await? + else { + return Ok(()); + }; + let guard_info = match guard_tensorlake_id { + Some(guard_id) => match self + .wait_running(sandbox, guard_id, "guard", started) + .await? + { + Some(info) => Some(info), + None => return Ok(()), + }, + None => None, + }; + self.set_phase(&sandbox.id, 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}"))?; + let guard_launcher_pid = + if let (Some(guard_info), Some(bundle)) = (&guard_info, bundles.guard) { + self.client + .write_file(guard_info, launch::BUNDLE_UPLOAD_PATH, bundle) + .await + .map_err(|error| format!("upload guard launch bundle: {error}"))?; + self.publish_progress(&sandbox.id, LaunchProgress::StartingLauncher); + Some(self.start_launcher(sandbox, guard_info, "guard").await?) + } else { + self.publish_progress(&sandbox.id, LaunchProgress::StartingLauncher); + None + }; + let launcher_pid = self + .start_launcher(sandbox, &workload_info, "workload") + .await?; + if let Some(record) = self.records.lock().await.get_mut(&sandbox.id) { + record.launcher_pid = Some(launcher_pid); + record.guard_launcher_pid = guard_launcher_pid; + } + self.set_phase(&sandbox.id, 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, + ) -> Result, String> { let mut last_pending_reason: Option = None; - let info = loop { + loop { if !self.is_active(&sandbox.id).await { - return Ok(()); + return Ok(None); } let info = self .client .get_sandbox(tensorlake_id) .await - .map_err(|error| error.to_string())?; + .map_err(|error| format!("get Tensorlake {role} sandbox: {error}"))?; match info.status.as_str() { - "running" => break info, + "running" => return Ok(Some(info)), "pending" => { // Report a new pending reason once, not on every poll. let reason = info @@ -504,36 +664,31 @@ impl TensorlakeComputeDriver { } other => { return Err(format!( - "Tensorlake sandbox entered state '{other}' before launch{}", + "Tensorlake {role} sandbox entered state '{other}' before launch{}", failure_detail(&info) )); } } if started.elapsed() > PROVISION_TIMEOUT { - return Err("Tensorlake sandbox did not start within 10 minutes".into()); + return Err(format!( + "Tensorlake {role} sandbox did not start within 10 minutes" + )); } tokio::time::sleep(self.config.poll_interval).await; - }; - self.set_phase(&sandbox.id, Phase::Launching).await; - self.publish_progress(&sandbox.id, LaunchProgress::VmRunning); - self.publish_progress(&sandbox.id, LaunchProgress::UploadingBundle); + } + } - let bundle = launch::build_launch_bundle(LaunchBundleInput { - sandbox, - config: &self.config, - tensorlake_sandbox_id: tensorlake_id, - identity, - gateway_ca_pem: self.gateway_ca_pem.as_deref().map(Vec::as_slice), - })?; - self.client - .write_file(&info, launch::BUNDLE_UPLOAD_PATH, bundle) - .await - .map_err(|error| format!("upload launch bundle: {error}"))?; - self.publish_progress(&sandbox.id, LaunchProgress::StartingLauncher); + /// 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, + info, &StartProcessRequest { command: launch::LAUNCHER_PATH.to_string(), args: vec![launch::BUNDLE_UPLOAD_PATH.to_string()], @@ -543,18 +698,15 @@ impl TensorlakeComputeDriver { }, ) .await - .map_err(|error| format!("start OpenShell launcher: {error}"))?; + .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" ); - if let Some(record) = self.records.lock().await.get_mut(&sandbox.id) { - record.launcher_pid = Some(launcher.pid); - } - self.set_phase(&sandbox.id, Phase::Running).await; - self.publish_progress(&sandbox.id, LaunchProgress::LauncherStarted); - Ok(()) + Ok(launcher.pid) } pub async fn get_sandbox(&self, sandbox_id: &str) -> Option { @@ -578,7 +730,7 @@ impl TensorlakeComputeDriver { } pub async fn delete_sandbox(&self, sandbox_id: &str) -> Result { - let tensorlake_id = { + 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); @@ -587,14 +739,17 @@ impl TensorlakeComputeDriver { let record = record.clone(); drop(records); self.emit_sandbox(&record); - record.tensorlake_id + (record.tensorlake_id, record.guard_tensorlake_id) }; - let deleted = self - .client - .delete_sandbox(&tensorlake_id) - .await - .map_err(|error| Status::unavailable(error.to_string()))?; - if !deleted { + let mut remaining = false; + for id in std::iter::once(&tensorlake_id).chain(guard_tensorlake_id.as_ref()) { + remaining |= self + .client + .delete_sandbox(id) + .await + .map_err(|error| Status::unavailable(error.to_string()))?; + } + if !remaining { self.forget(sandbox_id).await; } Ok(true) @@ -684,22 +839,14 @@ impl TensorlakeComputeDriver { .await .map_err(|error| format!("list Tensorlake sandboxes: {error}"))?; let mut records = self.records.lock().await; - for info in sandboxes { - let Some(sandbox_id) = info - .name - .as_deref() - .and_then(|name| name.strip_prefix(NAME_PREFIX)) - .filter(|id| !id.is_empty()) - else { + for (sandbox_id, workload, guard) in pair_by_name(&sandboxes) { + let Some(phase) = recovered_phase(workload, guard, self.config.topology) else { continue; }; - let phase = match observed_phase(&info) { - Some(Phase::Pending) => Phase::Failed { - reason: "DriverRestarted".into(), - message: "the Tensorlake driver restarted before this sandbox launched; delete and recreate it".into(), - }, - Some(phase) => phase, - None => continue, + // A guard VM whose workload VM is gone is still recorded, under + // the workload's name, so that delete can remove it. + let Some(anchor) = workload.or(guard) else { + continue; }; records.insert( sandbox_id.to_string(), @@ -708,11 +855,14 @@ impl TensorlakeComputeDriver { id: sandbox_id.to_string(), ..DriverSandbox::default() }, - tensorlake_id: info.sandbox_id.clone(), - tensorlake_name: info.name.clone().unwrap_or_default(), + tensorlake_id: workload + .map_or_else(|| anchor.sandbox_id.clone(), |info| info.sandbox_id.clone()), + tensorlake_name: tensorlake_name(sandbox_id), + guard_tensorlake_id: guard.map(|info| info.sandbox_id.clone()), identity: None, phase, launcher_pid: None, + guard_launcher_pid: None, }, ); } @@ -748,36 +898,105 @@ impl TensorlakeComputeDriver { .collect(); for (sandbox_id, record) in records { let info = observed.get(&record.tensorlake_id); - match reconcile(&record.phase, info) { + let guard_vm = record + .guard_tensorlake_id + .as_ref() + .map_or(GuardVm::NotUsed, |id| { + observed.get(id).map_or(GuardVm::Gone, GuardVm::Present) + }); + match reconcile(&record.phase, info, guard_vm) { Reconcile::Keep => {} Reconcile::Forget => self.forget(&sandbox_id).await, Reconcile::Set(next) => self.set_phase(&sandbox_id, next).await, } - if let (Some(info), Some(pid)) = (info, record.launcher_pid) - && record.phase == Phase::Running - && observed_phase(info) == Some(Phase::Running) - { - self.check_launcher(&sandbox_id, info, pid).await; + if record.phase != Phase::Running { + continue; + } + let launchers = [ + (info, record.launcher_pid, "workload"), + (guard_vm.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 its launcher has stopped. Without the + /// 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) { + 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()) { - warn!(%sandbox_id, ?failed, "OpenShell launcher stopped"); + 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, %error, "Tensorlake launcher status check failed"), + 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. +fn recovered_phase( + workload: Option<&SandboxInfo>, + guard: Option<&SandboxInfo>, + topology: Topology, +) -> 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, topology) { + (None, None, _) => return None, + (Some(Phase::Pending), _, _) | (_, Some(Phase::Pending), _) => restarted(), + (None, Some(_), _) => half("workload"), + (Some(_), None, Topology::Split) => half("guard"), + (Some(Phase::Suspended), _, _) | (_, Some(Phase::Suspended), _) => Phase::Suspended, + (Some(phase), _, _) => phase, + }) +} + #[derive(Debug, PartialEq, Eq)] enum Reconcile { Keep, @@ -785,32 +1004,85 @@ enum Reconcile { Set(Phase), } +/// What one poll saw of a sandbox's guard VM. +#[derive(Debug, Clone, Copy)] +enum GuardVm<'a> { + /// Combined topology: there is no guard VM. + NotUsed, + /// Split topology, but Tensorlake no longer lists the guard VM. + Gone, + Present(&'a SandboxInfo), +} + +impl<'a> GuardVm<'a> { + fn info(self) -> Option<&'a SandboxInfo> { + match self { + Self::Present(info) => Some(info), + Self::NotUsed | Self::Gone => None, + } + } +} + /// Decide how one poll observation changes a record. -fn reconcile(current: &Phase, info: Option<&SandboxInfo>) -> Reconcile { - match (current, info.and_then(observed_phase)) { +fn reconcile(current: &Phase, workload: Option<&SandboxInfo>, guard: GuardVm<'_>) -> Reconcile { + let workload_phase = workload.and_then(observed_phase); + // `None` when the topology has no guard VM; `Some(None)` when it is gone. + let guard_phase = match guard { + GuardVm::NotUsed => None, + GuardVm::Gone => Some(None), + GuardVm::Present(info) => Some(observed_phase(info)), + }; + let any_present = workload_phase.is_some() || matches!(guard_phase, Some(Some(_))); + match current { // Gone from Tensorlake while we delete it: finish the delete. - (Phase::Deleting, None) => Reconcile::Forget, + 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, _) - // Keep the current phase while a delete runs. - | (Phase::Deleting, Some(_)) - // A failed launch stays failed while the VM still exists. Nothing + | Phase::Pending + | Phase::Launching => return Reconcile::Keep, + // A failed launch stays failed while the VMs still exist. Nothing // will launch it again. - | (Phase::Failed { .. }, Some(Phase::Pending | Phase::Running)) => Reconcile::Keep, - (_, None) => Reconcile::Set(Phase::Failed { + Phase::Failed { .. } + if workload_phase + .as_ref() + .is_some_and(|phase| *phase != Phase::Suspended) + && guard_phase.as_ref().is_none_or(|phase| { + phase + .as_ref() + .is_some_and(|phase| *phase != Phase::Suspended) + }) => + { + return Reconcile::Keep; + } + _ => {} + } + let gone = |what: &str, info: Option<&SandboxInfo>| { + Reconcile::Set(Phase::Failed { reason: "TensorlakeTerminated".into(), message: format!( - "Tensorlake sandbox is no longer running{}", + "Tensorlake {what} sandbox is no longer running{}", info.map(failure_detail).unwrap_or_default() ), - }), - (_, Some(next)) => Reconcile::Set(next), + }) + }; + match (workload_phase, guard_phase) { + (None, _) => gone("workload", workload), + (Some(_), Some(None)) => gone("guard", guard.info()), + (Some(Phase::Suspended), _) | (_, Some(Some(Phase::Suspended))) => { + Reconcile::Set(Phase::Suspended) + } + (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>) -> Option { +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(), @@ -819,7 +1091,7 @@ fn launcher_failure(tensorlake_id: &str, process: Option<&ProcessInfo>) -> Optio Some(Phase::Failed { reason: "LauncherExited".into(), message: format!( - "the OpenShell launcher {outcome}; run `tl sbx logs {tensorlake_id}` for details" + "the OpenShell {role} launcher {outcome}; run `tl sbx logs {tensorlake_id}` for details" ), }) } @@ -1108,10 +1380,16 @@ mod tests { #[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), Reconcile::Keep); - assert_eq!(reconcile(&Phase::Launching, None), Reconcile::Keep); assert_eq!( - reconcile(&Phase::Pending, Some(&info("running"))), + reconcile(&Phase::Pending, None, GuardVm::NotUsed), + Reconcile::Keep + ); + assert_eq!( + reconcile(&Phase::Launching, None, GuardVm::NotUsed), + Reconcile::Keep + ); + assert_eq!( + reconcile(&Phase::Pending, Some(&info("running")), GuardVm::NotUsed), Reconcile::Keep ); } @@ -1123,31 +1401,174 @@ mod tests { message: "m".into(), }; for status in ["pending", "running"] { - assert_eq!(reconcile(&failed, Some(&info(status))), Reconcile::Keep); + let vm = info(status); + assert_eq!( + reconcile(&failed, Some(&vm), GuardVm::NotUsed), + Reconcile::Keep + ); + assert_eq!( + reconcile(&failed, Some(&vm), GuardVm::Present(&vm)), + Reconcile::Keep + ); } + // Once a VM is gone, the failure reason follows the VM. + assert!(matches!( + reconcile(&failed, None, GuardVm::NotUsed), + Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" + )); } #[test] fn reconcile_tracks_running_sandboxes() { - assert_eq!(reconcile(&Phase::Deleting, None), Reconcile::Forget); assert_eq!( - reconcile(&Phase::Deleting, Some(&info("running"))), + reconcile(&Phase::Deleting, None, GuardVm::NotUsed), + Reconcile::Forget + ); + assert_eq!( + reconcile(&Phase::Deleting, Some(&info("running")), GuardVm::NotUsed), Reconcile::Keep ); assert_eq!( - reconcile(&Phase::Running, Some(&info("suspended"))), + reconcile(&Phase::Running, Some(&info("suspended")), GuardVm::NotUsed), Reconcile::Set(Phase::Suspended) ); assert_eq!( - reconcile(&Phase::Suspended, Some(&info("running"))), + reconcile(&Phase::Suspended, Some(&info("running")), GuardVm::NotUsed), Reconcile::Set(Phase::Running) ); assert!(matches!( - reconcile(&Phase::Running, Some(&info("terminated"))), + reconcile(&Phase::Running, Some(&info("terminated")), GuardVm::NotUsed), Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" )); } + #[test] + fn reconcile_tracks_both_vms_of_a_split_sandbox() { + let running = info("running"); + let suspended = info("suspended"); + // Both present and running: keep running. + assert_eq!( + reconcile(&Phase::Running, Some(&running), GuardVm::Present(&running)), + Reconcile::Set(Phase::Running) + ); + // Delete finishes only when both are gone. + assert_eq!( + reconcile(&Phase::Deleting, None, GuardVm::Present(&running)), + Reconcile::Keep + ); + assert_eq!( + reconcile(&Phase::Deleting, None, GuardVm::Gone), + 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), GuardVm::Gone) + else { + panic!("a lost guard VM must fail the sandbox"); + }; + assert_eq!(reason, "TensorlakeTerminated"); + assert!(message.contains("guard")); + // A suspended guard VM suspends the sandbox. + assert_eq!( + reconcile( + &Phase::Running, + Some(&running), + GuardVm::Present(&suspended) + ), + Reconcile::Set(Phase::Suspended) + ); + } + + 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 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, Topology::Split), + Some(Phase::Running) + ); + // A workload VM without its guard: fine in the combined topology, + // broken in the split topology. + let (_, workload, guard) = pairs[1]; + assert_eq!( + recovered_phase(workload, guard, Topology::Combined), + Some(Phase::Running) + ); + assert!(matches!( + recovered_phase(workload, guard, Topology::Split), + 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, Topology::Split), + 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")), + Topology::Split + ), + Some(Phase::Failed { reason, .. }) if reason == "DriverRestarted" + )); + assert_eq!( + recovered_phase( + Some(&named("openshell-e", "terminated")), + None, + Topology::Split + ), + 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 @@ -1158,18 +1579,18 @@ mod tests { #[test] fn launcher_failure_reports_stopped_launchers() { assert_eq!( - launcher_failure("tl1", Some(&process("running", None))), + launcher_failure("tl1", Some(&process("running", None)), "workload"), None ); let Some(Phase::Failed { reason, message }) = - launcher_failure("tl1", Some(&process("exited", Some(1)))) + 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("exited with status 1")); + assert!(message.contains("guard launcher exited with status 1")); assert!(message.contains("tl sbx logs tl1")); - assert!(launcher_failure("tl1", None).is_some()); + assert!(launcher_failure("tl1", None, "workload").is_some()); } #[test] diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs index 4103fe996a..0688d898da 100644 --- a/crates/openshell-driver-tensorlake/src/launch.rs +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -1,23 +1,30 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Launch bundle for the combined Tensorlake topology. +//! Launch bundles for the Tensorlake topologies. //! -//! The guard (`openshell-supervisor`) and the starter (`openshell-sandbox`) -//! run in the same Tensorlake VM. The driver builds one tar archive per -//! sandbox generation. The in-image launcher extracts it as root, so each file -//! keeps the owner and mode set here: +//! 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 launcher starts the workload in a new network namespace that has only -//! loopback. This is the outer fence: the workload has no network path except -//! the authenticated boundary channel, even if the guard exits. +//! Split topology (default): 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. +//! +//! Combined topology: one VM gets both sides. The launcher starts the +//! workload in a network namespace that has only loopback. use std::collections::{BTreeMap, HashMap}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::path::PathBuf; use openshell_core::proto::compute::v1::DriverSandbox; @@ -39,6 +46,22 @@ pub const LAUNCHER_PATH: &str = "/opt/openshell/bin/openshell-tensorlake-launch" /// 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 SOCKET_PATH: &str = "/.openshell/channel/sandbox/control.sock"; @@ -55,6 +78,31 @@ 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 { + /// Workload and guard in one VM. + Combined, + /// 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::Combined => "combined", + Self::Workload => "workload", + Self::Guard => "guard", + } + } +} fn invalid(error: impl std::fmt::Display) -> String { error.to_string() @@ -93,7 +141,9 @@ pub fn resolve_identity( openshell_core::sandbox_env::DEFAULT_SANDBOX_GID, "group", )?; - if uid == SUPERVISOR_UID || gid == SUPERVISOR_GID { + 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" )); @@ -107,30 +157,42 @@ pub fn resolve_identity( .map_err(invalid) } -/// Evidence for the outer fence that the launcher builds. The driver cannot -/// inspect the VM, so the evidence names the launch recipe it requested. +/// Evidence for the outer fence the driver requested. The driver cannot +/// inspect the VM, so the evidence names the recipe. /// -/// A loopback-only network namespace has no route out. Egress needs a -/// mediated decision, revocation takes effect at the guard, and guard loss -/// leaves the namespace without a path. +/// Split: 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. Combined: a loopback-only network namespace has no route +/// out. Either way 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, - workload_network_namespace: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + guard_tensorlake_sandbox_id: Option<&'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: Option<&str>, generation: &str, ) -> Result { - if tensorlake_sandbox_id.is_empty() { + if tensorlake_sandbox_id.is_empty() || guard_tensorlake_sandbox_id == Some("") { return Err("Tensorlake sandbox ID is required for provisioning evidence".to_string()); } + let (topology, workload_network) = match guard_tensorlake_sandbox_id { + Some(_) => ("split", "private-netns-veth-to-forwarder-no-egress"), + None => ("combined", "private-loopback-only"), + }; let evidence = TensorlakeOuterFenceEvidence { + topology, tensorlake_sandbox_id, - workload_network_namespace: "private-loopback-only", + guard_tensorlake_sandbox_id, + workload_network, launcher: LAUNCHER_PATH, }; let encoded = serde_json::to_vec(&evidence).map_err(invalid)?; @@ -203,10 +265,10 @@ fn supervisor_environment( env::PROXY_TLS_DIR.to_string(), format!("{SUPERVISOR_RUN_DIR}/proxy-tls"), ), - ( - env::NETWORK_RUNTIME_CAPABILITIES.to_string(), - env::POLICY_DNS_TRANSPARENT_TCP_CAPABILITY.to_string(), - ), + // 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), @@ -261,17 +323,31 @@ fn nul_list>(items: I) -> Vec { pub struct LaunchBundleInput<'a> { pub sandbox: &'a DriverSandbox, pub config: &'a TensorlakeComputeConfig, + /// The workload VM (split) or the only VM (combined). pub tensorlake_sandbox_id: &'a str, + /// The guard VM. `None` builds the combined bundle. + pub guard_tensorlake_id: Option<&'a str>, pub identity: &'a ResolvedWorkloadIdentity, pub gateway_ca_pem: Option<&'a [u8]>, } -/// Build the launch bundle tar archive. Paths are relative to `/`. -pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, String> { +/// The tar archives for one sandbox generation. Paths are relative to `/`. +#[derive(Debug)] +pub struct LaunchBundles { + /// Uploaded to the workload VM, or to the only VM in the combined + /// topology, where it also carries the guard files. + pub workload: Vec, + /// Uploaded to the guard VM. `None` in the combined topology. + pub guard: Option>, +} + +/// 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; @@ -293,8 +369,9 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri .runtime_generation .to_string(); let tls = generate_sandbox_tls_material(session_id).map_err(invalid)?; - let provisioning_evidence = provisioning_evidence(tensorlake_sandbox_id, &generation)?; - let resource_claims = BTreeMap::from([ + 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(), @@ -304,6 +381,9 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri identity.resource_digest.clone(), ), ]); + if let Some(guard) = guard_tensorlake_id { + resource_claims.insert("tensorlake.guard_sandbox_id".to_string(), guard.to_string()); + } let verification_keys = launch_authentication .verification_keys .iter() @@ -317,6 +397,38 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri }) .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, transport) = if guard_tensorlake_id.is_some() { + ( + BoundaryListener::TlsTcp { + address: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), WORKLOAD_LISTEN_PORT), + tls: server_tls, + }, + SandboxTransport::Tcp { + authority: format!("{tensorlake_sandbox_id}:{WORKLOAD_LISTEN_PORT}"), + addresses: vec![SocketAddr::new( + IpAddr::V4(Ipv4Addr::LOCALHOST), + GUARD_TUNNEL_PORT, + )], + }, + ) + } else { + ( + BoundaryListener::Unix { + socket_path: PathBuf::from(SOCKET_PATH), + tls: server_tls, + }, + SandboxTransport::Unix { + socket_path: PathBuf::from(SOCKET_PATH), + }, + ) + }; let boundary = BoundaryConfig { boundary_id: sandbox.id.clone(), generation: generation.clone(), @@ -325,13 +437,7 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri auth_epoch: launch_authentication.supervisor.auth_epoch, gateway_id: launch_authentication.gateway_id.clone(), verification_keys, - listener: BoundaryListener::Unix { - socket_path: PathBuf::from(SOCKET_PATH), - tls: SandboxTlsServerConfig { - certificate_chain_path: PathBuf::from(SERVER_CERT_PATH), - private_key_path: PathBuf::from(SERVER_KEY_PATH), - }, - }, + listener, resource_claims: resource_claims.clone(), resource_claim_files: BTreeMap::new(), workload_identity: identity.clone(), @@ -342,9 +448,7 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri boundary_id: sandbox.id.clone(), generation, session_id, - transport: SandboxTransport::Unix { - socket_path: PathBuf::from(SOCKET_PATH), - }, + transport, tls: SandboxTlsClientConfig { server_name: tls.server_name.clone(), trust_anchor_pem: tls.trust_anchor_pem.clone(), @@ -354,19 +458,56 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri 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)?; + if guard_tensorlake_id.is_some() { + 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: Some(guard_archive.finish()?), + }) + } else { + add_guard_files(&mut workload_archive, &guard_files)?; + add_params(&mut workload_archive, Role::Combined, identity)?; + Ok(LaunchBundles { + workload: workload_archive.finish()?, + guard: None, + }) + } +} + +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); - let guard = Owner::new(SUPERVISOR_UID, SUPERVISOR_GID); - let root = Owner::new(0, 0); - let mut archive = Archive::default(); - archive.directory(".openshell", 0o755, root)?; - archive.directory(".openshell/channel", 0o755, root)?; + 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)?, + &serde_json::to_vec(boundary).map_err(invalid)?, )?; archive.file( SERVER_CERT_PATH, @@ -379,57 +520,140 @@ pub fn build_launch_bundle(input: LaunchBundleInput<'_>) -> Result, Stri 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(&runtime_descriptor).map_err(invalid)?, + &serde_json::to_vec(files.runtime_descriptor).map_err(invalid)?, )?; archive.file( AUTH_BUNDLE_PATH, 0o600, guard, - &serde_json::to_vec(&launch_authentication.supervisor).map_err(invalid)?, + &serde_json::to_vec(files.auth_bundle).map_err(invalid)?, )?; - if !spec.sandbox_token.is_empty() { + if !files.sandbox_token.is_empty() { archive.file( SANDBOX_TOKEN_PATH, 0o600, guard, - format!("{}\n", spec.sandbox_token).as_bytes(), + format!("{}\n", files.sandbox_token).as_bytes(), )?; } - if let Some(ca) = gateway_ca_pem { + if let Some(ca) = files.gateway_ca_pem { archive.file(GATEWAY_CA_PATH, 0o600, guard, ca)?; } - let environment = supervisor_environment(sandbox, config, gateway_ca_pem.is_some())?; archive.file( SUPERVISOR_ENV_PATH, 0o600, - root, + ROOT, &nul_list( - environment - .into_iter() + files + .environment + .iter() .map(|(key, value)| format!("{key}={value}")), ), )?; archive.file( SUPERVISOR_ARGS_PATH, 0o600, - root, + ROOT, &nul_list(supervisor_args()), + ) +} + +/// The Tensorlake key and the `tl sbx tunnel` arguments for the tunnel +/// identity in the guard VM. +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()); + } + archive.directory(TUNNEL_DIR, 0o700, tunnel)?; + archive.file( + TUNNEL_ENV_PATH, + 0o600, + tunnel, + &nul_list([format!("TENSORLAKE_API_KEY={}", config.api_key)]), )?; + 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(), + ] +} - archive.directory(".openshell/launch", 0o700, root)?; - let params = format!( - "WORKLOAD_UID={}\nWORKLOAD_GID={}\nSUPERVISOR_UID={SUPERVISOR_UID}\nSUPERVISOR_GID={SUPERVISOR_GID}\nWORKSPACE={WORKSPACE}\nSUPERVISOR_RUN_DIR={SUPERVISOR_RUN_DIR}\n", - identity.uid, identity.gid, - ); - archive.file(LAUNCH_PARAMS_PATH, 0o600, root, params.as_bytes())?; - archive.finish() +/// 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()); + if matches!(role, Role::Combined | Role::Workload) { + writeln!( + params, + "WORKLOAD_UID={}\nWORKLOAD_GID={}", + identity.uid, identity.gid + ) + .expect("writing to a String cannot fail"); + } + if matches!(role, Role::Combined | Role::Guard) { + writeln!( + params, + "SUPERVISOR_UID={SUPERVISOR_UID}\nSUPERVISOR_GID={SUPERVISOR_GID}\nSUPERVISOR_RUN_DIR={SUPERVISOR_RUN_DIR}" + ) + .expect("writing to a String cannot fail"); + } + if role == Role::Workload { + writeln!( + params, + "FORWARDER_UID={FORWARDER_UID}\nFORWARDER_GID={FORWARDER_GID}\nWORKLOAD_LISTEN_PORT={WORKLOAD_LISTEN_PORT}\nWORKLOAD_FORWARD_PORT={WORKLOAD_FORWARD_PORT}" + ) + .expect("writing to a String cannot fail"); + } + if role == Role::Guard { + writeln!( + params, + "TUNNEL_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)] @@ -538,13 +762,16 @@ mod tests { #[test] fn provisioning_evidence_binds_generation() { - let evidence = provisioning_evidence("tl-1", "gen-1").unwrap(); + let evidence = provisioning_evidence("tl-1", None, "gen-1").unwrap(); assert!(evidence.validate("gen-1").is_ok()); assert!(evidence.validate("gen-2").is_err()); - let other = provisioning_evidence("tl-2", "gen-1").unwrap(); + let other = provisioning_evidence("tl-2", None, "gen-1").unwrap(); assert_ne!(evidence.evidence_digest, other.evidence_digest); - assert!(provisioning_evidence("", "gen-1").is_err()); - assert!(provisioning_evidence("tl-1", "").is_err()); + assert!(provisioning_evidence("", None, "gen-1").is_err()); + assert!(provisioning_evidence("tl-1", None, "").is_err()); + assert!(provisioning_evidence("tl-1", Some(""), "gen-1").is_err()); + let split = provisioning_evidence("tl-1", Some("tl-1-guard"), "gen-1").unwrap(); + assert_ne!(split.evidence_digest, evidence.evidence_digest); } #[test] @@ -566,10 +793,11 @@ mod tests { let sandbox = sandbox_with_identity("", ""); let identity = resolve_identity(&sandbox, "img").unwrap(); let config = crate::config::tests::test_config(); - let result = build_launch_bundle(LaunchBundleInput { + let result = build_launch_bundles(LaunchBundleInput { sandbox: &sandbox, config: &config, tensorlake_sandbox_id: "tl-1", + guard_tensorlake_id: None, identity: &identity, gateway_ca_pem: None, }); @@ -622,24 +850,40 @@ mod tests { entries } - #[test] - fn bundle_separates_workload_and_guard_material() { + 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 combined_bundle_separates_workload_and_guard_material() { + let sandbox = launch_sandbox(); let identity = resolve_identity(&sandbox, "img").unwrap(); let config = crate::config::tests::test_config(); - let bytes = build_launch_bundle(LaunchBundleInput { + let bundles = build_launch_bundles(LaunchBundleInput { sandbox: &sandbox, config: &config, tensorlake_sandbox_id: "tl-1", + guard_tensorlake_id: None, identity: &identity, gateway_ca_pem: Some(b"ca"), }) .unwrap(); - let entries = read_entries(&bytes); + assert!(bundles.guard.is_none()); + let entries = read_entries(&bundles.workload); // Workload side: bootstrap and boundary key only, owned by the workload. let (mode, uid, bootstrap) = &entries[BOOTSTRAP_PATH.trim_start_matches('/')]; @@ -664,10 +908,95 @@ mod tests { assert!(env.contains(&format!( "OPENSHELL_SANDBOX_TOKEN_FILE={SANDBOX_TOKEN_PATH}\0" ))); + assert!(env.contains("OPENSHELL_NETWORK_RUNTIME_CAPABILITIES=\0")); assert!(!env.contains("sandbox.jwt.value")); let (_, _, params) = &entries[LAUNCH_PARAMS_PATH.trim_start_matches('/')]; - assert!(String::from_utf8_lossy(params).contains("WORKLOAD_UID=1000\n")); + let params = String::from_utf8_lossy(params); + assert!(params.contains("ROLE=combined\n")); + assert!(params.contains("WORKLOAD_UID=1000\n")); + assert!(params.contains("SUPERVISOR_UID=65534\n")); + assert!(!params.contains("TUNNEL_UID")); + assert!(!entries.contains_key(TUNNEL_ENV_PATH.trim_start_matches('/'))); + let bootstrap = String::from_utf8_lossy(&entry(&entries, BOOTSTRAP_PATH).2); + assert!(bootstrap.contains(SOCKET_PATH)); + } + + #[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(); + let bundles = build_launch_bundles(LaunchBundleInput { + sandbox: &sandbox, + config: &config, + tensorlake_sandbox_id: "tl-1", + guard_tensorlake_id: Some("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.as_deref().unwrap()); + 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\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] diff --git a/crates/openshell-driver-tensorlake/src/main.rs b/crates/openshell-driver-tensorlake/src/main.rs index 845e8d9358..fc2d8f54f5 100644 --- a/crates/openshell-driver-tensorlake/src/main.rs +++ b/crates/openshell-driver-tensorlake/src/main.rs @@ -10,7 +10,10 @@ 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_MEMORY_MB}; +use openshell_driver_tensorlake::config::{ + DEFAULT_API_URL, DEFAULT_CPUS, DEFAULT_GUARD_CPUS, DEFAULT_GUARD_MEMORY_MB, DEFAULT_MEMORY_MB, + Topology, +}; use openshell_driver_tensorlake::{ ComputeDriverService, TensorlakeComputeConfig, TensorlakeComputeDriver, }; @@ -56,10 +59,27 @@ struct Args { #[arg(long, env = "TENSORLAKE_API_KEY", hide_env_values = true)] tensorlake_api_key: String, - /// Registered Tensorlake image with the `OpenShell` guard and launcher. + /// Registered Tensorlake image with the `OpenShell` runtime and launcher. #[arg(long, env = "OPENSHELL_SANDBOX_IMAGE")] sandbox_image: String, + /// Where the guard runs. `split` puts it in its own VM and reaches the + /// workload VM through a Tensorlake tunnel, so credentials never enter + /// the workload VM. `combined` shares one VM; test credentials only. + #[arg(long, env = "OPENSHELL_TENSORLAKE_TOPOLOGY", default_value = "split")] + topology: Topology, + + /// 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, @@ -120,6 +140,10 @@ async fn main() -> Result<()> { .collect(), poll_interval: Duration::from_secs(args.poll_interval_secs.max(1)), log_level: args.log_level, + topology: args.topology, + guard_image: args.guard_image, + guard_cpus: args.guard_cpus, + guard_memory_mb: args.guard_memory_mb, }; let driver = TensorlakeComputeDriver::new(config, args.admission_config_json) .await From 75fd3ef822dcbe290c2c3a8acf8650de6f186204 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 14:41:06 -0500 Subject: [PATCH 19/31] docs(driver-tensorlake): document the split topology Describe the two-VM layout, the tunnel and forwarder path, the trust model, the new flags, and the end-to-end results measured on Tensorlake Cloud, including the three findings that shaped the design. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 201 ++++++---- .../docs/split-topology.md | 345 ++++++++++-------- docs/how-it-works/sandboxes/tensorlake.mdx | 61 +++- 3 files changed, 374 insertions(+), 233 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index c623350187..cb6319c028 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -19,12 +19,16 @@ 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. -In this version, the guard and the workload share one VM. The guard keeps -the gateway and provider credentials inside that VM, so a root user in the -VM could read them. Use test credentials only. The plan to move the guard -out of the workload VM, and the one Tensorlake capability it needs, is in +By default the guard and the workload run in two different VMs (the +"split" topology). 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. The design and its measurements are in [docs/split-topology.md](docs/split-topology.md). +With `--topology combined`, both run in one VM. That is cheaper, but a root +user in that VM can read the guard's credentials. Use it with test +credentials only. + The user-facing page is [Tensorlake Runtime](../../docs/how-it-works/sandboxes/tensorlake.mdx). @@ -34,62 +38,87 @@ The user-facing page is openshell CLI ──► gateway ──Unix socket──► openshell-driver-tensorlake ──HTTPS──► Tensorlake API ▲ │ the guard calls the gateway (outbound only) - ┌──────────────────┴──────── Tensorlake sandbox (VM) ───────────────────┐ - │ ┌───────────────── OpenShell sandbox ───────────────────────────────┐ │ - │ │ guard: openshell-supervisor (uid 65534, holds credentials) │ │ - │ │ ▲ TLS over /.openshell/channel/sandbox/control.sock │ │ - │ │ workload: openshell-sandbox (uid 1000, private network with │ │ - │ │ only loopback) ──► agent processes │ │ - │ └───────────────────────────────────────────────────────────────────┘ │ - └───────────────────────────────────────────────────────────────────────┘ + ┌──────────────────┴── 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 a VM and returns at once. It does - not wait for the VM. -2. In the background, the driver waits until the VM reports `running`. -3. The driver packs the files the guard and the workload need into one - archive. Each file in the archive has its owner and permissions set. - The driver uploads the archive with the Tensorlake file API and starts - `/opt/openshell/bin/openshell-tensorlake-launch` as root with the - Tensorlake process API. -4. The launch script unpacks the archive and deletes it. It starts the - workload in a private network that has only loopback. Then it starts - the guard as user 65534, with no special rights. -5. The driver reports the sandbox as ready when the launch script starts. - 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 the launch script is still - running. If it stopped, the driver marks the sandbox as failed with - reason `LauncherExited` and the exit status. Tensorlake does not - restart the script. +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. In both topologies 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. -### Where the files live in the VM +With `--topology combined`, step 1 creates one VM, step 3 packs one +archive, and the launch script starts the workload in a private network +namespace that has only loopback, then the guard, in that VM. -| Path | Owner | Contents | -|---|---|---| -| `/.openshell/channel/sandbox/` | workload | bootstrap file and TLS key for the channel to the guard | -| `/.openshell/supervisor/` (mode 0700) | guard | auth bundle, sandbox token, gateway CA, runtime descriptor | -| `/.openshell/supervisor/env`, `args` | root | the guard's environment and arguments | +### Where the files live in the VMs + +| Path | VM | Owner | Contents | +|---|---|---|---| +| `/.openshell/channel/sandbox/` | workload | workload | bootstrap file 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 | the Tensorlake key and the `tl sbx tunnel` arguments | +| `/.openshell/launch/params` | both | root | the role and the identities for the launch script | -The workload user cannot read the guard's files. Root in the VM can. +In the combined topology all of these except the tunnel files live in the +one VM. ### The outer fence -The launch script runs the workload in a network that has only loopback. -The only way out is the channel to the guard. The driver writes this launch -recipe into the sandbox's config, so the gateway knows which fence this -sandbox got. The driver cannot look inside the VM to confirm that the fence -is in place. +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. -You can add a second wall with `--allow-out`. It limits where the guard -itself can connect. See [Run the driver](#run-the-driver). +`--allow-out` limits where the guard VM itself can connect. See +[Run the driver](#run-the-driver). ## Build the images @@ -99,9 +128,13 @@ Images built this way start fast. | Image | Default name | Contents | |---|---|---| -| Sandbox | `openshell-tensorlake` | guard, workload, launch script | +| 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 ``` @@ -196,9 +229,12 @@ openshell-gateway --compute-driver tensorlake \ | `--tensorlake-api-url` | `TENSORLAKE_API_URL` | `https://sandbox.tensorlake.ai` | | `--tensorlake-api-key` | `TENSORLAKE_API_KEY` | required | | `--sandbox-image` | `OPENSHELL_SANDBOX_IMAGE` | required | +| `--topology` | `OPENSHELL_TENSORLAKE_TOPOLOGY` | `split`; `combined` shares one VM | +| `--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) | +| `--allow-out` | `OPENSHELL_TENSORLAKE_ALLOW_OUT` | empty (internet on for the guard VM) | | `--poll-interval-secs` | `OPENSHELL_TENSORLAKE_POLL_INTERVAL_SECS` | 3 | The guard trusts only the certificates in `--gateway-tls-ca`. It does not @@ -211,7 +247,10 @@ pause a sandbox that is still working. Keep the default `0`, which uses the longest timeout your plan allows. When you set `--allow-out`, the driver turns off internet access for the -VM and allows only the hosts you listed plus the gateway host. +VM that runs the guard and allows only the hosts you listed, the gateway +host, and in the split topology the Tensorlake host that the tunnel talks +to. The workload VM in the split topology always has internet access off +with an empty allow list. ## Run the control plane on Tensorlake @@ -330,33 +369,54 @@ workloads in it. - The driver keeps launch state in memory. After a driver restart, it finds running sandboxes again by their Tensorlake names (`openshell-`). Sandboxes that had not finished launching are reported as failed. -- Anyone with access to your Tensorlake account can run - `tl sbx exec --user root` and get around OpenShell. +- Anyone with access to your Tensorlake project can run + `tl sbx exec --user root` in the guard VM and read its credentials, or in + the workload VM and get around OpenShell policy. Keep the control plane + in a project of its own. +- Each guard VM holds a Tensorlake API key for its tunnel. That key can + open tunnels to any sandbox in the project. +- The split topology uses two Tensorlake VMs per sandbox. ## Verified on Tensorlake -The unit tests cover the archive layout, request mapping, and status -mapping. An end-to-end run (create a sandbox, run a command, read its -output) confirmed that: - -- the VM kernel supports Landlock and seccomp, and allows `unshare --net`; -- 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, which forwards the - calls to the plain HTTP/2 backend; -- image builds accept the multi-stage Dockerfiles and the `--public` flag; -- the Tensorlake dataplane supports the file and process APIs, exposed - ports, and managed processes. +The unit tests cover the archive layout, request mapping, pairing, and +status mapping. End-to-end runs on Tensorlake Cloud confirmed: + +- Split topology (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`. +- Both topologies: 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. + +Three findings shaped the split topology. 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, which also fixes policy +enforcement in the combined topology. And the transparent TCP capability +is for guards that share the workload's network namespace, so this driver +no longer grants it. ## Still to confirm - The port proxy keeps a long-lived connection open, and the idle timeout does not pause a sandbox whose only traffic is the guard's outgoing session. -- The conformance suite in `tests/suites/conformance` passes: lifecycle, - file transfer, and policy enforcement. -- A launch script exit is reported as `LauncherExited`, and a driver - restart recovers running sandboxes. +- The conformance suite in `tests/suites/conformance` passes: lifecycle and + file transfer. +- A driver restart recovers running sandbox pairs. +- The combined topology end to end after the PID namespace change. +- Which Tensorlake hosts the tunnel needs, so `--allow-out` can be tight on + the guard VM. ## Test runbook @@ -611,6 +671,7 @@ passes, because a published version cannot be replaced. - Stop and start. - GPU. -- The split topology in [docs/split-topology.md](docs/split-topology.md), - so production credentials never enter a workload VM. It is blocked on a - raw TCP path between Tensorlake sandboxes. +- 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. diff --git a/crates/openshell-driver-tensorlake/docs/split-topology.md b/crates/openshell-driver-tensorlake/docs/split-topology.md index 098e1ff4d2..eec882e23a 100644 --- a/crates/openshell-driver-tensorlake/docs/split-topology.md +++ b/crates/openshell-driver-tensorlake/docs/split-topology.md @@ -1,156 +1,213 @@ -# Split topology: the guard outside the workload VM +# Split topology: the guard in its own VM -Status: design. Not implemented. It needs one Tensorlake capability that is -not confirmed yet, listed under [What Tensorlake must provide](#what-tensorlake-must-provide). +Status: implemented as the default topology (`--topology split`) and +verified end to end on Tensorlake Cloud on 2026-10-20, including policy +enforcement with binary identity. The combined topology +(`--topology combined`) stays for tests and for accounts that cannot afford +two VMs per sandbox. ## Problem -Today the guard (`openshell-supervisor`) and the workload (`openshell-sandbox`) -share one Tensorlake VM. The guard holds the gateway session token and the -provider credentials. A root user in that VM can read them, and anyone with -access to the Tensorlake project can become root with `tl sbx exec --user -root`. So the driver is safe for test credentials only. +In the combined topology the guard (`openshell-supervisor`) and the workload +(`openshell-sandbox`) share one Tensorlake VM. The guard holds the gateway +session token and the provider credentials. The workload cannot read them in +normal operation: it runs as a different user, with `no_new_privs`, in a +network namespace that has only loopback. But one kernel exploit in that VM +gives the agent everything. That is container-grade separation. The VM +driver (`openshell-driver-vm`) gives hypervisor-grade separation, because its +guard runs outside the guest. This document describes how the Tensorlake +driver gets the same property. -The VM driver (`openshell-driver-vm`) does not have this gap. Its guard runs -on the gateway host and reaches the guest over a vsock channel. Credentials -never enter the VM. This document describes how to get the same property on -Tensorlake. +## Design -## What the protocol already supports - -The sandbox protocol between the guard and the workload is TLS with keys that -the driver creates for each sandbox generation. It does not depend on a Unix -socket. The shared types in `openshell-sandbox-backend` and `openshell-core` -offer three transports: - -| Side | Type | Variants | -|---|---|---| -| Workload listens | `BoundaryListener` | `Unix`, `TlsTcp { address }`, `Vsock` | -| Guard connects | `SandboxTransport` | `Unix`, `Tcp { authority, addresses }`, `Vsock` | - -The VM driver uses `Vsock`. The Tensorlake driver uses `Unix` today. The -split topology uses `TlsTcp` on the workload side and `Tcp` on the guard side. -`Tcp.addresses` must be concrete `IP:port` pairs; a hostname is not accepted. -No change to `openshell-supervisor` or `openshell-sandbox` is needed. +Two Tensorlake sandboxes per OpenShell sandbox: -## Two placements +| Tensorlake sandbox | Runs | Network | Holds | +|---|---|---|---| +| `openshell-` (workload VM) | `openshell-sandbox` and the agent in a private network namespace, plus a tunnel forwarder | Internet off, empty allow list. No outbound path at all. | Its own channel key. No gateway or provider secret. | +| `openshell--guard` (guard VM) | `openshell-supervisor` and a `tl` tunnel | Default internet, or `--allow-out` plus the gateway and Tensorlake hosts | Gateway token, provider credentials, a Tensorlake API key for the tunnel | -Both placements move the guard out of the workload VM. They differ in how -many guard processes share one VM. +``` + control sandbox guard VM (trusted) workload VM (untrusted) +┌───────────────┐ HTTPS ┌──────────────────────────┐ ┌──────────────────────────────────────┐ +│ gateway ◄─────┼────────┼─ openshell-supervisor │ │ 127.0.0.1:8443 socat forwarder │ +│ driver ─► API │ │ │ OpenShell TLS │ WSS to │ │ veth 169.254.77.1 -> .2:8444 │ +└───────────────┘ │ ▼ │ proxy │ ┌──▼── netns openshell-workload ────┐│ + │ 127.0.0.1:18443 tunnel ──┼───────►│ │ openshell-sandbox :8444 TLS ││ + └──────────────────────────┘ │ │ └─► agent processes (lo only) ││ + │ └───────────────────────────────────┘│ + └──────────────────────────────────────┘ +``` -### A. Guard in the control sandbox (recommended first) +The guard dials `127.0.0.1:18443` in its own VM. The `tl sbx tunnel` process +there carries the bytes to the Tensorlake sandbox proxy over a WebSocket, +and the proxy delivers them to `127.0.0.1:8443` in the workload VM. A +`socat` forwarder accepts them there and connects into the workload's +network namespace over a veth link, from `169.254.77.1` to the runtime at +`169.254.77.2:8444`. The tunnel and the forwarder do not inspect the bytes. +OpenShell's own TLS handshake runs end to end between guard and workload, +with the per-generation certificate the driver issued. + +The forwarder exists because the sandbox runtime rejects boundary peers +that are loopback or share its own address (`reject_workload_tcp_peer` in +`openshell-sandbox`), and the Tensorlake tunnel always delivers to loopback. +Measured: the runtime reset every tunnel connection until the forwarder +gave it a veth peer. The namespace also keeps the workload's loopback as +empty as in the combined topology, so the workload cannot reach the VM's +own SSH daemon or the forwarder. + +This is the same shape as the Kubernetes driver: one guard pod per workload +pod, a TLS listener in the workload, a NetworkPolicy that gives the workload +no egress. Tensorlake's network policy is the outer fence here. -The control sandbox already runs the gateway and the driver. It holds the -Tensorlake key, so it is already the trusted component. Run one -`openshell-supervisor` process per sandbox inside it, the same way the VM -driver runs one supervisor per sandbox on the gateway host. +## What the protocol already supports -``` - control sandbox (trusted) workload sandbox (untrusted) -┌─────────────────────────────────┐ ┌──────────────────────────┐ -│ gateway ◄── loopback ── guard ──┼── TLS/TCP ──► openshell-sandbox │ -│ driver ──► Tensorlake API │ │ └─► agent processes │ -└─────────────────────────────────┘ └──────────────────────────┘ -``` +The sandbox protocol does not depend on a Unix socket. The shared types in +`openshell-sandbox-backend` and `openshell-core` offer three transports: -- The guard dials the gateway on loopback. The public gateway URL is still - needed for users, but not for guards. The idle-timeout problem in the README - goes away for the workload VM, because the guard's connection to it is - incoming traffic. -- The workload VM gets a Tensorlake network policy with - `allow_internet_access: false` and an empty `allow_out`. It needs no - egress at all: the workload's connections travel over the boundary channel - to the guard, which applies policy and connects upstream. This network - policy is the outer fence, and the driver can record it as fence evidence - from the API response rather than from a launch recipe it cannot inspect. -- One image: the sandbox image keeps only `openshell-sandbox` and a smaller - launch script. The control image already has the gateway and the driver and - gains `openshell-supervisor`. -- The driver spawns and reaps the supervisor processes. The VM driver's - `spawn_host_supervisor` in `crates/openshell-driver-vm/src/driver.rs` is the - model: an environment and argument list, a run directory per sandbox, and a - wait on the child. - -The cost is that the control sandbox concentrates privilege. It does today -already. Keep it in its own Tensorlake project. - -### B. One guard VM per sandbox - -Create two Tensorlake sandboxes per OpenShell sandbox: `openshell-` for -the workload and `openshell--guard` for the guard. The guard VM runs from a -small guard image and dials the gateway over the public URL as today. - -This keeps the control sandbox small and gives each guard its own kernel. It -doubles the VM count and the boot time, needs a second image, and needs -pairwise recovery after a driver restart. Do it only if placement A proves -too concentrated. - -## Driver changes for placement A - -1. **Launch bundle.** Split `launch::build_launch_bundle` into a workload - bundle (bootstrap, server certificate and key, launch parameters) and a - guard bundle (runtime descriptor, auth bundle, sandbox token, gateway CA). - Only the workload bundle is uploaded. The guard bundle is written to a - private directory in the control sandbox, mode 0700, owned by the driver - user. -2. **Listener.** The bootstrap's `BoundaryListener` becomes - `TlsTcp { address: 0.0.0.0: }`. The launch script no longer creates a - network namespace. It starts `openshell-sandbox launch-capability-free` - directly. -3. **Transport.** The runtime descriptor's `SandboxTransport` becomes - `Tcp { authority: "openshell-", addresses: [:] }`. - The driver must know the workload VM's address when the VM reports - `running`. See the next section. -4. **Supervisor process.** After the launcher starts, the driver spawns - `openshell-supervisor` in the control sandbox with the guard bundle. It - records the child in the sandbox `Record` and treats child exit the same as - `LauncherExited` today. -5. **Network policy.** `CreateSandboxRequest.network` is always set for the - workload VM: `allow_internet_access: false`, `allow_out: []`. The - `--allow-out` flag then applies to the control sandbox, not to workload - VMs, and can be removed from the driver. -6. **Fence evidence.** Replace `TensorlakeOuterFenceEvidence.workload_network_namespace` - with the applied Tensorlake network policy. -7. **Recovery.** On restart, the driver finds workload VMs by name as today, - and restarts a supervisor for each one from the saved guard bundle. Guard - bundles therefore must survive a driver restart, which they do in the - control sandbox's `/var/lib/openshell`. -8. **Control image.** Add `openshell-supervisor` from the published - supervisor image and `ca-certificates` for upstream TLS. - -Steps 1 to 3 are pure Rust changes with unit tests. Steps 4 to 8 need a -Tensorlake account to test end to end. - -## What Tensorlake must provide - -The guard must open a raw TCP connection to the workload VM and complete a -TLS handshake with the workload's own certificate. The Tensorlake port proxy -cannot carry this channel, because it terminates TLS and presents its own -certificate. - -The driver needs one of: - -- **Private sandbox-to-sandbox networking.** Sandboxes in one project can - reach each other on a private IP, and the API returns that IP in the - sandbox description. This is the clean answer. `SandboxInfo` today exposes - `sandbox_url` and `routing_hint` only. -- **A raw TCP port forward.** An exposed port that forwards bytes without TLS - termination, reachable from the control sandbox, plus a stable address for - it. - -In both cases the workload VM must be able to accept the connection with -internet access turned off. - -Until one of these exists, the combined topology stays, and the README's -warning about test credentials stands. - -## Open questions - -- Does a Tensorlake network policy with `allow_internet_access: false` block - inbound connections too, or only outbound? -- How many supervisor processes can the control sandbox run with 2 vCPUs and - 4 GiB? The VM driver's supervisor is small, but the limit sets the - per-control-plane sandbox count. -- Can the driver learn the workload VM's address before the launcher starts, - so the guard bundle is complete at launch time, or must it start the - supervisor only after the first poll shows the address? +| Side | Type | Used here | +|---|---|---| +| Workload listens | `BoundaryListener::TlsTcp { address }` | `0.0.0.0:8444` inside the workload namespace | +| Guard connects | `SandboxTransport::Tcp { authority, addresses }` | authority `:8443`, address `127.0.0.1:18443` | + +The listener must not bind a loopback address, because workload sockets +share loopback, so it binds `0.0.0.0`. The sandbox runtime then protects the +listener port from workload connections itself, and rejects loopback peers +in `accept`, which is why the forwarder connects from a veth address. +`Tcp.addresses` must be concrete `IP:port` pairs, which `127.0.0.1:18443` +is. No change to `openshell-supervisor` or `openshell-sandbox` was needed. + +## Why the tunnel and not a sandbox IP + +The Tensorlake HTTPS port proxy terminates TLS and presents its own +certificate, so it cannot carry the OpenShell channel. Tensorlake has no +private sandbox-to-sandbox network and no sandbox IP in the API. The tunnel +is the one path that relays raw TCP between two sandboxes today. Measured on +Tensorlake Cloud on 2026-10-20: + +| Check | Result | +|---|---| +| Tunnel into a sandbox with internet off | Works. The fence can be fully closed. | +| Target port not in `exposed_ports` | Works. The port is never public. | +| Address the tunnel dials inside the target | `127.0.0.1:` only, not the `eth0` address | +| 100 tunnels from one sandbox | All alive, ~50 ms to open each | +| 500 concurrent connections through one tunnel | All held and answering | +| Throughput through one tunnel | ~300 MiB/s each direction | +| Idle tunnel | Still relaying after 13 minutes | +| `tl sbx tunnel` process | 15 MiB RSS | + +If Tensorlake adds private networking with a sandbox IP later, the driver +can put that IP into `Tcp.addresses` and drop the tunnel. Nothing else +changes. + +## What the driver does + +1. **Create.** Two Tensorlake create calls: the workload VM from the sandbox + image with `allow_internet_access: false` and an empty `allow_out`, and + the guard VM from the guard image with the operator's `--allow-out` plus + the gateway host and the Tensorlake API host. Create returns after both + are accepted. +2. **Wait.** A background task polls both VMs until they report `running`. +3. **Workload bundle.** Uploaded to the workload VM: the boundary bootstrap + with the `TlsTcp` listener, the channel server certificate and key, and + the launch parameters with `ROLE=workload`. The launcher creates the + `openshell-workload` network namespace with loopback and a veth link, + starts `openshell-sandbox launch-capability-free` inside it with a + resolver file that points at the runtime's DNS relay, and starts the + `socat` forwarder as user 65533 in the VM's own namespace. +4. **Guard bundle.** Uploaded to the guard VM: the runtime descriptor with + the `Tcp` transport, the auth bundle, sandbox token, gateway CA, the + guard's environment and arguments, and a tunnel file with the Tensorlake + API key and the workload VM's ID. `ROLE=guard`. The launcher starts the + tunnel as user 65533 and the guard as user 65534. Neither can read the + other's files. The launcher exits when either process exits. +5. **Run.** The driver reports Running when both launchers started. The + gateway marks the sandbox ready when the guard connects. The guard's + first connection to the workload retries until the workload listener is + up, so start order does not matter. +6. **Poll.** Every few seconds the driver lists Tensorlake sandboxes. If + either VM is gone, the sandbox is failed. Both launchers are checked; + an exit is reported as `LauncherExited` with the VM to look at. +7. **Delete.** Both VMs are deleted. The record is forgotten when both are + gone. +8. **Recover.** After a driver restart, VMs are paired by name: + `openshell-` and `openshell--guard`. A pair with one half missing + is reported as failed. + +### Fence evidence + +The driver writes the outer fence into the provisioning evidence that the +guard confirms with the workload: the recipe for the workload VM (a private network namespace whose only +link leads to the forwarder, in a VM with `allow_internet_access: false` +and an empty allow list) and the IDs of both VMs. The driver cannot inspect the VM, and Tensorlake does +not return the applied policy in `SandboxInfo`, so this is the requested +recipe, as in the combined topology. + +## Trust model + +| Attacker | Combined | Split | +|---|---|---| +| Agent with a local kernel exploit | Reads gateway token and credentials | Gets root in a VM that holds only its own channel key. Credentials are in another VM. Egress is still blocked by the Tensorlake fence and still mediated by the guard. | +| Tensorlake project member with `tl sbx exec --user root` | Reads everything in the one VM | Reads everything in the guard VM. Same as today. | +| Anyone with the guard VM's API key | n/a | Can open tunnels to any sandbox in that project. | + +The new exposure is the API key in each guard VM. Two mitigations: + +- Run the control plane and its sandboxes in a dedicated Tensorlake project, + so a leaked guard key reaches nothing else. This is already the README's + advice. +- Tensorlake could issue keys scoped to one target sandbox for tunnels. That + is the clean fix and needs platform work. + +## 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. Two VMs boot in parallel, so create +to ready stays a few seconds. All workload egress flows guard VM to proxy to +workload VM. The tunnel measured about 300 MiB/s, far above what an agent +needs, but each guard VM also pays the CPU for TLS and policy on that +traffic. Size `--guard-cpus` up for agents that move bulk data. + +## Alternative kept out: guards in the control sandbox + +Running every guard inside the control sandbox saves the guard VMs. It also +puts every credential of the project in one kernel, shares 2 vCPUs across +all guards, and drops every session when the control sandbox restarts. +Measured: a 4 GiB control sandbox would fit about 50 guards with `tl` +helper processes or about 100 with the tunnel linked in. The per-sandbox +guard VM was chosen instead because the security property is the point of +this work, and because it matches the Kubernetes driver and the customer +request that motivated it. + +## What the end-to-end test found + +Three fixes were needed before the first sandbox passed, in this order: + +1. **Loopback peers.** The sandbox runtime reset every tunnel connection, + because it rejects boundary peers that are loopback or share its own + address, and the Tensorlake tunnel always delivers to `127.0.0.1`. The + veth forwarder gives the runtime a non-loopback peer. +2. **PID namespace.** With a working channel, every connection was denied + with `transparent_tcp_identity_unavailable`. Binary identity resolution + walks a connecting process's ancestors up to its PID namespace init. In + the VM's root PID namespace that walk reached the root-owned launcher, + which the runtime cannot read. The runtime now runs as PID 1 of its own + PID namespace with a fresh procfs, in both topologies. +3. **Transparent TCP capability.** The guard was granted + `policy-dns-transparent-tcp`, which Docker and Podman use because their + guard shares the workload's network namespace. This guard never does, so + the capability is gone, as in the Kubernetes driver. + +A policy change reaches the guard on its next settings poll, a few seconds +after `openshell policy update` returns. Pass `--wait` to block until it is +effective. + +## Open items + +- Which hosts `tl sbx tunnel` contacts, so `--allow-out` on the guard VM + can be tight. Until measured, leave the guard VM's internet on and rely + on OpenShell policy, as the combined topology did. +- Tunnel reconnection. If the WebSocket drops, the guard launcher exits and + the sandbox is reported failed. A reconnecting tunnel would turn that into + a pause. +- Scoped Tensorlake keys for tunnels. diff --git a/docs/how-it-works/sandboxes/tensorlake.mdx b/docs/how-it-works/sandboxes/tensorlake.mdx index 2ce9e0e242..4ad0cf2ae7 100644 --- a/docs/how-it-works/sandboxes/tensorlake.mdx +++ b/docs/how-it-works/sandboxes/tensorlake.mdx @@ -24,11 +24,17 @@ real credentials. ## How It Works -Each OpenShell sandbox maps to one Tensorlake VM. The guard -(`openshell-supervisor`) and the workload (`openshell-sandbox`) run inside that -VM. The guard holds the gateway session and the provider credentials. The -workload runs in a private network namespace with only loopback, so every -connection it makes goes through the guard, and the guard applies the policy. +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. + +Set `--topology combined` to run both in one VM. That halves the VM count but +puts the credentials in the same kernel as the agent, so use it with test +credentials only. 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 @@ -142,23 +148,28 @@ socket_path = "/run/openshell/tensorlake.sock" |---|---|---| | `--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 guard and launcher. | +| `--sandbox-image` | `OPENSHELL_SANDBOX_IMAGE` | Required. A registered Tensorlake image with the OpenShell runtime, the Tensorlake CLI, and the launcher. | +| `--topology` | `OPENSHELL_TENSORLAKE_TOPOLOGY` | `split`. `combined` runs guard and workload in one VM. | +| `--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; the guard enforces policy. | +| `--allow-out` | `OPENSHELL_TENSORLAKE_ALLOW_OUT` | Empty. Internet on for the guard VM; the guard enforces policy. | Keep `--timeout-secs` at `0`. Tensorlake counts idle time from incoming traffic only, and the guard's traffic is outgoing, so a short timeout suspends a sandbox that is still working. -`--allow-out` adds a second fence at the Tensorlake network. The driver turns -off internet access for the VM and allows only the hosts you list plus the -gateway host. +`--allow-out` adds a second fence at the Tensorlake network for the VM that +runs the guard. The driver turns off internet access for it and allows only +the hosts you list, the gateway host, and the Tensorlake host the tunnel uses. +The workload VM always has all outbound traffic off. ## Images -Sandbox images must contain the guard, the workload runtime, and the launch -script. Build them on Tensorlake; no local Docker is needed: +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 @@ -174,13 +185,23 @@ replace a published version. Publish a new one. ## Trust Model -The guard and the workload share one VM. The guard runs as an unprivileged -user that the workload cannot read, and the workload has no network path -except the channel to the guard. But a root user in the VM can read the -guard's credentials, and anyone with access to the Tensorlake project can run -`tl sbx exec --user root`. Until the guard moves to its own VM, use test -credentials only, and keep the control plane in a Tensorlake project of its -own. +In the split topology 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. + +In the combined topology a root user in the one VM can read the guard's +credentials. Use it with test credentials only. ## Limits @@ -192,6 +213,8 @@ own. that much. - After a driver restart, sandboxes that had not finished launching are reported as failed. Running sandboxes are recovered by name. +- The split topology uses two Tensorlake VMs per sandbox. The guard VM + defaults to 1 vCPU and 1 GiB. For build details, the test runbook, and the design notes, see the [driver README](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-tensorlake/README.md). From 0bb3ea8f5c78bc9ee6e25e70b21adf5f09ba9c0c Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 16:18:19 -0500 Subject: [PATCH 20/31] docs(driver-tensorlake): align the README with the code and rework the runbook Fix the parts of the README that drifted from the driver, the launch script, and the deploy script: the variables deploy.sh forwards, the file layout in the VMs, the standard driver flags, the recovery phases, and the Tensorlake CLI commands. Replace the test runbook with a Testing section that separates unit tests, the conformance scenarios that fit this driver, and the manual checks. The conformance lifecycle test stops and starts sandboxes, which this driver rejects, so the runbook no longer runs it. Move the upstream image pin in both Dockerfiles to the branch's merge base with main. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 247 ++++++++++++++---- .../control/Dockerfile | 2 +- .../image/Dockerfile | 4 +- 3 files changed, 200 insertions(+), 53 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index cb6319c028..ad60a99498 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -98,11 +98,13 @@ namespace that has only loopback, then the guard, in that VM. | Path | VM | Owner | Contents | |---|---|---|---| -| `/.openshell/channel/sandbox/` | workload | workload | bootstrap file and TLS key for the channel to the guard | +| `/.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 | the Tensorlake key and the `tl sbx tunnel` arguments | +| `/.openshell/tunnel/` (mode 0700) | guard | tunnel | `env` with the Tensorlake key | +| `/.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 | In the combined topology all of these except the tunnel files live in the one VM. @@ -236,6 +238,10 @@ openshell-gateway --compute-driver tensorlake \ | `--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 | +| `--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, @@ -286,12 +292,17 @@ bundle in the control image for that connection. crates/openshell-driver-tensorlake/control/deploy.sh ``` - The script copies every `OPENSHELL_OIDC_*` variable into - `/etc/openshell-control/control.env` (mode 0600). Then it 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. + 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 every driver setting + from the table above can be set through its environment variable. Then + it 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: @@ -367,8 +378,13 @@ workloads in it. default is 1000:1000. - No GPU, `driver_config`, `platform_config`, or `agent_socket_path`. - The driver keeps launch state in memory. After a driver restart, it finds - running sandboxes again by their Tensorlake names (`openshell-`). - Sandboxes that had not finished launching are reported as failed. + running sandboxes again by their Tensorlake names (`openshell-` and + `openshell--guard`). A pair with a VM still pending is reported as + failed with reason `DriverRestarted`. A pair with one VM missing is + reported as failed with reason `PairIncomplete`. A pair whose VMs were + running but whose launch scripts had not started yet is recovered as + running, and the gateway then waits for a guard that never connects. + Delete and recreate such a sandbox. - Anyone with access to your Tensorlake project can run `tl sbx exec --user root` in the guard VM and read its credentials, or in the workload VM and get around OpenShell policy. Keep the control plane @@ -377,10 +393,59 @@ workloads in it. open tunnels to any sandbox in the project. - The split topology uses two Tensorlake VMs per sandbox. -## Verified on Tensorlake +## Testing -The unit tests cover the archive layout, request mapping, pairing, and -status mapping. End-to-end runs on Tensorlake Cloud confirmed: +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, + and the phase after each poll observation. +- Launcher failure messages and the progress events the CLI shows. + +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 | no; the driver does not support stop and start | + +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: - Split topology (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 @@ -406,30 +471,35 @@ enforcement in the combined topology. And the transparent TCP capability is for guards that share the workload's network namespace, so this driver no longer grants it. -## Still to confirm +### Still to confirm +- The conformance scenarios `smoke`, `file_transfer`, and `policy_advisor` + pass. - The port proxy keeps a long-lived connection open, and the idle timeout does not pause a sandbox whose only traffic is the guard's outgoing session. -- The conformance suite in `tests/suites/conformance` passes: lifecycle and - file transfer. - A driver restart recovers running sandbox pairs. - The combined topology end to end after the PID namespace change. - Which Tensorlake hosts the tunnel needs, so `--allow-out` can be tight on the guard VM. -## Test runbook +### Runbook -This section is a temporary checklist for the items in -[Still to confirm](#still-to-confirm). Remove it once they are confirmed. +This runbook covers the items in [Still to confirm](#still-to-confirm). +Remove the steps that pass once they are recorded above. Use two shells. Shell A keeps the tunnel open. Shell B runs everything -else. The later steps run `deploy.sh` again, so keep the exported -variables in shell B for the whole run. The steps assume the control -sandbox is `openshell-control`, the CLI gateway is named `tensorlake`, and -the tunnel listens on port 18080. +else. Some steps run `deploy.sh` again, so keep the exported variables in +shell B for the whole run. The steps assume the control sandbox is +`openshell-control`, the CLI gateway is named `tensorlake`, and the tunnel +listens on port 18080. -### 0. Build and deploy the control plane +Each OpenShell sandbox has two Tensorlake VMs: `openshell-` for the +workload and `openshell--guard` for the guard, where `` is the +OpenShell sandbox ID. `tl sbx ls` shows both names. The commands below +call them `$WORKLOAD_VM` and `$GUARD_VM`. + +#### 0. Build and deploy the control plane Build the two images. Skip this if you already have a pair you trust: @@ -489,43 +559,71 @@ fails. Remove the old entry first with `$OPENSHELL_BIN gateway remove tensorlake`, or pick a new name and export that instead. Both commands must succeed before you go on. -### 1. Conformance suite +Create one sandbox and watch the launch steps: + +```shell +$OPENSHELL_BIN sandbox create --name hello -- echo hello +``` + +Expected: the CLI shows the VM request, the VM start, the bundle upload, +and the wait for the guard, then prints `hello`. `tl sbx ls` shows two +new VMs. Delete it with `$OPENSHELL_BIN sandbox delete hello`. + +#### 1. Conformance suite Allow up to an hour. Each scenario creates its own sandboxes and deletes -them. Save the output: +them. Run the three test files that fit this driver and save the output: ```shell cargo test --locked \ --manifest-path tests/suites/conformance/Cargo.toml \ --package openshell-test-conformance-cli \ + --test smoke --test file_transfer --test policy_advisor \ --no-fail-fast -- --test-threads=1 --nocapture 2>&1 \ | tee ~/tensorlake-conformance.log ``` -The policy scenario opens a TCP connection to `1.1.1.1:443` from bash -inside the sandbox and expects `DENIED`. That line is the one to look for. +Do not run `--test lifecycle`. It stops and starts a sandbox, which this +driver rejects by design. + +In the log, the line to look for is `DENIED` from the `denied-tcp-open` +step of `mechanistic-proposal`. + +#### 2. Launch script death -### 2. Launch script death +The driver watches the launch script in both VMs. Test both roles. ```shell $OPENSHELL_BIN sandbox create --name kill-test --detach $OPENSHELL_BIN sandbox get kill-test ``` -Repeat the get until it shows Ready. Then find the sandbox ID and kill the -launch script as root: +Repeat the get until it shows Ready. Then find the two VM names and +confirm that the launch script runs in each: ```shell -$OPENSHELL_BIN sandbox get kill-test --output json | grep '"id"' -tl sbx exec --user root openshell- pkill -f openshell-tensorlake-launch +tl sbx ls | grep openshell- +export WORKLOAD_VM=openshell- +export GUARD_VM=openshell--guard +tl sbx ps $WORKLOAD_VM +tl sbx ps $GUARD_VM +``` + +Kill the script in the guard VM first: + +```shell +tl sbx exec --user root $GUARD_VM pkill -f openshell-tensorlake-launch sleep 10 $OPENSHELL_BIN sandbox get kill-test ``` -Expected: Ready is False and the reason is `LauncherExited`. Keep this -sandbox for step 5. +Expected: Ready is False, the reason is `LauncherExited`, and the message +names the guard launcher and the guard VM. Delete the sandbox, create it +again, and repeat with `$WORKLOAD_VM`. Expected: the same reason, with +the message naming the workload launcher. Keep the second sandbox for +step 7. -### 3. Driver restart +#### 3. Driver restart Create one sandbox and wait for Ready. Then create a second and do not wait: @@ -555,10 +653,12 @@ $OPENSHELL_BIN sandbox get restart-b Expected: a `Recovered Tensorlake sandboxes` log line, `restart-a` still Ready with the exec printing `hello`, and `restart-b` Failed with reason -`DriverRestarted` if it was still pending at restart time. If `restart-b` -had already reached Ready, it should also work. +`DriverRestarted` if a VM was still pending at restart time. If both VMs +of `restart-b` were already running, the driver recovers it as running. +It then becomes Ready only if its launch scripts had started before the +restart. Record which case you saw. -### 4. Idle timeout +#### 4. Idle timeout Read the timeout that the control sandbox got from the default of `0`: @@ -567,7 +667,8 @@ tl sbx describe openshell-control ``` Note the timeout value. That is the plan maximum. Then run a bounded test -with a 3 minute timeout: +with a 3 minute timeout. `deploy.sh` forwards every `OPENSHELL_TENSORLAKE_*` +variable to the driver: ```shell OPENSHELL_TENSORLAKE_TIMEOUT_SECS=180 crates/openshell-driver-tensorlake/control/deploy.sh @@ -580,8 +681,7 @@ Wait for Ready, then leave it alone for 5 minutes and check: ```shell sleep 300 $OPENSHELL_BIN sandbox get idle-test -$OPENSHELL_BIN sandbox get idle-test --output json | grep '"id"' -tl sbx describe openshell- +tl sbx ls | grep openshell- ``` Expected: the sandbox shows Suspended, because the guard's outgoing @@ -593,26 +693,73 @@ variable to restore the default: crates/openshell-driver-tensorlake/control/deploy.sh ``` -### 5. Delete +#### 5. Combined topology + +```shell +OPENSHELL_TENSORLAKE_TOPOLOGY=combined crates/openshell-driver-tensorlake/control/deploy.sh +$OPENSHELL_BIN sandbox create --name combined-test --detach +$OPENSHELL_BIN sandbox get combined-test +``` + +Wait for Ready. Then check that one VM serves the sandbox, that the +workload runs as the workload user, and that policy still denies egress +with a binary identity: + +```shell +tl sbx ls | grep openshell- +$OPENSHELL_BIN sandbox exec --name combined-test --no-tty -- id -u +$OPENSHELL_BIN sandbox exec --name combined-test --no-tty -- \ + bash -c 'if exec 3<>/dev/tcp/1.1.1.1/443; then echo ALLOWED; else echo DENIED; fi' +tl sbx logs openshell- | grep -i "denied\|identity" | tail -5 +``` + +Expected: one VM named `openshell-` and no `-guard` VM, `1000`, +`DENIED`, and a guard log line that names the Bash binary by path rather +than `transparent_tcp_identity_unavailable`. Delete the sandbox and +deploy again without the variable. + +#### 6. Tunnel hosts and `--allow-out` + +Find which hosts the tunnel in a guard VM talks to. Use a Ready sandbox, +for example `restart-a`: + +```shell +tl sbx exec --user root $GUARD_VM ss -tnp +tl sbx exec --user root $GUARD_VM cat /etc/hosts +``` + +Note the peer addresses of the `tl` process and resolve them. Then +deploy with an allow list and check that a sandbox still becomes Ready: + +```shell +OPENSHELL_TENSORLAKE_ALLOW_OUT=api.anthropic.com crates/openshell-driver-tensorlake/control/deploy.sh +$OPENSHELL_BIN sandbox create --name allow-test -- echo hello +``` + +Expected: `hello`. If the sandbox never becomes Ready, read +`tl sbx logs $GUARD_VM`. A tunnel that cannot reach its host exits, and +the driver reports `LauncherExited` for the guard. Make +`effective_allow_out` in `src/config.rs` add the hosts you found, then +deploy again without the variable. + +#### 7. Delete ```shell -$OPENSHELL_BIN sandbox delete kill-test -$OPENSHELL_BIN sandbox delete restart-a -$OPENSHELL_BIN sandbox delete restart-b -$OPENSHELL_BIN sandbox delete idle-test +$OPENSHELL_BIN sandbox delete kill-test restart-a restart-b idle-test allow-test sleep 10 $OPENSHELL_BIN sandbox list -tl sbx list +tl sbx ls ``` Expected: no sandboxes in the first list, and no names starting with `openshell-` in the second, apart from `openshell-control`. -### What to collect +#### What to collect - The conformance log file. -- The output of each `get` and `list` command. +- The output of each `get`, `list`, and `ps` command. - The last 50 lines of `tl sbx logs openshell-control`. +- The tunnel peer addresses from step 6. ## After the runbook passes diff --git a/crates/openshell-driver-tensorlake/control/Dockerfile b/crates/openshell-driver-tensorlake/control/Dockerfile index 5abe8a5857..2dc42668de 100644 --- a/crates/openshell-driver-tensorlake/control/Dockerfile +++ b/crates/openshell-driver-tensorlake/control/Dockerfile @@ -12,7 +12,7 @@ # expand variables in FROM, so the image tags are fixed here. Pin the # upstream commit this branch is based on, the same as image/Dockerfile. -FROM ghcr.io/nvidia/openshell/gateway:1cb9ef8ab469354a641893f8e26957e988f5c7ef AS gateway +FROM ghcr.io/nvidia/openshell/gateway:ea265a2f9a86e6fc1911041fec4b5fdcefd674dd AS gateway FROM rust:1.95-trixie AS driver WORKDIR /src diff --git a/crates/openshell-driver-tensorlake/image/Dockerfile b/crates/openshell-driver-tensorlake/image/Dockerfile index f1a480f8c7..151198e17e 100644 --- a/crates/openshell-driver-tensorlake/image/Dockerfile +++ b/crates/openshell-driver-tensorlake/image/Dockerfile @@ -17,8 +17,8 @@ # 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:1cb9ef8ab469354a641893f8e26957e988f5c7ef AS supervisor -FROM ghcr.io/nvidia/openshell/sandbox:1cb9ef8ab469354a641893f8e26957e988f5c7ef AS sandbox +FROM ghcr.io/nvidia/openshell/supervisor:ea265a2f9a86e6fc1911041fec4b5fdcefd674dd AS supervisor +FROM ghcr.io/nvidia/openshell/sandbox:ea265a2f9a86e6fc1911041fec4b5fdcefd674dd AS sandbox FROM ubuntu:24.04 From 1a78bd2535488bcf7c3bd86a6ece9e82b3f73d70 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 16:50:17 -0500 Subject: [PATCH 21/31] fix(driver-tensorlake): keep sandbox names across a driver restart The gateway copies the name from every driver snapshot into its own record and refuses a name change. A recovered record had only an ID, so after a driver restart every status update for a recovered sandbox failed with "name cannot be changed after creation". Tensorlake keeps no labels, so the driver now saves a copy of each sandbox request, without its credentials, under --state-dir and reads it back at recovery. Create saves the request before any VM exists, forget removes it, and recovery prunes files whose VMs are gone. The control plane keeps the directory next to the gateway database. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- Cargo.lock | 1 + crates/openshell-driver-tensorlake/Cargo.toml | 1 + crates/openshell-driver-tensorlake/README.md | 16 +- .../control/openshell-control-start.sh | 3 +- .../openshell-driver-tensorlake/src/config.rs | 8 + .../openshell-driver-tensorlake/src/driver.rs | 177 +++++++++++--- crates/openshell-driver-tensorlake/src/lib.rs | 1 + .../openshell-driver-tensorlake/src/main.rs | 10 + .../openshell-driver-tensorlake/src/state.rs | 224 ++++++++++++++++++ docs/how-it-works/sandboxes/tensorlake.mdx | 4 +- 10 files changed, 407 insertions(+), 38 deletions(-) create mode 100644 crates/openshell-driver-tensorlake/src/state.rs diff --git a/Cargo.lock b/Cargo.lock index 4abc57a15f..d9e1f751e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4622,6 +4622,7 @@ dependencies = [ "openshell-isolation-interface", "openshell-otel", "openshell-sandbox-backend", + "prost", "reqwest 0.12.28", "serde", "serde_json", diff --git a/crates/openshell-driver-tensorlake/Cargo.toml b/crates/openshell-driver-tensorlake/Cargo.toml index 6d30e307b0..80a5618ecd 100644 --- a/crates/openshell-driver-tensorlake/Cargo.toml +++ b/crates/openshell-driver-tensorlake/Cargo.toml @@ -24,6 +24,7 @@ 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 } diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index ad60a99498..ca7d581531 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -238,6 +238,7 @@ openshell-gateway --compute-driver tensorlake \ | `--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 | @@ -377,9 +378,14 @@ workloads in it. - The workload identity accepts a numeric user ID and group ID only. The default is 1000:1000. - No GPU, `driver_config`, `platform_config`, or `agent_socket_path`. -- The driver keeps launch state in memory. After a driver restart, it finds - running sandboxes again by their Tensorlake names (`openshell-` and - `openshell--guard`). A pair with a VM still pending is reported as +- The driver keeps launch state in memory and a copy of each sandbox + request, without its credentials, under `--state-dir`. After a driver + restart, it finds running sandboxes again by their Tensorlake names + (`openshell-` and `openshell--guard`) and reports them under the + names in the saved requests. Keep the state directory with the gateway + database: a recovered sandbox with no saved request has no name, and the + gateway then rejects every status update for it until it is deleted. A + pair with a VM still pending is reported as failed with reason `DriverRestarted`. A pair with one VM missing is reported as failed with reason `PairIncomplete`. A pair whose VMs were running but whose launch scripts had not started yet is recovered as @@ -656,7 +662,9 @@ Ready with the exec printing `hello`, and `restart-b` Failed with reason `DriverRestarted` if a VM was still pending at restart time. If both VMs of `restart-b` were already running, the driver recovers it as running. It then becomes Ready only if its launch scripts had started before the -restart. Record which case you saw. +restart. Record which case you saw. The gateway log must show no +`name cannot be changed after creation` error: the driver reports each +recovered sandbox under the name in its saved request. #### 4. Idle timeout diff --git a/crates/openshell-driver-tensorlake/control/openshell-control-start.sh b/crates/openshell-driver-tensorlake/control/openshell-control-start.sh index 9385d6fc5a..436e8c876d 100755 --- a/crates/openshell-driver-tensorlake/control/openshell-control-start.sh +++ b/crates/openshell-driver-tensorlake/control/openshell-control-start.sh @@ -108,7 +108,8 @@ trap 'exit 143' TERM INT --gateway-name "${GATEWAY_NAME}" \ --grpc-endpoint "${OPENSHELL_CONTROL_PUBLIC_URL}" \ --gateway-tls-ca "${PUBLIC_CA}" \ - --sandbox-image "${OPENSHELL_SANDBOX_IMAGE}" & + --sandbox-image "${OPENSHELL_SANDBOX_IMAGE}" \ + --state-dir "${STATE_DIR}/tensorlake" & DRIVER_PID=$! for _ in $(seq 1 50); do diff --git a/crates/openshell-driver-tensorlake/src/config.rs b/crates/openshell-driver-tensorlake/src/config.rs index d738dd0d2c..0fa856fbfe 100644 --- a/crates/openshell-driver-tensorlake/src/config.rs +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -92,6 +92,9 @@ pub struct TensorlakeComputeConfig { 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 { @@ -113,6 +116,7 @@ impl std::fmt::Debug for TensorlakeComputeConfig { .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() } } @@ -229,6 +233,10 @@ pub(crate) mod tests { 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() + )), } } diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs index a15f343e0d..3948d543d2 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -38,6 +38,7 @@ use crate::client::{ }; use crate::config::{TensorlakeComputeConfig, Topology}; use crate::launch::{self, LaunchBundleInput}; +use crate::state::StateStore; /// Prefix for Tensorlake sandbox names created by this driver. pub const NAME_PREFIX: &str = "openshell-"; @@ -242,6 +243,8 @@ pub struct TensorlakeComputeDriver { 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 { @@ -272,6 +275,7 @@ impl TensorlakeComputeDriver { 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), @@ -279,6 +283,7 @@ impl TensorlakeComputeDriver { gateway_ca_pem, records: Arc::new(Mutex::new(HashMap::new())), events, + state, }; driver.recover().await?; let poller = driver.clone(); @@ -289,6 +294,7 @@ impl TensorlakeComputeDriver { #[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), @@ -296,6 +302,7 @@ impl TensorlakeComputeDriver { gateway_ca_pem: None, records: Arc::new(Mutex::new(HashMap::new())), events, + state, } } @@ -449,7 +456,19 @@ impl TensorlakeComputeDriver { guard_network.clone() }; let name = tensorlake_name(&sandbox.id); - let created = self + // 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)), @@ -460,7 +479,13 @@ impl TensorlakeComputeDriver { wait: Some(false), }) .await - .map_err(create_error)?; + { + 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, @@ -501,6 +526,7 @@ impl TensorlakeComputeDriver { "Failed to delete the workload VM after the guard VM create failed" ); } + self.discard_state(&sandbox.id).await; return Err(create_error(error)); } } @@ -508,13 +534,6 @@ impl TensorlakeComputeDriver { None }; - // Keep secrets out of the stored record; only the provisioning task - // sees the launch credentials. - let mut stored = sandbox.clone(); - if let Some(spec) = stored.spec.as_mut() { - spec.sandbox_token.clear(); - spec.launch_authentication.clear(); - } let record = Record { sandbox: stored, tensorlake_id: created.sandbox_id.clone(), @@ -801,6 +820,7 @@ impl TensorlakeComputeDriver { 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 { @@ -811,6 +831,13 @@ impl TensorlakeComputeDriver { } } + /// 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())); } @@ -831,41 +858,55 @@ impl TensorlakeComputeDriver { /// 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. + /// 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 records = self.records.lock().await; + let mut recovered = Vec::new(); for (sandbox_id, workload, guard) in pair_by_name(&sandboxes) { let Some(phase) = recovered_phase(workload, guard, self.config.topology) else { continue; }; - // A guard VM whose workload VM is gone is still recorded, under - // the workload's name, so that delete can remove it. - let Some(anchor) = workload.or(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 + } }; - records.insert( - sandbox_id.to_string(), - Record { - sandbox: DriverSandbox { - id: sandbox_id.to_string(), - ..DriverSandbox::default() - }, - tensorlake_id: workload - .map_or_else(|| anchor.sandbox_id.clone(), |info| info.sandbox_id.clone()), - tensorlake_name: tensorlake_name(sandbox_id), - guard_tensorlake_id: guard.map(|info| info.sandbox_id.clone()), - identity: None, - phase, - launcher_pid: None, - guard_launcher_pid: 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(()) } @@ -970,6 +1011,33 @@ fn pair_by_name( /// 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()), + identity: None, + phase, + launcher_pid: None, + guard_launcher_pid: None, + }) +} + fn recovered_phase( workload: Option<&SandboxInfo>, guard: Option<&SandboxInfo>, @@ -1508,6 +1576,51 @@ mod tests { 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.as_deref(), + Some(guard.sandbox_id.as_str()) + ); + 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::Suspended).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) = ( diff --git a/crates/openshell-driver-tensorlake/src/lib.rs b/crates/openshell-driver-tensorlake/src/lib.rs index 77da0d1adc..b031de3d31 100644 --- a/crates/openshell-driver-tensorlake/src/lib.rs +++ b/crates/openshell-driver-tensorlake/src/lib.rs @@ -6,6 +6,7 @@ pub mod config; pub mod driver; pub mod grpc; pub mod launch; +pub mod state; pub use config::TensorlakeComputeConfig; pub use driver::TensorlakeComputeDriver; diff --git a/crates/openshell-driver-tensorlake/src/main.rs b/crates/openshell-driver-tensorlake/src/main.rs index fc2d8f54f5..355749e77a 100644 --- a/crates/openshell-driver-tensorlake/src/main.rs +++ b/crates/openshell-driver-tensorlake/src/main.rs @@ -107,6 +107,15 @@ struct Args { 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] @@ -144,6 +153,7 @@ async fn main() -> Result<()> { 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 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/how-it-works/sandboxes/tensorlake.mdx b/docs/how-it-works/sandboxes/tensorlake.mdx index 4ad0cf2ae7..333544cd9e 100644 --- a/docs/how-it-works/sandboxes/tensorlake.mdx +++ b/docs/how-it-works/sandboxes/tensorlake.mdx @@ -155,6 +155,7 @@ socket_path = "/run/openshell/tensorlake.sock" | `--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. | +| `--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`. Tensorlake counts idle time from incoming traffic only, and the guard's traffic is outgoing, so a short timeout suspends @@ -212,7 +213,8 @@ credentials. Use it with test credentials only. - The driver polls Tensorlake every few seconds. Status changes can lag by that much. - After a driver restart, sandboxes that had not finished launching are - reported as failed. Running sandboxes are recovered by name. + reported as failed. Running sandboxes are recovered from the saved + requests in `--state-dir`. Keep that directory with the gateway database. - The split topology uses two Tensorlake VMs per sandbox. The guard VM defaults to 1 vCPU and 1 GiB. From a410a3187c603f38ae78881d41edbc193db7ad4d Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 16:53:58 -0500 Subject: [PATCH 22/31] fix(driver-tensorlake): pass the sandbox API URL to the tunnel and disable Nagle on the forwarder The guard starts `tl sbx tunnel` with `env -i`, so the tunnel saw only the API key and always resolved the workload through the public sandbox service, even when `--tensorlake-api-url` named another deployment. Write `TENSORLAKE_SANDBOX_API_URL` into the tunnel env, which is the variable `tl` reads for the sandbox lifecycle URL. Reject API URL shapes that `tl` silently ignores so a bad value fails at startup. Set socat's nodelay option on both forwarder sockets. Every boundary RPC crosses them as small frames, so delayed ACKs could stall each exchange. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 2 +- .../image/openshell-tensorlake-launch.sh | 7 ++-- .../openshell-driver-tensorlake/src/config.rs | 36 ++++++++++++++++++- .../openshell-driver-tensorlake/src/launch.rs | 23 +++++++++--- 4 files changed, 59 insertions(+), 9 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index ca7d581531..a64d0fef6c 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -101,7 +101,7 @@ namespace that has only loopback, then the guard, in that VM. | `/.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 | +| `/.openshell/tunnel/` (mode 0700) | guard | tunnel | `env` with the Tensorlake key and the sandbox 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 | diff --git a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh index 44b51bfa22..64c055e3cd 100755 --- a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh +++ b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh @@ -163,15 +163,16 @@ start_workload() { # 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. +# 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" \ - "TCP4:${VETH_WORKLOAD_ADDR}:${WORKLOAD_LISTEN_PORT},bind=${VETH_HOST_ADDR}" & + "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+=("$!") } diff --git a/crates/openshell-driver-tensorlake/src/config.rs b/crates/openshell-driver-tensorlake/src/config.rs index 0fa856fbfe..7cad411683 100644 --- a/crates/openshell-driver-tensorlake/src/config.rs +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -152,8 +152,23 @@ impl TensorlakeComputeConfig { )); } } - url::Url::parse(&self.api_url) + let api_url = url::Url::parse(&self.api_url) .map_err(|error| format!("invalid Tensorlake API URL: {error}"))?; + // The guard's tunnel receives this URL as TENSORLAKE_SANDBOX_API_URL. + // The tl CLI silently ignores values of any other shape and falls + // back to the public service, so reject them here. + if !matches!(api_url.scheme(), "http" | "https") + || api_url.host_str().is_none() + || api_url.query().is_some() + || api_url.fragment().is_some() + || !api_url.username().is_empty() + || api_url.password().is_some() + { + return Err( + "Tensorlake API URL must be an http or https URL with a host and no query, fragment, or credentials" + .into(), + ); + } 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()); } @@ -262,6 +277,25 @@ pub(crate) mod tests { 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(())); + } + #[test] fn validate_rejects_missing_endpoint() { let mut config = test_config(); diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs index 0688d898da..57e4e21cd2 100644 --- a/crates/openshell-driver-tensorlake/src/launch.rs +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -577,8 +577,13 @@ fn add_guard_files(archive: &mut Archive, files: &GuardFiles<'_>) -> Result<(), ) } -/// The Tensorlake key and the `tl sbx tunnel` arguments for the tunnel -/// identity in the guard VM. +/// The Tensorlake key, the Tensorlake sandbox API URL, 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`; its `TENSORLAKE_API_URL` names the +/// main Tensorlake API, not the sandbox API this driver is configured with. fn add_tunnel_files( archive: &mut Archive, config: &TensorlakeComputeConfig, @@ -588,12 +593,18 @@ fn add_tunnel_files( 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']) { + 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)]), + &nul_list([ + format!("TENSORLAKE_API_KEY={}", config.api_key), + format!("TENSORLAKE_SANDBOX_API_URL={}", config.api_url), + ]), )?; archive.file( TUNNEL_ARGS_PATH, @@ -928,6 +939,7 @@ mod tests { 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(); let bundles = build_launch_bundles(LaunchBundleInput { sandbox: &sandbox, config: &config, @@ -980,7 +992,10 @@ mod tests { 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\0"); + assert_eq!( + env, + b"TENSORLAKE_API_KEY=tl_secret_key\0TENSORLAKE_SANDBOX_API_URL=https://sandbox.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); From e650d6528b2e6f383e42668c83e46d600603e3e0 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 17:04:54 -0500 Subject: [PATCH 23/31] docs(driver-tensorlake): fold the split topology design into the README The split topology is the default, so its design doc repeated the README. Keep the four parts the README lacked as one short section: the trust model, why the tunnel, the rejected alternative, and the cost. Remove the doc. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 41 +++- .../docs/split-topology.md | 213 ------------------ 2 files changed, 39 insertions(+), 215 deletions(-) delete mode 100644 crates/openshell-driver-tensorlake/docs/split-topology.md diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index a64d0fef6c..cf713eccec 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -22,8 +22,7 @@ it makes goes through the guard, and the guard applies the policy. By default the guard and the workload run in two different VMs (the "split" topology). 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. The design and its measurements are in -[docs/split-topology.md](docs/split-topology.md). +the VM that runs the agent. See [Design decisions](#design-decisions). With `--topology combined`, both run in one VM. That is cheaper, but a root user in that VM can read the guard's credentials. Use it with test @@ -122,6 +121,44 @@ 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 | Combined | Split | +|---|---|---| +| Agent with a kernel exploit | Reads the guard's credentials | Gets root in a VM with no credentials | +| Project member with `tl sbx exec --user root` | Reads everything | Reads everything in the guard VM | +| Holder of a guard VM's Tensorlake key | n/a | Can open 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. diff --git a/crates/openshell-driver-tensorlake/docs/split-topology.md b/crates/openshell-driver-tensorlake/docs/split-topology.md deleted file mode 100644 index eec882e23a..0000000000 --- a/crates/openshell-driver-tensorlake/docs/split-topology.md +++ /dev/null @@ -1,213 +0,0 @@ -# Split topology: the guard in its own VM - -Status: implemented as the default topology (`--topology split`) and -verified end to end on Tensorlake Cloud on 2026-10-20, including policy -enforcement with binary identity. The combined topology -(`--topology combined`) stays for tests and for accounts that cannot afford -two VMs per sandbox. - -## Problem - -In the combined topology the guard (`openshell-supervisor`) and the workload -(`openshell-sandbox`) share one Tensorlake VM. The guard holds the gateway -session token and the provider credentials. The workload cannot read them in -normal operation: it runs as a different user, with `no_new_privs`, in a -network namespace that has only loopback. But one kernel exploit in that VM -gives the agent everything. That is container-grade separation. The VM -driver (`openshell-driver-vm`) gives hypervisor-grade separation, because its -guard runs outside the guest. This document describes how the Tensorlake -driver gets the same property. - -## Design - -Two Tensorlake sandboxes per OpenShell sandbox: - -| Tensorlake sandbox | Runs | Network | Holds | -|---|---|---|---| -| `openshell-` (workload VM) | `openshell-sandbox` and the agent in a private network namespace, plus a tunnel forwarder | Internet off, empty allow list. No outbound path at all. | Its own channel key. No gateway or provider secret. | -| `openshell--guard` (guard VM) | `openshell-supervisor` and a `tl` tunnel | Default internet, or `--allow-out` plus the gateway and Tensorlake hosts | Gateway token, provider credentials, a Tensorlake API key for the tunnel | - -``` - control sandbox guard VM (trusted) workload VM (untrusted) -┌───────────────┐ HTTPS ┌──────────────────────────┐ ┌──────────────────────────────────────┐ -│ gateway ◄─────┼────────┼─ openshell-supervisor │ │ 127.0.0.1:8443 socat forwarder │ -│ driver ─► API │ │ │ OpenShell TLS │ WSS to │ │ veth 169.254.77.1 -> .2:8444 │ -└───────────────┘ │ ▼ │ proxy │ ┌──▼── netns openshell-workload ────┐│ - │ 127.0.0.1:18443 tunnel ──┼───────►│ │ openshell-sandbox :8444 TLS ││ - └──────────────────────────┘ │ │ └─► agent processes (lo only) ││ - │ └───────────────────────────────────┘│ - └──────────────────────────────────────┘ -``` - -The guard dials `127.0.0.1:18443` in its own VM. The `tl sbx tunnel` process -there carries the bytes to the Tensorlake sandbox proxy over a WebSocket, -and the proxy delivers them to `127.0.0.1:8443` in the workload VM. A -`socat` forwarder accepts them there and connects into the workload's -network namespace over a veth link, from `169.254.77.1` to the runtime at -`169.254.77.2:8444`. The tunnel and the forwarder do not inspect the bytes. -OpenShell's own TLS handshake runs end to end between guard and workload, -with the per-generation certificate the driver issued. - -The forwarder exists because the sandbox runtime rejects boundary peers -that are loopback or share its own address (`reject_workload_tcp_peer` in -`openshell-sandbox`), and the Tensorlake tunnel always delivers to loopback. -Measured: the runtime reset every tunnel connection until the forwarder -gave it a veth peer. The namespace also keeps the workload's loopback as -empty as in the combined topology, so the workload cannot reach the VM's -own SSH daemon or the forwarder. - -This is the same shape as the Kubernetes driver: one guard pod per workload -pod, a TLS listener in the workload, a NetworkPolicy that gives the workload -no egress. Tensorlake's network policy is the outer fence here. - -## What the protocol already supports - -The sandbox protocol does not depend on a Unix socket. The shared types in -`openshell-sandbox-backend` and `openshell-core` offer three transports: - -| Side | Type | Used here | -|---|---|---| -| Workload listens | `BoundaryListener::TlsTcp { address }` | `0.0.0.0:8444` inside the workload namespace | -| Guard connects | `SandboxTransport::Tcp { authority, addresses }` | authority `:8443`, address `127.0.0.1:18443` | - -The listener must not bind a loopback address, because workload sockets -share loopback, so it binds `0.0.0.0`. The sandbox runtime then protects the -listener port from workload connections itself, and rejects loopback peers -in `accept`, which is why the forwarder connects from a veth address. -`Tcp.addresses` must be concrete `IP:port` pairs, which `127.0.0.1:18443` -is. No change to `openshell-supervisor` or `openshell-sandbox` was needed. - -## Why the tunnel and not a sandbox IP - -The Tensorlake HTTPS port proxy terminates TLS and presents its own -certificate, so it cannot carry the OpenShell channel. Tensorlake has no -private sandbox-to-sandbox network and no sandbox IP in the API. The tunnel -is the one path that relays raw TCP between two sandboxes today. Measured on -Tensorlake Cloud on 2026-10-20: - -| Check | Result | -|---|---| -| Tunnel into a sandbox with internet off | Works. The fence can be fully closed. | -| Target port not in `exposed_ports` | Works. The port is never public. | -| Address the tunnel dials inside the target | `127.0.0.1:` only, not the `eth0` address | -| 100 tunnels from one sandbox | All alive, ~50 ms to open each | -| 500 concurrent connections through one tunnel | All held and answering | -| Throughput through one tunnel | ~300 MiB/s each direction | -| Idle tunnel | Still relaying after 13 minutes | -| `tl sbx tunnel` process | 15 MiB RSS | - -If Tensorlake adds private networking with a sandbox IP later, the driver -can put that IP into `Tcp.addresses` and drop the tunnel. Nothing else -changes. - -## What the driver does - -1. **Create.** Two Tensorlake create calls: the workload VM from the sandbox - image with `allow_internet_access: false` and an empty `allow_out`, and - the guard VM from the guard image with the operator's `--allow-out` plus - the gateway host and the Tensorlake API host. Create returns after both - are accepted. -2. **Wait.** A background task polls both VMs until they report `running`. -3. **Workload bundle.** Uploaded to the workload VM: the boundary bootstrap - with the `TlsTcp` listener, the channel server certificate and key, and - the launch parameters with `ROLE=workload`. The launcher creates the - `openshell-workload` network namespace with loopback and a veth link, - starts `openshell-sandbox launch-capability-free` inside it with a - resolver file that points at the runtime's DNS relay, and starts the - `socat` forwarder as user 65533 in the VM's own namespace. -4. **Guard bundle.** Uploaded to the guard VM: the runtime descriptor with - the `Tcp` transport, the auth bundle, sandbox token, gateway CA, the - guard's environment and arguments, and a tunnel file with the Tensorlake - API key and the workload VM's ID. `ROLE=guard`. The launcher starts the - tunnel as user 65533 and the guard as user 65534. Neither can read the - other's files. The launcher exits when either process exits. -5. **Run.** The driver reports Running when both launchers started. The - gateway marks the sandbox ready when the guard connects. The guard's - first connection to the workload retries until the workload listener is - up, so start order does not matter. -6. **Poll.** Every few seconds the driver lists Tensorlake sandboxes. If - either VM is gone, the sandbox is failed. Both launchers are checked; - an exit is reported as `LauncherExited` with the VM to look at. -7. **Delete.** Both VMs are deleted. The record is forgotten when both are - gone. -8. **Recover.** After a driver restart, VMs are paired by name: - `openshell-` and `openshell--guard`. A pair with one half missing - is reported as failed. - -### Fence evidence - -The driver writes the outer fence into the provisioning evidence that the -guard confirms with the workload: the recipe for the workload VM (a private network namespace whose only -link leads to the forwarder, in a VM with `allow_internet_access: false` -and an empty allow list) and the IDs of both VMs. The driver cannot inspect the VM, and Tensorlake does -not return the applied policy in `SandboxInfo`, so this is the requested -recipe, as in the combined topology. - -## Trust model - -| Attacker | Combined | Split | -|---|---|---| -| Agent with a local kernel exploit | Reads gateway token and credentials | Gets root in a VM that holds only its own channel key. Credentials are in another VM. Egress is still blocked by the Tensorlake fence and still mediated by the guard. | -| Tensorlake project member with `tl sbx exec --user root` | Reads everything in the one VM | Reads everything in the guard VM. Same as today. | -| Anyone with the guard VM's API key | n/a | Can open tunnels to any sandbox in that project. | - -The new exposure is the API key in each guard VM. Two mitigations: - -- Run the control plane and its sandboxes in a dedicated Tensorlake project, - so a leaked guard key reaches nothing else. This is already the README's - advice. -- Tensorlake could issue keys scoped to one target sandbox for tunnels. That - is the clean fix and needs platform work. - -## 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. Two VMs boot in parallel, so create -to ready stays a few seconds. All workload egress flows guard VM to proxy to -workload VM. The tunnel measured about 300 MiB/s, far above what an agent -needs, but each guard VM also pays the CPU for TLS and policy on that -traffic. Size `--guard-cpus` up for agents that move bulk data. - -## Alternative kept out: guards in the control sandbox - -Running every guard inside the control sandbox saves the guard VMs. It also -puts every credential of the project in one kernel, shares 2 vCPUs across -all guards, and drops every session when the control sandbox restarts. -Measured: a 4 GiB control sandbox would fit about 50 guards with `tl` -helper processes or about 100 with the tunnel linked in. The per-sandbox -guard VM was chosen instead because the security property is the point of -this work, and because it matches the Kubernetes driver and the customer -request that motivated it. - -## What the end-to-end test found - -Three fixes were needed before the first sandbox passed, in this order: - -1. **Loopback peers.** The sandbox runtime reset every tunnel connection, - because it rejects boundary peers that are loopback or share its own - address, and the Tensorlake tunnel always delivers to `127.0.0.1`. The - veth forwarder gives the runtime a non-loopback peer. -2. **PID namespace.** With a working channel, every connection was denied - with `transparent_tcp_identity_unavailable`. Binary identity resolution - walks a connecting process's ancestors up to its PID namespace init. In - the VM's root PID namespace that walk reached the root-owned launcher, - which the runtime cannot read. The runtime now runs as PID 1 of its own - PID namespace with a fresh procfs, in both topologies. -3. **Transparent TCP capability.** The guard was granted - `policy-dns-transparent-tcp`, which Docker and Podman use because their - guard shares the workload's network namespace. This guard never does, so - the capability is gone, as in the Kubernetes driver. - -A policy change reaches the guard on its next settings poll, a few seconds -after `openshell policy update` returns. Pass `--wait` to block until it is -effective. - -## Open items - -- Which hosts `tl sbx tunnel` contacts, so `--allow-out` on the guard VM - can be tight. Until measured, leave the guard VM's internet on and rely - on OpenShell policy, as the combined topology did. -- Tunnel reconnection. If the WebSocket drops, the guard launcher exits and - the sandbox is reported failed. A reconnecting tunnel would turn that into - a pause. -- Scoped Tensorlake keys for tunnels. From e98adced2d8ee83655e3d4389098e51927be49c7 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 17:12:14 -0500 Subject: [PATCH 24/31] refactor(driver-tensorlake): remove the combined topology The guard always runs in its own VM now. The one-VM mode put the credentials in the agent's kernel, was unverified since the PID namespace change, and doubled the code paths. Drop the --topology flag, the combined launch role, and the branches that allowed a sandbox without a guard VM. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 83 ++--- .../image/openshell-tensorlake-launch.sh | 48 +-- .../openshell-driver-tensorlake/src/config.rs | 63 +--- .../openshell-driver-tensorlake/src/driver.rs | 319 +++++++----------- .../openshell-driver-tensorlake/src/launch.rs | 232 ++++--------- .../openshell-driver-tensorlake/src/main.rs | 8 - docs/how-it-works/sandboxes/tensorlake.mdx | 17 +- 7 files changed, 238 insertions(+), 532 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index cf713eccec..39b92f740e 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -19,14 +19,10 @@ 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. -By default the guard and the workload run in two different VMs (the -"split" topology). 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). - -With `--topology combined`, both run in one VM. That is cheaper, but a root -user in that VM can read the guard's credentials. Use it with test -credentials only. +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). @@ -89,10 +85,6 @@ When the gateway asks for a new sandbox: Tensorlake cannot push changes to the driver. So the driver asks Tensorlake for the list of sandboxes every few seconds. -With `--topology combined`, step 1 creates one VM, step 3 packs one -archive, and the launch script starts the workload in a private network -namespace that has only loopback, then the guard, in that VM. - ### Where the files live in the VMs | Path | VM | Owner | Contents | @@ -105,9 +97,6 @@ namespace that has only loopback, then the guard, in that VM. | `/.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 | -In the combined topology all of these except the tunnel files live in the -one VM. - ### The outer fence The workload runs in a network namespace whose only link leads to the @@ -127,13 +116,14 @@ it from outside. 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. +Kubernetes driver, which runs one guard pod per workload pod. A one-VM +mode existed and was removed: it was cheaper, unverified, and unsafe. -| Attacker | Combined | Split | -|---|---|---| -| Agent with a kernel exploit | Reads the guard's credentials | Gets root in a VM with no credentials | -| Project member with `tl sbx exec --user root` | Reads everything | Reads everything in the guard VM | -| Holder of a guard VM's Tensorlake key | n/a | Can open tunnels to any sandbox in the project | +| 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 @@ -268,7 +258,6 @@ openshell-gateway --compute-driver tensorlake \ | `--tensorlake-api-url` | `TENSORLAKE_API_URL` | `https://sandbox.tensorlake.ai` | | `--tensorlake-api-key` | `TENSORLAKE_API_KEY` | required | | `--sandbox-image` | `OPENSHELL_SANDBOX_IMAGE` | required | -| `--topology` | `OPENSHELL_TENSORLAKE_TOPOLOGY` | `split`; `combined` shares one VM | | `--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 | @@ -292,9 +281,8 @@ longest timeout your plan allows. When you set `--allow-out`, the driver turns off internet access for the VM that runs the guard and allows only the hosts you listed, the gateway -host, and in the split topology the Tensorlake host that the tunnel talks -to. The workload VM in the split topology always has internet access off -with an empty allow list. +host, and the Tensorlake host that the tunnel talks to. The workload VM +always has internet access off with an empty allow list. ## Run the control plane on Tensorlake @@ -434,7 +422,7 @@ workloads in it. in a project of its own. - Each guard VM holds a Tensorlake API key for its tunnel. That key can open tunnels to any sandbox in the project. -- The split topology uses two Tensorlake VMs per sandbox. +- Each sandbox uses two Tensorlake VMs. ## Testing @@ -490,7 +478,7 @@ the tunnel. End-to-end runs on Tensorlake Cloud confirmed: -- Split topology (2026-10-20): create to Ready in about 4 seconds with two +- 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 @@ -500,17 +488,16 @@ End-to-end runs on Tensorlake Cloud confirmed: identity; 20 sequential fetches through guard and tunnel took 3.7 seconds; delete removes both VMs; a guard launcher exit is reported as `LauncherExited`. -- Both topologies: the VM kernel supports Landlock, seccomp, network, mount, +- 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. -Three findings shaped the split topology. The sandbox runtime rejects +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, which also fixes policy -enforcement in the combined topology. And the transparent TCP capability +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. @@ -522,7 +509,6 @@ no longer grants it. does not pause a sandbox whose only traffic is the guard's outgoing session. - A driver restart recovers running sandbox pairs. -- The combined topology end to end after the PID namespace change. - Which Tensorlake hosts the tunnel needs, so `--allow-out` can be tight on the guard VM. @@ -664,7 +650,7 @@ Expected: Ready is False, the reason is `LauncherExited`, and the message names the guard launcher and the guard VM. Delete the sandbox, create it again, and repeat with `$WORKLOAD_VM`. Expected: the same reason, with the message naming the workload launcher. Keep the second sandbox for -step 7. +step 6. #### 3. Driver restart @@ -738,32 +724,7 @@ variable to restore the default: crates/openshell-driver-tensorlake/control/deploy.sh ``` -#### 5. Combined topology - -```shell -OPENSHELL_TENSORLAKE_TOPOLOGY=combined crates/openshell-driver-tensorlake/control/deploy.sh -$OPENSHELL_BIN sandbox create --name combined-test --detach -$OPENSHELL_BIN sandbox get combined-test -``` - -Wait for Ready. Then check that one VM serves the sandbox, that the -workload runs as the workload user, and that policy still denies egress -with a binary identity: - -```shell -tl sbx ls | grep openshell- -$OPENSHELL_BIN sandbox exec --name combined-test --no-tty -- id -u -$OPENSHELL_BIN sandbox exec --name combined-test --no-tty -- \ - bash -c 'if exec 3<>/dev/tcp/1.1.1.1/443; then echo ALLOWED; else echo DENIED; fi' -tl sbx logs openshell- | grep -i "denied\|identity" | tail -5 -``` - -Expected: one VM named `openshell-` and no `-guard` VM, `1000`, -`DENIED`, and a guard log line that names the Bash binary by path rather -than `transparent_tcp_identity_unavailable`. Delete the sandbox and -deploy again without the variable. - -#### 6. Tunnel hosts and `--allow-out` +#### 5. Tunnel hosts and `--allow-out` Find which hosts the tunnel in a guard VM talks to. Use a Ready sandbox, for example `restart-a`: @@ -787,7 +748,7 @@ the driver reports `LauncherExited` for the guard. Make `effective_allow_out` in `src/config.rs` add the hosts you found, then deploy again without the variable. -#### 7. Delete +#### 6. Delete ```shell $OPENSHELL_BIN sandbox delete kill-test restart-a restart-b idle-test allow-test @@ -804,7 +765,7 @@ Expected: no sandboxes in the first list, and no names starting with - The conformance log file. - The output of each `get`, `list`, and `ps` command. - The last 50 lines of `tl sbx logs openshell-control`. -- The tunnel peer addresses from step 6. +- The tunnel peer addresses from step 5. ## After the runbook passes diff --git a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh index 64c055e3cd..496e3ac9df 100755 --- a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh +++ b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh @@ -19,9 +19,6 @@ # 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. -# combined Start both in this VM. The workload runs in a network -# namespace that has only loopback, so its only path out is the -# channel to the guard. Test credentials only. # # 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 @@ -65,7 +62,7 @@ tar --extract --file "$BUNDLE" --directory / --same-owner --same-permissions --n rm -f "$BUNDLE" # Read launch parameters (KEY=VALUE, numeric values and absolute paths). -ROLE=combined +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="" @@ -110,11 +107,9 @@ cleanup() { } trap cleanup EXIT -# Workload runtime, in private network, mount, and PID namespaces. $1 is -# "loopback" for a network namespace with only loopback (combined role: the -# guard is in this VM and uses a Unix socket), or "veth" for a namespace -# that also has one veth link to this VM (workload role: the guard connects -# over TCP through the forwarder). Either way the resolver points at the +# 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. # @@ -123,7 +118,6 @@ trap cleanup EXIT # a connecting process's ancestors up to the namespace init; without the # namespace it would reach this root-owned script and fail. start_workload() { - local network="$1" require_numeric "$WORKLOAD_UID" "$WORKLOAD_GID" require_absolute "$WORKSPACE" install -d -m 0755 "$WORKSPACE" @@ -133,23 +127,17 @@ start_workload() { 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" - local -a enter - local -a unshare_common=(--pid --fork --kill-child --mount-proc --mount --propagation private) - if [ "$network" = veth ]; then - 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 - enter=(ip netns exec "$WORKLOAD_NETNS" unshare "${unshare_common[@]}" --) - else - enter=(unshare --net "${unshare_common[@]}" --) - fi - log "starting workload runtime as ${WORKLOAD_UID}:${WORKLOAD_GID} (${network} network)" - "${enter[@]}" /bin/bash -euc ' + 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 @@ -210,12 +198,8 @@ start_tunnel() { } case "$ROLE" in - combined) - start_workload loopback - start_guard - ;; workload) - start_workload veth + start_workload start_forwarder ;; guard) diff --git a/crates/openshell-driver-tensorlake/src/config.rs b/crates/openshell-driver-tensorlake/src/config.rs index 7cad411683..3d870a5827 100644 --- a/crates/openshell-driver-tensorlake/src/config.rs +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -18,47 +18,13 @@ 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 in the split topology. +/// Default vCPU count for a guard VM. pub const DEFAULT_GUARD_CPUS: f64 = 1.0; -/// Default memory in MiB for a guard VM in the split topology. The guard -/// uses about 32 MiB and the tunnel about 15 MiB. +/// 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; -/// Where the guard runs relative to the workload. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub enum Topology { - /// The guard runs in its own Tensorlake VM and reaches the workload VM - /// through a Tensorlake tunnel. Credentials never enter the workload VM. - #[default] - Split, - /// The guard and the workload share one VM. Test credentials only. - Combined, -} - -impl Topology { - pub const fn as_str(self) -> &'static str { - match self { - Self::Split => "split", - Self::Combined => "combined", - } - } -} - -impl std::str::FromStr for Topology { - type Err = String; - - fn from_str(value: &str) -> Result { - match value.trim().to_ascii_lowercase().as_str() { - "split" => Ok(Self::Split), - "combined" => Ok(Self::Combined), - other => Err(format!( - "unknown topology '{other}'; use 'split' or 'combined'" - )), - } - } -} - #[derive(Clone)] pub struct TensorlakeComputeConfig { /// Tensorlake sandbox lifecycle API base URL. @@ -85,8 +51,6 @@ pub struct TensorlakeComputeConfig { pub poll_interval: Duration, /// Default log level for the guard when the sandbox spec sets none. pub log_level: String, - /// Guard placement. - pub topology: Topology, /// Registered Tensorlake image for guard VMs. `None` uses /// `default_image`, which contains the guard and the Tensorlake CLI. pub guard_image: Option, @@ -112,7 +76,6 @@ impl std::fmt::Debug for TensorlakeComputeConfig { .field("timeout_secs", &self.timeout_secs) .field("allow_out", &self.allow_out) .field("poll_interval", &self.poll_interval) - .field("topology", &self.topology) .field("guard_image", &self.guard_image) .field("guard_cpus", &self.guard_cpus) .field("guard_memory_mb", &self.guard_memory_mb) @@ -185,7 +148,7 @@ impl TensorlakeComputeConfig { Ok(()) } - /// Image for guard VMs in the split topology. + /// Image for guard VMs. pub fn guard_image(&self) -> &str { self.guard_image.as_deref().unwrap_or(&self.default_image) } @@ -197,9 +160,9 @@ impl TensorlakeComputeConfig { .and_then(|url| url.host_str().map(str::to_string)) } - /// Tensorlake `allow_out` for the VM that runs the guard, with the hosts - /// the guard itself needs added: the gateway, and in the split topology - /// the Tensorlake hosts the tunnel talks to. + /// Tensorlake `allow_out` for the guard VM, with the hosts the guard + /// itself needs added: the gateway and the Tensorlake hosts the tunnel + /// talks to. pub fn effective_allow_out(&self) -> Vec { let mut entries = self.allow_out.clone(); if entries.is_empty() { @@ -216,9 +179,7 @@ impl TensorlakeComputeConfig { { push(host); } - if self.topology == Topology::Split - && let Some(host) = self.tensorlake_host() - { + if let Some(host) = self.tensorlake_host() { push(format!("*.{host}")); push(host); } @@ -244,7 +205,6 @@ pub(crate) mod tests { allow_out: Vec::new(), poll_interval: DEFAULT_POLL_INTERVAL, log_level: "info".into(), - topology: Topology::Combined, guard_image: None, guard_cpus: DEFAULT_GUARD_CPUS, guard_memory_mb: DEFAULT_GUARD_MEMORY_MB, @@ -266,7 +226,12 @@ pub(crate) mod tests { config.allow_out = vec!["api.anthropic.com".into()]; assert_eq!( config.effective_allow_out(), - vec!["api.anthropic.com", "gateway.example.com"] + vec![ + "api.anthropic.com", + "gateway.example.com", + "*.sandbox.tensorlake.ai", + "sandbox.tensorlake.ai" + ] ); } diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs index 3948d543d2..05faae7b4a 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -4,7 +4,7 @@ //! Tensorlake compute driver. //! //! Each `OpenShell` sandbox maps to one Tensorlake sandbox (a small VM) for -//! the workload and, in the default split topology, a second one for the +//! 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 @@ -36,14 +36,14 @@ use crate::client::{ CreateSandboxRequest, NetworkPolicy, ProcessInfo, Resources, SandboxInfo, StartProcessRequest, TensorlakeClient, TensorlakeError, }; -use crate::config::{TensorlakeComputeConfig, Topology}; +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 in the split topology. +/// 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. @@ -73,17 +73,16 @@ enum Phase { #[derive(Debug, Clone)] struct Record { sandbox: DriverSandbox, - /// The workload VM, or the only VM in the combined topology. + /// The workload VM. tensorlake_id: String, tensorlake_name: String, - /// The guard VM in the split topology. - guard_tensorlake_id: Option, + /// 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 and - /// in the combined topology. + /// PID of the launcher in the guard VM. `None` for recovered records. guard_launcher_pid: Option, } @@ -439,22 +438,17 @@ impl TensorlakeComputeDriver { if self.records.lock().await.contains_key(&sandbox.id) { return Err(Status::already_exists("sandbox already exists")); } - let split = self.config.topology == Topology::Split; - // The VM that runs the guard needs the gateway and, with a tunnel, - // the Tensorlake hosts. Empty keeps Tensorlake's default internet. + // The guard VM needs the gateway and the Tensorlake hosts. Empty + // keeps Tensorlake's default internet. let allow_out = self.config.effective_allow_out(); let guard_network = (!allow_out.is_empty()).then(|| NetworkPolicy { allow_internet_access: false, allow_out, deny_out: Vec::new(), }); - // The workload VM in the split topology gets no outbound path at - // all. Its connections travel over the boundary channel to the guard. - let workload_network = if split { - Some(NetworkPolicy::no_egress()) - } else { - guard_network.clone() - }; + // 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 @@ -491,47 +485,43 @@ impl TensorlakeComputeDriver { tensorlake_sandbox_id = %created.sandbox_id, "Created Tensorlake sandbox" ); - let guard_tensorlake_id = if split { - 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; - match guard { - Ok(guard) => { - info!( + 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 = %guard.sandbox_id, - "Created Tensorlake guard sandbox" + tensorlake_sandbox_id = %created.sandbox_id, + %cleanup, + "Failed to delete the workload VM after the guard VM create failed" ); - Some(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)); } + self.discard_state(&sandbox.id).await; + return Err(create_error(error)); } - } else { - None }; let record = Record { @@ -558,7 +548,7 @@ impl TensorlakeComputeDriver { .provision( &sandbox, &created.sandbox_id, - guard_tensorlake_id.as_deref(), + &guard_tensorlake_id, &identity, ) .await @@ -584,7 +574,7 @@ impl TensorlakeComputeDriver { &self, sandbox: &DriverSandbox, tensorlake_id: &str, - guard_tensorlake_id: Option<&str>, + guard_tensorlake_id: &str, identity: &ResolvedWorkloadIdentity, ) -> Result<(), String> { let started = Instant::now(); @@ -594,15 +584,11 @@ impl TensorlakeComputeDriver { else { return Ok(()); }; - let guard_info = match guard_tensorlake_id { - Some(guard_id) => match self - .wait_running(sandbox, guard_id, "guard", started) - .await? - { - Some(info) => Some(info), - None => return Ok(()), - }, - None => None, + let Some(guard_info) = self + .wait_running(sandbox, guard_tensorlake_id, "guard", started) + .await? + else { + return Ok(()); }; self.set_phase(&sandbox.id, Phase::Launching).await; self.publish_progress(&sandbox.id, LaunchProgress::VmRunning); @@ -620,24 +606,18 @@ impl TensorlakeComputeDriver { .write_file(&workload_info, launch::BUNDLE_UPLOAD_PATH, bundles.workload) .await .map_err(|error| format!("upload launch bundle: {error}"))?; - let guard_launcher_pid = - if let (Some(guard_info), Some(bundle)) = (&guard_info, bundles.guard) { - self.client - .write_file(guard_info, launch::BUNDLE_UPLOAD_PATH, bundle) - .await - .map_err(|error| format!("upload guard launch bundle: {error}"))?; - self.publish_progress(&sandbox.id, LaunchProgress::StartingLauncher); - Some(self.start_launcher(sandbox, guard_info, "guard").await?) - } else { - self.publish_progress(&sandbox.id, LaunchProgress::StartingLauncher); - None - }; + self.client + .write_file(&guard_info, launch::BUNDLE_UPLOAD_PATH, bundles.guard) + .await + .map_err(|error| format!("upload guard launch bundle: {error}"))?; + 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) { record.launcher_pid = Some(launcher_pid); - record.guard_launcher_pid = guard_launcher_pid; + record.guard_launcher_pid = Some(guard_launcher_pid); } self.set_phase(&sandbox.id, Phase::Running).await; self.publish_progress(&sandbox.id, LaunchProgress::LauncherStarted); @@ -761,7 +741,10 @@ impl TensorlakeComputeDriver { (record.tensorlake_id, record.guard_tensorlake_id) }; let mut remaining = false; - for id in std::iter::once(&tensorlake_id).chain(guard_tensorlake_id.as_ref()) { + for id in [&tensorlake_id, &guard_tensorlake_id] { + if id.is_empty() { + continue; + } remaining |= self .client .delete_sandbox(id) @@ -869,7 +852,7 @@ impl TensorlakeComputeDriver { .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, self.config.topology) else { + let Some(phase) = recovered_phase(workload, guard) else { continue; }; let saved = match self.state.load(sandbox_id).await { @@ -939,13 +922,8 @@ impl TensorlakeComputeDriver { .collect(); for (sandbox_id, record) in records { let info = observed.get(&record.tensorlake_id); - let guard_vm = record - .guard_tensorlake_id - .as_ref() - .map_or(GuardVm::NotUsed, |id| { - observed.get(id).map_or(GuardVm::Gone, GuardVm::Present) - }); - match reconcile(&record.phase, info, guard_vm) { + 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, @@ -955,7 +933,7 @@ impl TensorlakeComputeDriver { } let launchers = [ (info, record.launcher_pid, "workload"), - (guard_vm.info(), record.guard_launcher_pid, "guard"), + (guard_info, record.guard_launcher_pid, "guard"), ]; for (info, pid, role) in launchers { if let (Some(info), Some(pid)) = (info, pid) @@ -1030,7 +1008,9 @@ fn recovered_record( sandbox, tensorlake_id: anchor.sandbox_id.clone(), tensorlake_name: tensorlake_name(sandbox_id), - guard_tensorlake_id: guard.map(|info| info.sandbox_id.clone()), + guard_tensorlake_id: guard + .map(|info| info.sandbox_id.clone()) + .unwrap_or_default(), identity: None, phase, launcher_pid: None, @@ -1038,11 +1018,7 @@ fn recovered_record( }) } -fn recovered_phase( - workload: Option<&SandboxInfo>, - guard: Option<&SandboxInfo>, - topology: Topology, -) -> Option { +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 { @@ -1055,13 +1031,13 @@ fn recovered_phase( reason: "PairIncomplete".into(), message: format!("the {what} VM of this sandbox is gone; delete and recreate it"), }; - Some(match (workload_phase, guard_phase, topology) { - (None, None, _) => return None, - (Some(Phase::Pending), _, _) | (_, Some(Phase::Pending), _) => restarted(), - (None, Some(_), _) => half("workload"), - (Some(_), None, Topology::Split) => half("guard"), - (Some(Phase::Suspended), _, _) | (_, Some(Phase::Suspended), _) => Phase::Suspended, - (Some(phase), _, _) => phase, + Some(match (workload_phase, guard_phase) { + (None, None) => return None, + (Some(Phase::Pending), _) | (_, Some(Phase::Pending)) => restarted(), + (None, Some(_)) => half("workload"), + (Some(_), None) => half("guard"), + (Some(Phase::Suspended), _) | (_, Some(Phase::Suspended)) => Phase::Suspended, + (Some(phase), _) => phase, }) } @@ -1072,35 +1048,16 @@ enum Reconcile { Set(Phase), } -/// What one poll saw of a sandbox's guard VM. -#[derive(Debug, Clone, Copy)] -enum GuardVm<'a> { - /// Combined topology: there is no guard VM. - NotUsed, - /// Split topology, but Tensorlake no longer lists the guard VM. - Gone, - Present(&'a SandboxInfo), -} - -impl<'a> GuardVm<'a> { - fn info(self) -> Option<&'a SandboxInfo> { - match self { - Self::Present(info) => Some(info), - Self::NotUsed | Self::Gone => None, - } - } -} - -/// Decide how one poll observation changes a record. -fn reconcile(current: &Phase, workload: Option<&SandboxInfo>, guard: GuardVm<'_>) -> Reconcile { +/// 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); - // `None` when the topology has no guard VM; `Some(None)` when it is gone. - let guard_phase = match guard { - GuardVm::NotUsed => None, - GuardVm::Gone => Some(None), - GuardVm::Present(info) => Some(observed_phase(info)), - }; - let any_present = workload_phase.is_some() || matches!(guard_phase, Some(Some(_))); + 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, @@ -1116,11 +1073,9 @@ fn reconcile(current: &Phase, workload: Option<&SandboxInfo>, guard: GuardVm<'_> if workload_phase .as_ref() .is_some_and(|phase| *phase != Phase::Suspended) - && guard_phase.as_ref().is_none_or(|phase| { - phase - .as_ref() - .is_some_and(|phase| *phase != Phase::Suspended) - }) => + && guard_phase + .as_ref() + .is_some_and(|phase| *phase != Phase::Suspended) => { return Reconcile::Keep; } @@ -1137,8 +1092,8 @@ fn reconcile(current: &Phase, workload: Option<&SandboxInfo>, guard: GuardVm<'_> }; match (workload_phase, guard_phase) { (None, _) => gone("workload", workload), - (Some(_), Some(None)) => gone("guard", guard.info()), - (Some(Phase::Suspended), _) | (_, Some(Some(Phase::Suspended))) => { + (Some(_), None) => gone("guard", guard), + (Some(Phase::Suspended), _) | (_, Some(Phase::Suspended)) => { Reconcile::Set(Phase::Suspended) } (Some(next), _) => Reconcile::Set(next), @@ -1448,16 +1403,10 @@ mod tests { #[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, None, GuardVm::NotUsed), - Reconcile::Keep - ); - assert_eq!( - reconcile(&Phase::Launching, None, GuardVm::NotUsed), - Reconcile::Keep - ); - assert_eq!( - reconcile(&Phase::Pending, Some(&info("running")), GuardVm::NotUsed), + reconcile(&Phase::Pending, Some(&info("running")), None), Reconcile::Keep ); } @@ -1470,67 +1419,61 @@ mod tests { }; for status in ["pending", "running"] { let vm = info(status); - assert_eq!( - reconcile(&failed, Some(&vm), GuardVm::NotUsed), - Reconcile::Keep - ); - assert_eq!( - reconcile(&failed, Some(&vm), GuardVm::Present(&vm)), - Reconcile::Keep - ); + 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, None, GuardVm::NotUsed), + 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, None, GuardVm::NotUsed), - Reconcile::Forget - ); - assert_eq!( - reconcile(&Phase::Deleting, Some(&info("running")), GuardVm::NotUsed), + reconcile(&Phase::Deleting, Some(&info("running")), None), Reconcile::Keep ); assert_eq!( - reconcile(&Phase::Running, Some(&info("suspended")), GuardVm::NotUsed), + reconcile(&Phase::Running, Some(&info("suspended")), Some(&guard)), Reconcile::Set(Phase::Suspended) ); assert_eq!( - reconcile(&Phase::Suspended, Some(&info("running")), GuardVm::NotUsed), + reconcile(&Phase::Suspended, Some(&info("running")), Some(&guard)), Reconcile::Set(Phase::Running) ); assert!(matches!( - reconcile(&Phase::Running, Some(&info("terminated")), GuardVm::NotUsed), + reconcile(&Phase::Running, Some(&info("terminated")), Some(&guard)), Reconcile::Set(Phase::Failed { reason, .. }) if reason == "TensorlakeTerminated" )); } #[test] - fn reconcile_tracks_both_vms_of_a_split_sandbox() { + 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), GuardVm::Present(&running)), + reconcile(&Phase::Running, Some(&running), Some(&running)), Reconcile::Set(Phase::Running) ); // Delete finishes only when both are gone. assert_eq!( - reconcile(&Phase::Deleting, None, GuardVm::Present(&running)), + reconcile(&Phase::Deleting, None, Some(&running)), Reconcile::Keep ); - assert_eq!( - reconcile(&Phase::Deleting, None, GuardVm::Gone), - Reconcile::Forget - ); + 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), GuardVm::Gone) + reconcile(&Phase::Running, Some(&running), None) else { panic!("a lost guard VM must fail the sandbox"); }; @@ -1538,11 +1481,7 @@ mod tests { assert!(message.contains("guard")); // A suspended guard VM suspends the sandbox. assert_eq!( - reconcile( - &Phase::Running, - Some(&running), - GuardVm::Present(&suspended) - ), + reconcile(&Phase::Running, Some(&running), Some(&suspended)), Reconcile::Set(Phase::Suspended) ); } @@ -1604,10 +1543,7 @@ mod tests { assert_eq!(snapshot.namespace, "default"); assert_eq!(snapshot.workspace, "ws"); assert_eq!(record.tensorlake_id, workload.sandbox_id); - assert_eq!( - record.guard_tensorlake_id.as_deref(), - Some(guard.sandbox_id.as_str()) - ); + 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"); @@ -1642,25 +1578,17 @@ mod tests { 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, Topology::Split), - Some(Phase::Running) - ); - // A workload VM without its guard: fine in the combined topology, - // broken in the split topology. + assert_eq!(recovered_phase(workload, guard), Some(Phase::Running)); + // A workload VM without its guard is broken. let (_, workload, guard) = pairs[1]; - assert_eq!( - recovered_phase(workload, guard, Topology::Combined), - Some(Phase::Running) - ); assert!(matches!( - recovered_phase(workload, guard, Topology::Split), + 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, Topology::Split), + recovered_phase(workload, guard), Some(Phase::Failed { reason, .. }) if reason == "PairIncomplete" )); // A pending VM at restart cannot finish launching. @@ -1668,16 +1596,11 @@ mod tests { recovered_phase( Some(&named("openshell-d", "running")), Some(&named("openshell-d-guard", "pending")), - Topology::Split ), Some(Phase::Failed { reason, .. }) if reason == "DriverRestarted" )); assert_eq!( - recovered_phase( - Some(&named("openshell-e", "terminated")), - None, - Topology::Split - ), + recovered_phase(Some(&named("openshell-e", "terminated")), None), None ); } diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs index 57e4e21cd2..4af4ccbfc3 100644 --- a/crates/openshell-driver-tensorlake/src/launch.rs +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -14,14 +14,11 @@ //! - `/.openshell/tunnel/*` belongs to the tunnel identity (mode 0700). It //! holds the Tensorlake key the guard VM's tunnel authenticates with. //! -//! Split topology (default): 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. -//! -//! Combined topology: one VM gets both sides. The launcher starts the -//! workload in a network namespace that has only loopback. +//! 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}; @@ -64,7 +61,6 @@ pub const FORWARDER_UID: u32 = 65_533; pub const FORWARDER_GID: u32 = 65_533; const WORKSPACE: &str = "/sandbox"; -const SOCKET_PATH: &str = "/.openshell/channel/sandbox/control.sock"; 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"; @@ -86,8 +82,6 @@ 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 { - /// Workload and guard in one VM. - Combined, /// Only `openshell-sandbox`, listening for a remote guard. Workload, /// Only the tunnel and `openshell-supervisor`. @@ -97,7 +91,6 @@ pub enum Role { impl Role { const fn as_str(self) -> &'static str { match self { - Self::Combined => "combined", Self::Workload => "workload", Self::Guard => "guard", } @@ -158,19 +151,16 @@ pub fn resolve_identity( } /// Evidence for the outer fence the driver requested. The driver cannot -/// inspect the VM, so the evidence names the recipe. -/// -/// Split: 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. Combined: a loopback-only network namespace has no route -/// out. Either way egress needs a mediated decision, revocation takes effect -/// at the guard, and guard loss leaves the workload without a path. +/// 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, - #[serde(skip_serializing_if = "Option::is_none")] - guard_tensorlake_sandbox_id: Option<&'a str>, + guard_tensorlake_sandbox_id: &'a str, workload_network: &'static str, launcher: &'static str, } @@ -178,21 +168,17 @@ struct TensorlakeOuterFenceEvidence<'a> { /// Bind the launch recipe to one generation as provisioning evidence. fn provisioning_evidence( tensorlake_sandbox_id: &str, - guard_tensorlake_sandbox_id: Option<&str>, + guard_tensorlake_sandbox_id: &str, generation: &str, ) -> Result { - if tensorlake_sandbox_id.is_empty() || guard_tensorlake_sandbox_id == Some("") { + 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 (topology, workload_network) = match guard_tensorlake_sandbox_id { - Some(_) => ("split", "private-netns-veth-to-forwarder-no-egress"), - None => ("combined", "private-loopback-only"), - }; let evidence = TensorlakeOuterFenceEvidence { - topology, + topology: "split", tensorlake_sandbox_id, guard_tensorlake_sandbox_id, - workload_network, + workload_network: "private-netns-veth-to-forwarder-no-egress", launcher: LAUNCHER_PATH, }; let encoded = serde_json::to_vec(&evidence).map_err(invalid)?; @@ -323,10 +309,10 @@ fn nul_list>(items: I) -> Vec { pub struct LaunchBundleInput<'a> { pub sandbox: &'a DriverSandbox, pub config: &'a TensorlakeComputeConfig, - /// The workload VM (split) or the only VM (combined). + /// The workload VM. pub tensorlake_sandbox_id: &'a str, - /// The guard VM. `None` builds the combined bundle. - pub guard_tensorlake_id: Option<&'a str>, + /// The guard VM. + pub guard_tensorlake_id: &'a str, pub identity: &'a ResolvedWorkloadIdentity, pub gateway_ca_pem: Option<&'a [u8]>, } @@ -334,11 +320,10 @@ pub struct LaunchBundleInput<'a> { /// The tar archives for one sandbox generation. Paths are relative to `/`. #[derive(Debug)] pub struct LaunchBundles { - /// Uploaded to the workload VM, or to the only VM in the combined - /// topology, where it also carries the guard files. + /// Uploaded to the workload VM. pub workload: Vec, - /// Uploaded to the guard VM. `None` in the combined topology. - pub guard: Option>, + /// Uploaded to the guard VM. + pub guard: Vec, } /// Build the launch bundles. @@ -381,9 +366,10 @@ pub fn build_launch_bundles(input: LaunchBundleInput<'_>) -> Result) -> Result) -> Result Result<(), String> { use std::fmt::Write as _; let mut params = format!("ROLE={}\nWORKSPACE={WORKSPACE}\n", role.as_str()); - if matches!(role, Role::Combined | Role::Workload) { - writeln!( + match role { + Role::Workload => writeln!( params, - "WORKLOAD_UID={}\nWORKLOAD_GID={}", + "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 - ) - .expect("writing to a String cannot fail"); - } - if matches!(role, Role::Combined | Role::Guard) { - writeln!( - params, - "SUPERVISOR_UID={SUPERVISOR_UID}\nSUPERVISOR_GID={SUPERVISOR_GID}\nSUPERVISOR_RUN_DIR={SUPERVISOR_RUN_DIR}" - ) - .expect("writing to a String cannot fail"); - } - if role == Role::Workload { - writeln!( - params, - "FORWARDER_UID={FORWARDER_UID}\nFORWARDER_GID={FORWARDER_GID}\nWORKLOAD_LISTEN_PORT={WORKLOAD_LISTEN_PORT}\nWORKLOAD_FORWARD_PORT={WORKLOAD_FORWARD_PORT}" - ) - .expect("writing to a String cannot fail"); - } - if role == Role::Guard { - writeln!( + ), + Role::Guard => writeln!( params, - "TUNNEL_UID={TUNNEL_UID}\nTUNNEL_GID={TUNNEL_GID}\nTUNNEL_RUN_DIR={TUNNEL_RUN_DIR}" - ) - .expect("writing to a String cannot fail"); + "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()) } @@ -773,16 +719,14 @@ mod tests { #[test] fn provisioning_evidence_binds_generation() { - let evidence = provisioning_evidence("tl-1", None, "gen-1").unwrap(); + 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", None, "gen-1").unwrap(); + let other = provisioning_evidence("tl-2", "tl-2-guard", "gen-1").unwrap(); assert_ne!(evidence.evidence_digest, other.evidence_digest); - assert!(provisioning_evidence("", None, "gen-1").is_err()); - assert!(provisioning_evidence("tl-1", None, "").is_err()); - assert!(provisioning_evidence("tl-1", Some(""), "gen-1").is_err()); - let split = provisioning_evidence("tl-1", Some("tl-1-guard"), "gen-1").unwrap(); - assert_ne!(split.evidence_digest, evidence.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] @@ -808,7 +752,7 @@ mod tests { sandbox: &sandbox, config: &config, tensorlake_sandbox_id: "tl-1", - guard_tensorlake_id: None, + guard_tensorlake_id: "tl-1-guard", identity: &identity, gateway_ca_pem: None, }); @@ -879,60 +823,6 @@ mod tests { .unwrap_or_else(|| panic!("{path} missing from bundle")) } - #[test] - fn combined_bundle_separates_workload_and_guard_material() { - let sandbox = launch_sandbox(); - let identity = resolve_identity(&sandbox, "img").unwrap(); - let config = crate::config::tests::test_config(); - let bundles = build_launch_bundles(LaunchBundleInput { - sandbox: &sandbox, - config: &config, - tensorlake_sandbox_id: "tl-1", - guard_tensorlake_id: None, - identity: &identity, - gateway_ca_pem: Some(b"ca"), - }) - .unwrap(); - assert!(bundles.guard.is_none()); - let entries = read_entries(&bundles.workload); - - // Workload side: bootstrap and boundary key only, owned by the workload. - let (mode, uid, bootstrap) = &entries[BOOTSTRAP_PATH.trim_start_matches('/')]; - assert_eq!((*mode, *uid), (0o600, 1000)); - let bootstrap = String::from_utf8_lossy(bootstrap); - assert!(bootstrap.contains("\"FOO\"")); - assert!(!bootstrap.contains("gateway.token.value")); - assert!(!bootstrap.contains("sandbox.jwt.value")); - - // Guard side: credentials owned by the guard identity. - for path in [AUTH_BUNDLE_PATH, SANDBOX_TOKEN_PATH, GATEWAY_CA_PATH] { - let (mode, uid, _) = &entries[path.trim_start_matches('/')]; - assert_eq!((*mode, *uid), (0o600, u64::from(SUPERVISOR_UID)), "{path}"); - } - let (mode, uid, _) = &entries[SUPERVISOR_DIR.trim_start_matches('/')]; - assert_eq!((*mode, *uid), (0o700, u64::from(SUPERVISOR_UID))); - - let (_, _, env) = &entries[SUPERVISOR_ENV_PATH.trim_start_matches('/')]; - let env = String::from_utf8_lossy(env); - assert!(env.contains("OPENSHELL_ENDPOINT=https://gateway.example.com:8080\0")); - assert!(env.contains(&format!("OPENSHELL_TLS_CA={GATEWAY_CA_PATH}\0"))); - assert!(env.contains(&format!( - "OPENSHELL_SANDBOX_TOKEN_FILE={SANDBOX_TOKEN_PATH}\0" - ))); - assert!(env.contains("OPENSHELL_NETWORK_RUNTIME_CAPABILITIES=\0")); - assert!(!env.contains("sandbox.jwt.value")); - - let (_, _, params) = &entries[LAUNCH_PARAMS_PATH.trim_start_matches('/')]; - let params = String::from_utf8_lossy(params); - assert!(params.contains("ROLE=combined\n")); - assert!(params.contains("WORKLOAD_UID=1000\n")); - assert!(params.contains("SUPERVISOR_UID=65534\n")); - assert!(!params.contains("TUNNEL_UID")); - assert!(!entries.contains_key(TUNNEL_ENV_PATH.trim_start_matches('/'))); - let bootstrap = String::from_utf8_lossy(&entry(&entries, BOOTSTRAP_PATH).2); - assert!(bootstrap.contains(SOCKET_PATH)); - } - #[test] fn split_bundles_keep_every_secret_out_of_the_workload_vm() { let sandbox = launch_sandbox(); @@ -944,7 +834,7 @@ mod tests { sandbox: &sandbox, config: &config, tensorlake_sandbox_id: "tl-1", - guard_tensorlake_id: Some("tl-1-guard"), + guard_tensorlake_id: "tl-1-guard", identity: &identity, gateway_ca_pem: Some(b"ca"), }) @@ -984,7 +874,7 @@ mod tests { // Guard VM: credentials for the guard, the key for the tunnel, no // channel server key. - let guard = read_entries(bundles.guard.as_deref().unwrap()); + 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); diff --git a/crates/openshell-driver-tensorlake/src/main.rs b/crates/openshell-driver-tensorlake/src/main.rs index 355749e77a..6d6bb87f5e 100644 --- a/crates/openshell-driver-tensorlake/src/main.rs +++ b/crates/openshell-driver-tensorlake/src/main.rs @@ -12,7 +12,6 @@ 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, - Topology, }; use openshell_driver_tensorlake::{ ComputeDriverService, TensorlakeComputeConfig, TensorlakeComputeDriver, @@ -63,12 +62,6 @@ struct Args { #[arg(long, env = "OPENSHELL_SANDBOX_IMAGE")] sandbox_image: String, - /// Where the guard runs. `split` puts it in its own VM and reaches the - /// workload VM through a Tensorlake tunnel, so credentials never enter - /// the workload VM. `combined` shares one VM; test credentials only. - #[arg(long, env = "OPENSHELL_TENSORLAKE_TOPOLOGY", default_value = "split")] - topology: Topology, - /// 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")] @@ -149,7 +142,6 @@ async fn main() -> Result<()> { .collect(), poll_interval: Duration::from_secs(args.poll_interval_secs.max(1)), log_level: args.log_level, - topology: args.topology, guard_image: args.guard_image, guard_cpus: args.guard_cpus, guard_memory_mb: args.guard_memory_mb, diff --git a/docs/how-it-works/sandboxes/tensorlake.mdx b/docs/how-it-works/sandboxes/tensorlake.mdx index 333544cd9e..84261024ea 100644 --- a/docs/how-it-works/sandboxes/tensorlake.mdx +++ b/docs/how-it-works/sandboxes/tensorlake.mdx @@ -32,10 +32,6 @@ 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. -Set `--topology combined` to run both in one VM. That halves the VM count but -puts the credentials in the same kernel as the agent, so use it with test -credentials only. - 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 @@ -149,7 +145,6 @@ socket_path = "/run/openshell/tensorlake.sock" | `--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. | -| `--topology` | `OPENSHELL_TENSORLAKE_TOPOLOGY` | `split`. `combined` runs guard and workload in one VM. | | `--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 | @@ -186,9 +181,8 @@ replace a published version. Publish a new one. ## Trust Model -In the split topology 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 +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. @@ -201,9 +195,6 @@ Two things to know: - 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. -In the combined topology a root user in the one VM can read the guard's -credentials. Use it with test credentials only. - ## Limits - Stop and start are not supported. Delete the sandbox instead. @@ -215,8 +206,8 @@ credentials. Use it with test credentials only. - After a driver restart, sandboxes that had not finished launching are reported as failed. Running sandboxes are recovered from the saved requests in `--state-dir`. Keep that directory with the gateway database. -- The split topology uses two Tensorlake VMs per sandbox. The guard VM - defaults to 1 vCPU and 1 GiB. +- Each sandbox uses two Tensorlake VMs. The guard VM defaults to 1 vCPU and + 1 GiB. For build details, the test runbook, and the design notes, see the [driver README](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-tensorlake/README.md). From da3e8ed43247b24ff7b13908b90c3dbfb5c145f5 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 17:13:48 -0500 Subject: [PATCH 25/31] docs(driver-tensorlake): drop the note about the removed one-VM mode Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 39b92f740e..6339de727c 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -116,8 +116,7 @@ it from outside. 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. A one-VM -mode existed and was removed: it was cheaper, unverified, and unsafe. +Kubernetes driver, which runs one guard pod per workload pod. | Attacker | Gets | |---|---| From b5dc178fe07f71a614b7dfe87ff9c17af7cf5f46 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 20:37:59 -0500 Subject: [PATCH 26/31] fix(driver-tensorlake): keep DNS working under --allow-out With an allow list, the driver sent allow_internet_access: false for the guard VM. Tensorlake then blocks all DNS, so the tunnel could not resolve its own API host and every guard launcher exited with a DNS error. Keep internet access on in the Tensorlake policy when an allow list is set. Tensorlake then connects only to the listed hosts and its resolver answers only for them. Add the platform API host, where the tunnel checks its key, to the allow list and to the tunnel environment through a new --tensorlake-platform-api-url flag. Record the runbook results in the README and remove the runbook: the conformance scenarios, launcher kills, driver restart recovery, idle timeout, allow list, and delete all passed on Tensorlake on 2026-10-20. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 317 +++--------------- .../openshell-driver-tensorlake/src/config.rs | 99 ++++-- .../openshell-driver-tensorlake/src/driver.rs | 8 +- .../openshell-driver-tensorlake/src/launch.rs | 14 +- .../openshell-driver-tensorlake/src/main.rs | 11 + docs/how-it-works/sandboxes/tensorlake.mdx | 14 +- 6 files changed, 137 insertions(+), 326 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 6339de727c..5f8559214e 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -255,6 +255,7 @@ openshell-gateway --compute-driver tensorlake \ | `--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 | @@ -273,15 +274,19 @@ 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, and only incoming traffic resets -it. The guard's traffic to the gateway is outgoing. So a short timeout can -pause a sandbox that is still working. Keep the default `0`, which uses the -longest timeout your plan allows. +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 driver turns off internet access for the -VM that runs the guard and allows only the hosts you listed, the gateway -host, and the Tensorlake host that the tunnel talks to. The workload VM -always has internet access off with an empty allow list. +When you set `--allow-out`, the VM that runs the guard can connect only to +the hosts you listed, the gateway host, and the two Tensorlake hosts the +tunnel talks to: the sandbox API and the platform API. 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 @@ -413,8 +418,9 @@ workloads in it. failed with reason `DriverRestarted`. A pair with one VM missing is reported as failed with reason `PairIncomplete`. A pair whose VMs were running but whose launch scripts had not started yet is recovered as - running, and the gateway then waits for a guard that never connects. - Delete and recreate such a sandbox. + running. The gateway then keeps it in `Provisioning` with reason + `ConfigurationPending`, and it never becomes Ready. Delete and recreate + such a sandbox. - Anyone with access to your Tensorlake project can run `tl sbx exec --user root` in the guard VM and read its credentials, or in the workload VM and get around OpenShell policy. Keep the control plane @@ -492,6 +498,25 @@ End-to-end runs on Tensorlake Cloud confirmed: 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` (see [Limits](#limits)). + 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. Three findings shaped the design. The sandbox runtime rejects boundary peers on loopback, so the tunnel needs the veth forwarder. Binary @@ -500,273 +525,7 @@ so the runtime must run in its own PID namespace. And the transparent TCP capabi is for guards that share the workload's network namespace, so this driver no longer grants it. -### Still to confirm - -- The conformance scenarios `smoke`, `file_transfer`, and `policy_advisor` - pass. -- The port proxy keeps a long-lived connection open, and the idle timeout - does not pause a sandbox whose only traffic is the guard's outgoing - session. -- A driver restart recovers running sandbox pairs. -- Which Tensorlake hosts the tunnel needs, so `--allow-out` can be tight on - the guard VM. - -### Runbook - -This runbook covers the items in [Still to confirm](#still-to-confirm). -Remove the steps that pass once they are recorded above. - -Use two shells. Shell A keeps the tunnel open. Shell B runs everything -else. Some steps run `deploy.sh` again, so keep the exported variables in -shell B for the whole run. The steps assume the control sandbox is -`openshell-control`, the CLI gateway is named `tensorlake`, and the tunnel -listens on port 18080. - -Each OpenShell sandbox has two Tensorlake VMs: `openshell-` for the -workload and `openshell--guard` for the guard, where `` is the -OpenShell sandbox ID. `tl sbx ls` shows both names. The commands below -call them `$WORKLOAD_VM` and `$GUARD_VM`. - -#### 0. Build and deploy the control plane - -Build the two images. Skip this if you already have a pair you trust: - -```shell -cd ~/Documents/work/OpenShell -SANDBOX_IMAGE=openshell-tensorlake-test CONTROL_IMAGE=openshell-control-test \ - crates/openshell-driver-tensorlake/build-images.sh -``` - -Export the deploy settings. For a test gateway without a login service: - -```shell -export TENSORLAKE_API_KEY=your_api_key -export CONTROL_IMAGE=openshell-control-test -export OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1 -``` - -With a login service, replace the last line with -`export OPENSHELL_OIDC_ISSUER=https://issuer.example.com`. - -Deploy. Use `RECREATE=1` if a control sandbox already exists and you want -the new image: - -```shell -RECREATE=1 crates/openshell-driver-tensorlake/control/deploy.sh -``` - -The script prints the public URL and the sandbox ID. Check that the -control plane came up: - -```shell -tl sbx logs openshell-control | tail -20 -``` - -Expected: a line `control plane started at https://8080-...` and no -`error` lines. - -Open the tunnel in shell A: - -```shell -tl sbx tunnel openshell-control 8080 --listen-port 18080 -``` - -Back in shell B, build the CLI, register the gateway, and check it: - -```shell -cargo build -p openshell-cli -export OPENSHELL_BIN=$PWD/target/debug/openshell -$OPENSHELL_BIN gateway add http://127.0.0.1:18080 --name tensorlake -export OPENSHELL_GATEWAY=tensorlake -$OPENSHELL_BIN gateway list -$OPENSHELL_BIN status -``` - -If the gateway name is already registered from an earlier run, the add -fails. Remove the old entry first with -`$OPENSHELL_BIN gateway remove tensorlake`, or pick a new name and export -that instead. Both commands must succeed before you go on. - -Create one sandbox and watch the launch steps: - -```shell -$OPENSHELL_BIN sandbox create --name hello -- echo hello -``` - -Expected: the CLI shows the VM request, the VM start, the bundle upload, -and the wait for the guard, then prints `hello`. `tl sbx ls` shows two -new VMs. Delete it with `$OPENSHELL_BIN sandbox delete hello`. - -#### 1. Conformance suite - -Allow up to an hour. Each scenario creates its own sandboxes and deletes -them. Run the three test files that fit this driver and save the output: - -```shell -cargo test --locked \ - --manifest-path tests/suites/conformance/Cargo.toml \ - --package openshell-test-conformance-cli \ - --test smoke --test file_transfer --test policy_advisor \ - --no-fail-fast -- --test-threads=1 --nocapture 2>&1 \ - | tee ~/tensorlake-conformance.log -``` - -Do not run `--test lifecycle`. It stops and starts a sandbox, which this -driver rejects by design. - -In the log, the line to look for is `DENIED` from the `denied-tcp-open` -step of `mechanistic-proposal`. - -#### 2. Launch script death - -The driver watches the launch script in both VMs. Test both roles. - -```shell -$OPENSHELL_BIN sandbox create --name kill-test --detach -$OPENSHELL_BIN sandbox get kill-test -``` - -Repeat the get until it shows Ready. Then find the two VM names and -confirm that the launch script runs in each: - -```shell -tl sbx ls | grep openshell- -export WORKLOAD_VM=openshell- -export GUARD_VM=openshell--guard -tl sbx ps $WORKLOAD_VM -tl sbx ps $GUARD_VM -``` - -Kill the script in the guard VM first: - -```shell -tl sbx exec --user root $GUARD_VM pkill -f openshell-tensorlake-launch -sleep 10 -$OPENSHELL_BIN sandbox get kill-test -``` - -Expected: Ready is False, the reason is `LauncherExited`, and the message -names the guard launcher and the guard VM. Delete the sandbox, create it -again, and repeat with `$WORKLOAD_VM`. Expected: the same reason, with -the message naming the workload launcher. Keep the second sandbox for -step 6. - -#### 3. Driver restart - -Create one sandbox and wait for Ready. Then create a second and do not -wait: - -```shell -$OPENSHELL_BIN sandbox create --name restart-a --detach -$OPENSHELL_BIN sandbox get restart-a -$OPENSHELL_BIN sandbox create --name restart-b --detach -``` - -Restart the control plane by running the deploy script again with the -same variables. Without `RECREATE=1`, it keeps the sandbox and the gateway -state and only restarts the process: - -```shell -crates/openshell-driver-tensorlake/control/deploy.sh -``` - -If the tunnel in shell A dropped, start it again. Then check: - -```shell -tl sbx logs openshell-control | grep -i recovered -$OPENSHELL_BIN sandbox list -$OPENSHELL_BIN sandbox exec --name restart-a --no-tty -- echo hello -$OPENSHELL_BIN sandbox get restart-b -``` - -Expected: a `Recovered Tensorlake sandboxes` log line, `restart-a` still -Ready with the exec printing `hello`, and `restart-b` Failed with reason -`DriverRestarted` if a VM was still pending at restart time. If both VMs -of `restart-b` were already running, the driver recovers it as running. -It then becomes Ready only if its launch scripts had started before the -restart. Record which case you saw. The gateway log must show no -`name cannot be changed after creation` error: the driver reports each -recovered sandbox under the name in its saved request. - -#### 4. Idle timeout - -Read the timeout that the control sandbox got from the default of `0`: - -```shell -tl sbx describe openshell-control -``` - -Note the timeout value. That is the plan maximum. Then run a bounded test -with a 3 minute timeout. `deploy.sh` forwards every `OPENSHELL_TENSORLAKE_*` -variable to the driver: - -```shell -OPENSHELL_TENSORLAKE_TIMEOUT_SECS=180 crates/openshell-driver-tensorlake/control/deploy.sh -$OPENSHELL_BIN sandbox create --name idle-test --detach -$OPENSHELL_BIN sandbox get idle-test -``` - -Wait for Ready, then leave it alone for 5 minutes and check: - -```shell -sleep 300 -$OPENSHELL_BIN sandbox get idle-test -tl sbx ls | grep openshell- -``` - -Expected: the sandbox shows Suspended, because the guard's outgoing -session did not reset the idle clock. That confirms the plan maximum must -be long enough for a user session. Afterwards, deploy again without the -variable to restore the default: - -```shell -crates/openshell-driver-tensorlake/control/deploy.sh -``` - -#### 5. Tunnel hosts and `--allow-out` - -Find which hosts the tunnel in a guard VM talks to. Use a Ready sandbox, -for example `restart-a`: - -```shell -tl sbx exec --user root $GUARD_VM ss -tnp -tl sbx exec --user root $GUARD_VM cat /etc/hosts -``` - -Note the peer addresses of the `tl` process and resolve them. Then -deploy with an allow list and check that a sandbox still becomes Ready: - -```shell -OPENSHELL_TENSORLAKE_ALLOW_OUT=api.anthropic.com crates/openshell-driver-tensorlake/control/deploy.sh -$OPENSHELL_BIN sandbox create --name allow-test -- echo hello -``` - -Expected: `hello`. If the sandbox never becomes Ready, read -`tl sbx logs $GUARD_VM`. A tunnel that cannot reach its host exits, and -the driver reports `LauncherExited` for the guard. Make -`effective_allow_out` in `src/config.rs` add the hosts you found, then -deploy again without the variable. - -#### 6. Delete - -```shell -$OPENSHELL_BIN sandbox delete kill-test restart-a restart-b idle-test allow-test -sleep 10 -$OPENSHELL_BIN sandbox list -tl sbx ls -``` - -Expected: no sandboxes in the first list, and no names starting with -`openshell-` in the second, apart from `openshell-control`. - -#### What to collect - -- The conformance log file. -- The output of each `get`, `list`, and `ps` command. -- The last 50 lines of `tl sbx logs openshell-control`. -- The tunnel peer addresses from step 5. - -## After the runbook passes +## Next steps This section is a temporary plan. Remove it once the work is done. @@ -816,8 +575,8 @@ you record the final run. Run the `Tensorlake Images` workflow with a version and `public: true`, or run `PUBLIC=1 VERSION= build-images.sh` from a clean checkout in -the project that owns the public images. Do this only after the runbook -passes, because a published version cannot be replaced. +the project that owns the public images. Publish from a commit whose +tests passed, because a published version cannot be replaced. ### 3. Later diff --git a/crates/openshell-driver-tensorlake/src/config.rs b/crates/openshell-driver-tensorlake/src/config.rs index 3d870a5827..1ba5137d9c 100644 --- a/crates/openshell-driver-tensorlake/src/config.rs +++ b/crates/openshell-driver-tensorlake/src/config.rs @@ -9,6 +9,10 @@ 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; @@ -29,6 +33,9 @@ pub const DEFAULT_GUARD_MEMORY_MB: i64 = 1024; 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, @@ -66,6 +73,7 @@ impl std::fmt::Debug for TensorlakeComputeConfig { 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) @@ -115,23 +123,12 @@ impl TensorlakeComputeConfig { )); } } - let api_url = url::Url::parse(&self.api_url) - .map_err(|error| format!("invalid Tensorlake API URL: {error}"))?; - // The guard's tunnel receives this URL as TENSORLAKE_SANDBOX_API_URL. - // The tl CLI silently ignores values of any other shape and falls - // back to the public service, so reject them here. - if !matches!(api_url.scheme(), "http" | "https") - || api_url.host_str().is_none() - || api_url.query().is_some() - || api_url.fragment().is_some() - || !api_url.username().is_empty() - || api_url.password().is_some() - { - return Err( - "Tensorlake API URL must be an http or https URL with a host and no query, fragment, or credentials" - .into(), - ); - } + // 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()); } @@ -153,16 +150,13 @@ impl TensorlakeComputeConfig { self.guard_image.as_deref().unwrap_or(&self.default_image) } - /// Host of the Tensorlake API, which the guard VM's tunnel must reach. - fn tensorlake_host(&self) -> Option { - url::Url::parse(&self.api_url) - .ok() - .and_then(|url| url.host_str().map(str::to_string)) - } - /// Tensorlake `allow_out` for the guard VM, with the hosts the guard - /// itself needs added: the gateway and the Tensorlake hosts the tunnel - /// talks to. + /// 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() { @@ -173,20 +167,42 @@ impl TensorlakeComputeConfig { entries.push(host); } }; - if let Some(host) = url::Url::parse(&self.grpc_endpoint) - .ok() - .and_then(|url| url.host_str().map(str::to_string)) - { + if let Some(host) = url_host(&self.grpc_endpoint) { push(host); } - if let Some(host) = self.tensorlake_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::*; @@ -194,6 +210,7 @@ pub(crate) mod tests { 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(), @@ -230,7 +247,23 @@ pub(crate) mod tests { "api.anthropic.com", "gateway.example.com", "*.sandbox.tensorlake.ai", - "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" ] ); } @@ -259,6 +292,8 @@ pub(crate) mod tests { 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] diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs index 05faae7b4a..2795486dd8 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -439,10 +439,14 @@ impl TensorlakeComputeDriver { return Err(Status::already_exists("sandbox already exists")); } // The guard VM needs the gateway and the Tensorlake hosts. Empty - // keeps Tensorlake's default internet. + // 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: false, + allow_internet_access: true, allow_out, deny_out: Vec::new(), }); diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs index 4af4ccbfc3..6300e1b96d 100644 --- a/crates/openshell-driver-tensorlake/src/launch.rs +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -540,13 +540,13 @@ fn add_guard_files(archive: &mut Archive, files: &GuardFiles<'_>) -> Result<(), ) } -/// The Tensorlake key, the Tensorlake sandbox API URL, and the -/// `tl sbx tunnel` arguments for the tunnel identity in the guard VM. +/// 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`; its `TENSORLAKE_API_URL` names the -/// main Tensorlake API, not the sandbox API this driver is configured with. +/// 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, @@ -556,7 +556,7 @@ fn add_tunnel_files( 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']) { + 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)?; @@ -567,6 +567,7 @@ fn add_tunnel_files( &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( @@ -830,6 +831,7 @@ mod tests { 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, @@ -884,7 +886,7 @@ mod tests { 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\0" + 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))); diff --git a/crates/openshell-driver-tensorlake/src/main.rs b/crates/openshell-driver-tensorlake/src/main.rs index 6d6bb87f5e..796b8c06e8 100644 --- a/crates/openshell-driver-tensorlake/src/main.rs +++ b/crates/openshell-driver-tensorlake/src/main.rs @@ -12,6 +12,7 @@ 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, @@ -55,6 +56,15 @@ struct Args { #[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, @@ -126,6 +136,7 @@ async fn main() -> Result<()> { 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, diff --git a/docs/how-it-works/sandboxes/tensorlake.mdx b/docs/how-it-works/sandboxes/tensorlake.mdx index 84261024ea..e29e25bb8f 100644 --- a/docs/how-it-works/sandboxes/tensorlake.mdx +++ b/docs/how-it-works/sandboxes/tensorlake.mdx @@ -150,16 +150,16 @@ socket_path = "/run/openshell/tensorlake.sock" | `--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`. Tensorlake counts idle time from incoming -traffic only, and the guard's traffic is outgoing, so a short timeout suspends -a sandbox that is still working. +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. The driver turns off internet access for it and allows only -the hosts you list, the gateway host, and the Tensorlake host the tunnel uses. -The workload VM always has all outbound traffic off. +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 @@ -209,5 +209,5 @@ Two things to know: - Each sandbox uses two Tensorlake VMs. The guard VM defaults to 1 vCPU and 1 GiB. -For build details, the test runbook, and the design notes, see the +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). From 8b5c40c579fc35ba917603cf86d83d447b799836 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 21:17:24 -0500 Subject: [PATCH 27/31] feat(driver-tensorlake): add stop and start Stop runs the launch script with --stop in both VMs, which ends the current generation, then suspends the VMs so their disks stay. Start resumes the VMs and launches a new generation with the fresh credentials the gateway sends. The launch script now ends a previous generation before it launches, so the same VMs can be used again. A launch counter on each record lets a stop or start cancel an in-flight launch. A stopped sandbox reports Suspended=True so the gateway keeps it Stopped, and a starting one reports Bootstrapping=True. Suspended VMs found at restart, or suspended by hand, are reported as stopped. The lifecycle conformance file passes on Tensorlake. The docs and the README limits sections are reduced to a single scope line. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 69 ++- .../image/openshell-tensorlake-launch.sh | 106 +++- .../openshell-driver-tensorlake/src/client.rs | 25 +- .../openshell-driver-tensorlake/src/driver.rs | 551 ++++++++++++++++-- .../openshell-driver-tensorlake/src/grpc.rs | 21 +- .../openshell-driver-tensorlake/src/launch.rs | 3 + docs/how-it-works/sandboxes/tensorlake.mdx | 20 +- 7 files changed, 686 insertions(+), 109 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 5f8559214e..6c487872a2 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -85,6 +85,28 @@ When the gateway asks for a new sandbox: 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 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 | @@ -96,6 +118,7 @@ for the list of sandboxes every few seconds. | `/.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 @@ -401,33 +424,9 @@ 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. -## Limits - -- Stop and start are not supported. Delete the sandbox instead. -- The workload identity accepts a numeric user ID and group ID only. The - default is 1000:1000. -- No GPU, `driver_config`, `platform_config`, or `agent_socket_path`. -- The driver keeps launch state in memory and a copy of each sandbox - request, without its credentials, under `--state-dir`. After a driver - restart, it finds running sandboxes again by their Tensorlake names - (`openshell-` and `openshell--guard`) and reports them under the - names in the saved requests. Keep the state directory with the gateway - database: a recovered sandbox with no saved request has no name, and the - gateway then rejects every status update for it until it is deleted. A - pair with a VM still pending is reported as - failed with reason `DriverRestarted`. A pair with one VM missing is - reported as failed with reason `PairIncomplete`. A pair whose VMs were - running but whose launch scripts had not started yet is recovered as - running. The gateway then keeps it in `Provisioning` with reason - `ConfigurationPending`, and it never becomes Ready. Delete and recreate - such a sandbox. -- Anyone with access to your Tensorlake project can run - `tl sbx exec --user root` in the guard VM and read its credentials, or in - the workload VM and get around OpenShell policy. Keep the control plane - in a project of its own. -- Each guard VM holds a Tensorlake API key for its tunnel. That key can - open tunnels to any sandbox in the project. -- Each sandbox uses two Tensorlake VMs. +## Scope + +A single team with its own Tensorlake project can run it today. ## Testing @@ -472,7 +471,7 @@ registered gateway, selected with `OPENSHELL_GATEWAY`. Its test files: | `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 | no; the driver does not support stop and start | +| `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 @@ -506,7 +505,7 @@ End-to-end runs on Tensorlake Cloud confirmed: 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` (see [Limits](#limits)). + 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 @@ -518,6 +517,17 @@ End-to-end runs on Tensorlake Cloud confirmed: `--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. + 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, @@ -580,7 +590,6 @@ tests passed, because a published version cannot be replaced. ### 3. Later -- Stop and start. - GPU. - Tensorlake keys scoped to one tunnel target, so a guard VM's key cannot reach other sandboxes. diff --git a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh index 496e3ac9df..71bd2f3ebb 100755 --- a/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh +++ b/crates/openshell-driver-tensorlake/image/openshell-tensorlake-launch.sh @@ -23,9 +23,21 @@ # 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 @@ -40,6 +52,11 @@ 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 @@ -51,15 +68,88 @@ fatal() { } [ "$(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" -if [ -e /.openshell ]; then - fatal "/.openshell already exists; this sandbox was already launched" -fi 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="" @@ -106,6 +196,16 @@ cleanup() { 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 diff --git a/crates/openshell-driver-tensorlake/src/client.rs b/crates/openshell-driver-tensorlake/src/client.rs index ce4788a09b..9b737a2cfa 100644 --- a/crates/openshell-driver-tensorlake/src/client.rs +++ b/crates/openshell-driver-tensorlake/src/client.rs @@ -3,7 +3,8 @@ //! Minimal Tensorlake sandbox HTTP client. //! -//! Lifecycle calls go to the sandbox API (`POST/GET/DELETE /sandboxes`). +//! 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. @@ -232,6 +233,28 @@ impl TensorlakeClient { 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 diff --git a/crates/openshell-driver-tensorlake/src/driver.rs b/crates/openshell-driver-tensorlake/src/driver.rs index 2795486dd8..0a7a30d573 100644 --- a/crates/openshell-driver-tensorlake/src/driver.rs +++ b/crates/openshell-driver-tensorlake/src/driver.rs @@ -9,6 +9,11 @@ //! 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; @@ -49,6 +54,13 @@ 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. @@ -62,7 +74,9 @@ enum Phase { Launching, /// The launcher started. The gateway waits for the guard session. Running, - Suspended, + /// 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, @@ -84,6 +98,9 @@ struct Record { 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 { @@ -92,7 +109,7 @@ impl Record { sandbox.status = Some(DriverSandboxStatus { name: self.tensorlake_name.clone(), instance_id: self.tensorlake_id.clone(), - conditions: vec![ready_condition(&self.phase)], + conditions: phase_conditions(&self.phase), deleting: self.phase == Phase::Deleting, resolved_identity: self.identity.as_ref().map(|identity| ProtoIdentity { uid: identity.uid, @@ -107,6 +124,39 @@ impl Record { } } +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 => ( @@ -124,11 +174,10 @@ fn ready_condition(phase: &Phase) -> DriverCondition { "TensorlakeRunning", "Tensorlake sandbox is running".to_string(), ), - Phase::Suspended => ( + Phase::Stopped => ( "False", - "Suspended", - "Tensorlake sandbox is suspended; the Tensorlake driver cannot resume it yet" - .to_string(), + "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 => ( @@ -137,13 +186,7 @@ fn ready_condition(phase: &Phase) -> DriverCondition { "Tensorlake sandbox is being deleted".to_string(), ), }; - DriverCondition { - r#type: "Ready".to_string(), - status: status.to_string(), - reason: reason.to_string(), - message, - transition_time: None, - } + condition("Ready", status, reason, message) } /// Tensorlake sandbox name for an `OpenShell` sandbox ID. @@ -537,6 +580,7 @@ impl TensorlakeComputeDriver { phase: Phase::Pending, launcher_pid: None, guard_launcher_pid: None, + launch: 0, }; self.records .lock() @@ -545,23 +589,229 @@ impl TensorlakeComputeDriver { 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(); - let sandbox = sandbox.clone(); tokio::spawn(async move { - if let Err(message) = driver - .provision( - &sandbox, - &created.sandbox_id, - &guard_tensorlake_id, - &identity, - ) - .await - { - warn!(sandbox_id = %sandbox.id, %message, "Tensorlake sandbox launch failed"); - driver.publish_progress(&sandbox.id, LaunchProgress::Failed(&message)); + 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_phase( - &sandbox.id, + .set_launch_phase( + &sandbox_id, + launch_id, Phase::Failed { reason: "LaunchFailed".into(), message, @@ -570,7 +820,66 @@ impl TensorlakeComputeDriver { .await; } }); - Ok(()) + } + + 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. @@ -580,21 +889,26 @@ impl TensorlakeComputeDriver { 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) + .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) + .wait_running(sandbox, guard_tensorlake_id, "guard", started, launch) .await? else { return Ok(()); }; - self.set_phase(&sandbox.id, Phase::Launching).await; + 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); @@ -614,16 +928,26 @@ impl TensorlakeComputeDriver { .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) { + 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_phase(&sandbox.id, Phase::Running).await; + self.set_launch_phase(&sandbox.id, launch, Phase::Running) + .await; self.publish_progress(&sandbox.id, LaunchProgress::LauncherStarted); Ok(()) } @@ -636,10 +960,11 @@ impl TensorlakeComputeDriver { tensorlake_id: &str, role: &str, started: Instant, + launch: u64, ) -> Result, String> { let mut last_pending_reason: Option = None; loop { - if !self.is_active(&sandbox.id).await { + if !self.owns_launch(&sandbox.id, launch).await { return Ok(None); } let info = self @@ -782,14 +1107,33 @@ impl TensorlakeComputeDriver { .chain(live) } - async fn is_active(&self, sandbox_id: &str) -> bool { + /// 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) + .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; @@ -1019,6 +1363,7 @@ fn recovered_record( phase, launcher_pid: None, guard_launcher_pid: None, + launch: 0, }) } @@ -1037,10 +1382,12 @@ fn recovered_phase(workload: Option<&SandboxInfo>, guard: Option<&SandboxInfo>) }; Some(match (workload_phase, guard_phase) { (None, None) => return None, - (Some(Phase::Pending), _) | (_, Some(Phase::Pending)) => restarted(), (None, Some(_)) => half("workload"), (Some(_), None) => half("guard"), - (Some(Phase::Suspended), _) | (_, Some(Phase::Suspended)) => Phase::Suspended, + // 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, }) } @@ -1072,17 +1419,23 @@ fn reconcile( | Phase::Pending | Phase::Launching => return Reconcile::Keep, // A failed launch stays failed while the VMs still exist. Nothing - // will launch it again. + // 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::Suspended) + .is_some_and(|phase| *phase != Phase::Stopped) && guard_phase .as_ref() - .is_some_and(|phase| *phase != Phase::Suspended) => + .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>| { @@ -1097,9 +1450,8 @@ fn reconcile( match (workload_phase, guard_phase) { (None, _) => gone("workload", workload), (Some(_), None) => gone("guard", guard), - (Some(Phase::Suspended), _) | (_, Some(Phase::Suspended)) => { - Reconcile::Set(Phase::Suspended) - } + // 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), } } @@ -1128,7 +1480,7 @@ fn observed_phase(info: &SandboxInfo) -> Option { match info.status.as_str() { "pending" => Some(Phase::Pending), "running" | "snapshotting" => Some(Phase::Running), - "suspending" | "suspended" => Some(Phase::Suspended), + "suspending" | "suspended" => Some(Phase::Stopped), _ => None, } } @@ -1157,6 +1509,8 @@ fn failure_detail(info: &SandboxInfo) -> String { 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. @@ -1179,6 +1533,11 @@ impl LaunchProgress<'_> { "Accepted", "Tensorlake accepted the sandbox request".to_string(), ), + Self::Resuming => ( + "Normal", + "Resuming", + "Resuming the Tensorlake VMs".to_string(), + ), Self::Pending(reason) => ( "Normal", "Pending", @@ -1221,6 +1580,10 @@ impl LaunchProgress<'_> { 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); @@ -1256,6 +1619,19 @@ impl LaunchProgress<'_> { } } +/// 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( @@ -1376,6 +1752,40 @@ mod tests { 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"); @@ -1448,12 +1858,24 @@ mod tests { ); assert_eq!( reconcile(&Phase::Running, Some(&info("suspended")), Some(&guard)), - Reconcile::Set(Phase::Suspended) - ); - assert_eq!( - reconcile(&Phase::Suspended, Some(&info("running")), Some(&guard)), - Reconcile::Set(Phase::Running) + 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" @@ -1483,10 +1905,19 @@ mod tests { }; assert_eq!(reason, "TensorlakeTerminated"); assert!(message.contains("guard")); - // A suspended guard VM suspends the sandbox. + // A suspended guard VM stops the sandbox. assert_eq!( reconcile(&Phase::Running, Some(&running), Some(&suspended)), - Reconcile::Set(Phase::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) ); } @@ -1553,7 +1984,7 @@ mod tests { 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::Suspended).unwrap(); + 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); @@ -1603,6 +2034,17 @@ mod tests { ), 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 @@ -1711,7 +2153,8 @@ mod tests { #[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::Suspended)); + 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 index 6a5852a597..89628de07c 100644 --- a/crates/openshell-driver-tensorlake/src/grpc.rs +++ b/crates/openshell-driver-tensorlake/src/grpc.rs @@ -121,19 +121,24 @@ impl ComputeDriver for ComputeDriverService { &self, request: Request, ) -> Result, Status> { - required_id(&request.into_inner().sandbox_id)?; - Err(Status::unimplemented( - "the Tensorlake driver cannot stop a sandbox yet; delete it instead", - )) + 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, + request: Request, ) -> Result, Status> { - Err(Status::unimplemented( - "the Tensorlake driver cannot restart a sandbox yet", - )) + 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( diff --git a/crates/openshell-driver-tensorlake/src/launch.rs b/crates/openshell-driver-tensorlake/src/launch.rs index 6300e1b96d..41172219a3 100644 --- a/crates/openshell-driver-tensorlake/src/launch.rs +++ b/crates/openshell-driver-tensorlake/src/launch.rs @@ -39,6 +39,9 @@ use crate::config::TensorlakeComputeConfig; 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; diff --git a/docs/how-it-works/sandboxes/tensorlake.mdx b/docs/how-it-works/sandboxes/tensorlake.mdx index e29e25bb8f..bdf57748c4 100644 --- a/docs/how-it-works/sandboxes/tensorlake.mdx +++ b/docs/how-it-works/sandboxes/tensorlake.mdx @@ -32,6 +32,10 @@ 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 @@ -195,19 +199,9 @@ Two things to know: - 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. -## Limits - -- Stop and start are not supported. Delete the sandbox instead. -- Workload identity accepts numeric user and group IDs only. The default is - `1000:1000`. -- No GPU, `driver_config`, `platform_config`, or `agent_socket_path`. -- The driver polls Tensorlake every few seconds. Status changes can lag by - that much. -- After a driver restart, sandboxes that had not finished launching are - reported as failed. Running sandboxes are recovered from the saved - requests in `--state-dir`. Keep that directory with the gateway database. -- Each sandbox uses two Tensorlake VMs. The guard VM defaults to 1 vCPU and - 1 GiB. +## 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). From d4fa2bff505168c207259d336d1d9d26420c3142 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Tue, 20 Oct 2026 22:50:50 -0500 Subject: [PATCH 28/31] docs(driver-tensorlake): align the README with the driver code Drop the stale two-topology wording, list the platform API URL in the tunnel environment, name every host that --allow-out adds, state which driver settings the control plane env file can carry, note when a failed sandbox can be started, and complete the unit test list. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 42 +++++++++++++------- 1 file changed, 27 insertions(+), 15 deletions(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 6c487872a2..43c176f54d 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -68,9 +68,9 @@ When the gateway asks for a new sandbox: `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. In both topologies the workload - runtime is PID 1 of its own PID namespace, so network policy can resolve - which binary opened a connection. + 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 @@ -100,6 +100,10 @@ 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 @@ -114,7 +118,7 @@ stays stopped until you start it. | `/.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 and the sandbox API URL | +| `/.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 | @@ -304,9 +308,10 @@ 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 two Tensorlake hosts the -tunnel talks to: the sandbox API and the platform API. Tensorlake's -resolver then answers only for those names. Internet access stays on in +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. @@ -349,13 +354,17 @@ bundle in the control image for that connection. `/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 every driver setting - from the table above can be set through its environment variable. Then - it 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. + 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: @@ -453,8 +462,11 @@ The unit tests cover: - 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, - and the phase after each poll observation. + 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 From 6ee4166c8ad2123205320d6a2b7dc4394e89d2bd Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Wed, 21 Oct 2026 01:47:12 -0500 Subject: [PATCH 29/31] docs(driver-tensorlake): add the OpenCode on Tensorlake case study Replace the Claude Code case study in the driver README with one that builds an OpenCode image on Tensorlake and runs it through OpenShell. Add the example Dockerfile, a tutorial page under docs/tutorials, and its navigation entry and index card. Remove docs/control-plane-auth.md. The OIDC decision it recorded is already in the README and the public Tensorlake page, and the mTLS fallback it designed is not implemented. The README now states that in one sentence. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 104 +++++-- .../docs/control-plane-auth.md | 135 --------- .../examples/opencode/Dockerfile | 27 ++ docs/index.yml | 3 + docs/tutorials/index.mdx | 5 + docs/tutorials/run-opencode-on-tensorlake.mdx | 275 ++++++++++++++++++ 6 files changed, 384 insertions(+), 165 deletions(-) delete mode 100644 crates/openshell-driver-tensorlake/docs/control-plane-auth.md create mode 100644 crates/openshell-driver-tensorlake/examples/opencode/Dockerfile create mode 100644 docs/tutorials/run-opencode-on-tensorlake.mdx diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 43c176f54d..74f315a276 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -387,8 +387,8 @@ 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. -The decision and the fallback for deployments without an identity provider -are in [docs/control-plane-auth.md](docs/control-plane-auth.md). +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 @@ -551,47 +551,91 @@ no longer grants it. This section is a temporary plan. Remove it once the work is done. -### 1. Case study: run Claude Code on Tensorlake through OpenShell - -The hello test proves the plumbing. The case study proves the three things -a real user needs: the guard injects a real provider credential, the policy -blocks a real agent's stray traffic, and a custom agent image works. The -`--from` flag on sandbox create maps to a Tensorlake image name, so the -driver already supports this. - -Build a derived image on Tensorlake. Its Dockerfile starts -`FROM openshell-tensorlake-test` and installs Claude Code. Register it: +### 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 path/to/Dockerfile \ - --registered-name openshell-tensorlake-claude --cas +tl sbx image create crates/openshell-driver-tensorlake/examples/opencode/Dockerfile \ + --registered-name openshell-tensorlake-opencode --cas ``` -Import the provider profile and create the provider. The API key stays in -the gateway and never enters the workload: +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/claude-code.yaml -export ANTHROPIC_API_KEY=your_api_key -openshell provider create --name anthropic --type anthropic --from-existing +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: +**Run the agent:** ```shell openshell sandbox create --name demo \ - --from openshell-tensorlake-claude \ - --provider anthropic \ - -- claude -p "write a hello world in python and run it" + --from openshell-tensorlake-opencode \ + --provider openrouter \ + -- opencode -m openrouter/nvidia/nemotron-3.5-lightning:free ``` -Then show one denied request, for example the agent reaching PyPI. Approve -the drafted policy rule and run again. - -The output is a tutorial page under `docs/tutorials/`, modeled on -"Run your first agent", plus a section in the design doc. The first run -will hit denials for npm or PyPI. Budget time to settle the policy before -you record the final run. +**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 diff --git a/crates/openshell-driver-tensorlake/docs/control-plane-auth.md b/crates/openshell-driver-tensorlake/docs/control-plane-auth.md deleted file mode 100644 index 7e215f136d..0000000000 --- a/crates/openshell-driver-tensorlake/docs/control-plane-auth.md +++ /dev/null @@ -1,135 +0,0 @@ -# Control-plane authentication on Tensorlake - -Status: decided. The control plane runs on Tensorlake behind a public URL and -authenticates users with OIDC. The mTLS design below stays as the fallback -for deployments that have no identity provider. - -## Decision - -A public gateway endpoint is inherent to a remote sandbox provider. Guards in -sandbox VMs must dial the gateway, they cannot hold a Tensorlake key, and -Tensorlake offers no inbound tunnel to a user's machine. So the gateway must -accept connections from the internet, and the gateway itself must -authenticate every user call. - -OIDC is the supported way to do that. The gateway already validates tokens, -checks roles, and refreshes keys, and the CLI already logs in through a -browser or a device code. The `control/` scripts refuse to start without an -issuer unless the operator sets the test-only -`OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1`. - -The mTLS-over-tunnel design below is not implemented. Use it if a deployment -has no identity provider and cannot get one. - -## Problem - -The control plane (gateway and driver) runs in a Tensorlake sandbox. Guards -in other sandboxes reach the gateway through the Tensorlake port proxy: - -``` -https://8080-.sandbox.tensorlake.ai -``` - -Guards cannot hold a Tensorlake key, so this port must accept anonymous -requests at the proxy. The gateway must then authenticate users itself. - -Today there are two choices: - -- OIDC: safe, but needs an identity provider. -- `OPENSHELL_CONTROL_ALLOW_UNAUTHENTICATED=1`: anyone with the URL controls - the gateway. Test only. - -We need a production setup without an identity provider. - -## Facts from the code - -1. **Guard calls reject anonymous callers.** A guard calls 17 gateway - methods. 14 accept only a sandbox principal (sandbox JWT). 3 are dual - (`GetSandboxConfig`, `UpdateConfig`, `GetDraftPolicy`) and also accept a - user. With `allow_unauthenticated_users = false` and a configured - authenticator, a caller without credentials gets `Unauthenticated` on - all of them (`crates/openshell-server/src/multiplex.rs`, `AuthGrpcRouter`). -2. **Client certificates are optional at the TLS handshake.** With a client - CA, the gateway accepts connections without a certificate - (`allow_unauthenticated()` in `crates/openshell-server/src/tls.rs`). A - verified certificate becomes a user only when `mtls_auth.enabled` is set. - So one TLS port serves mTLS users and guards with sandbox JWTs. -3. **A Tensorlake tunnel is raw TCP to `127.0.0.1:`** in the sandbox, - and every connection needs a Tensorlake credential. The port does not - need to be exposed. TLS stays end to end, so the client certificate - reaches the gateway. -4. The gateway has one gRPC listener and no per-listener auth settings. - -## Design - -``` - CONTROL SANDBOX - ┌────────────────────────────────────────────┐ - guards ── HTTPS ──► │ :8080 (exposed) local gRPC proxy │ - (sandbox JWT) │ re-encrypts ─────────┐ │ - │ ▼ │ - users ── tl tunnel ───────────────────► 127.0.0.1:8443 gateway │ - (Tensorlake key + │ TLS, mTLS users on, │ - client cert) │ anonymous users off │ - └────────────────────────────────────────────┘ -``` - -| Caller | Path | Checks | -|---|---|---| -| Guard | port proxy → local proxy → gateway | sandbox JWT | -| User (CLI) | `tl sbx tunnel 8443` → gateway | Tensorlake credential (tunnel), then client certificate (mTLS) | -| Anyone else | port proxy → local proxy → gateway | no credential, so `Unauthenticated` | - -### Components - -- **Gateway**: binds `127.0.0.1:8443` with TLS. Settings: - `mtls_auth.enabled = true`, `allow_unauthenticated_users = false`, sandbox - JWT signing as today. Server certificate SANs include `127.0.0.1` and - `localhost`, for the tunnel. -- **Local gRPC proxy** (nginx `grpc_pass grpcs://127.0.0.1:8443`): listens on - `:8080` with plaintext HTTP/2 behind the Tensorlake port proxy. It - forwards all gRPC to the gateway over TLS, without a client certificate. - Long timeouts keep supervisor streams open. -- **Certificates**: `openshell-gateway generate-certs` creates the CA, the - server certificate, and a client certificate on first start. The user - downloads the client bundle once with `tl sbx cp`. Treat it as a secret. -- **Driver**: no change. `--grpc-endpoint` stays the public URL, and - `--gateway-tls-ca` stays the public CA bundle, because guards still go - through the Tensorlake port proxy. - -### User setup - -```shell -tl sbx cp openshell-control:/var/lib/openshell/keys/client/ ~/.config/openshell/... -tl sbx tunnel openshell-control 8443 --listen-port 18443 -openshell gateway add https://127.0.0.1:18443 --local --name tensorlake -``` - -The exact CLI registration and certificate paths need confirmation during -implementation. - -## Security notes - -- Two checks for users: Tensorlake project access and the client - certificate. -- Anyone with Tensorlake project access can already run - `tl sbx exec --user root` in the control sandbox and read its keys. The - client certificate does not protect against project members. Use a - separate Tensorlake project for the control plane. -- The public port exposes only what a sandbox JWT can call. The 3 dual - methods still need a user or sandbox principal. -- Health endpoints stay unauthenticated, as today. - -## Later: OIDC with Tensorlake identity - -If the Tensorlake login system is an OIDC provider, the gateway can trust -Tensorlake accounts directly (`OPENSHELL_OIDC_ISSUER`). Users then log in -with their Tensorlake identity, and no client certificate is needed. This -needs Tensorlake-side setup. - -## Open questions - -- Does the Tensorlake port proxy keep long-lived gRPC streams open? -- Does `openshell gateway add` support a tunneled mTLS endpoint without an - SSH remote? If not, which registration fits best? -- nginx or another small proxy (for example Envoy) in the control image? 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/docs/index.yml b/docs/index.yml index 99dcdf3eb5..5eedb74f31 100644 --- a/docs/index.yml +++ b/docs/index.yml @@ -115,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). From 8a9b94e13c2c42a0755c0e2d8dae537ef5fbfbe8 Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Wed, 21 Oct 2026 02:09:29 -0500 Subject: [PATCH 30/31] docs(driver-tensorlake): record the OIDC login run on Tensorlake Add the 2026-10-21 login run to the verified list: Keycloak in a second Tensorlake sandbox as the issuer, browser login through the public URL, the OpenCode case study with an admin token, and a user-role account denied until it joins the workspace. Note the one defect found: the Tensorlake port proxy drops the gRPC status from trailers-only responses, so denied calls through the public URL show "missing grpc-status trailer". Tell users what the message means on the Tensorlake page, and list the fix options under Later. Signed-off-by: Shanshan Wang --- crates/openshell-driver-tensorlake/README.md | 19 +++++++++++++++++++ docs/how-it-works/sandboxes/tensorlake.mdx | 13 ++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 74f315a276..9c63799fb7 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -539,6 +539,21 @@ End-to-end runs on Tensorlake Cloud confirmed: 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 @@ -651,3 +666,7 @@ tests passed, because a published version cannot be replaced. 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/docs/how-it-works/sandboxes/tensorlake.mdx b/docs/how-it-works/sandboxes/tensorlake.mdx index bdf57748c4..fda0796f92 100644 --- a/docs/how-it-works/sandboxes/tensorlake.mdx +++ b/docs/how-it-works/sandboxes/tensorlake.mdx @@ -107,7 +107,18 @@ public URL. The proxy terminates TLS. 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`. +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 From c736a72c75629827f837690869540f453fda4fbf Mon Sep 17 00:00:00 2001 From: Shanshan Wang Date: Wed, 21 Oct 2026 08:49:05 -0500 Subject: [PATCH 31/31] build(driver-tensorlake): name public images after the release tag or commit A public build no longer needs a hand-picked version. build-images.sh takes it from the checkout: the release tag on HEAD with dots turned into dashes, or else the short commit hash. The Tensorlake Images workflow drops its version requirement and fetches tags so a run from a release tag publishes that release. VERSION stays as an override. Signed-off-by: Shanshan Wang --- .github/workflows/tensorlake-images.yml | 15 ++++---- crates/openshell-driver-tensorlake/README.md | 36 +++++++++++------- .../build-images.sh | 37 +++++++++++++++---- docs/how-it-works/sandboxes/tensorlake.mdx | 6 ++- 4 files changed, 64 insertions(+), 30 deletions(-) diff --git a/.github/workflows/tensorlake-images.yml b/.github/workflows/tensorlake-images.yml index 3bc53a936c..4658bb38de 100644 --- a/.github/workflows/tensorlake-images.yml +++ b/.github/workflows/tensorlake-images.yml @@ -8,8 +8,11 @@ name: Tensorlake Images # 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. Public names are permanent, so -# pick a version that is not registered yet. +# 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. @@ -18,7 +21,7 @@ on: workflow_dispatch: inputs: version: - description: "Image version suffix, for example 0-1-5. Required for a public build." + description: "Image version suffix. Default: the release tag on the checkout as 0-1-6, or the short commit." required: false type: string default: "" @@ -48,6 +51,8 @@ jobs: - 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: @@ -55,10 +60,6 @@ jobs: PUBLIC: ${{ inputs.public }} run: | set -euo pipefail - if [ "${PUBLIC}" = "true" ] && [ -z "${VERSION}" ]; then - echo "::error::a public build needs a version" >&2 - exit 1 - fi 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 diff --git a/crates/openshell-driver-tensorlake/README.md b/crates/openshell-driver-tensorlake/README.md index 9c63799fb7..86bc96e14b 100644 --- a/crates/openshell-driver-tensorlake/README.md +++ b/crates/openshell-driver-tensorlake/README.md @@ -240,22 +240,31 @@ a new image on top of it. Build from a clean checkout, in the project that owns the public images: ```shell -PUBLIC=1 VERSION=0-1-5 crates/openshell-driver-tensorlake/build-images.sh +PUBLIC=1 crates/openshell-driver-tensorlake/build-images.sh ``` -This registers `openshell-tensorlake-0-1-5` and `openshell-control-0-1-5` -as public images. Any Tensorlake project can use them 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. +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 with a version -and the `public` flag. It needs the `TENSORLAKE_API_KEY` repository secret for -the project that owns the public images. +(`.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 @@ -654,10 +663,11 @@ run above used `openshell-tensorlake-test`. ### 2. Publish the first public image pair -Run the `Tensorlake Images` workflow with a version and `public: true`, or -run `PUBLIC=1 VERSION= build-images.sh` from a clean checkout in -the project that owns the public images. Publish from a commit whose -tests passed, because a published version cannot be replaced. +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 diff --git a/crates/openshell-driver-tensorlake/build-images.sh b/crates/openshell-driver-tensorlake/build-images.sh index 2e63cb643f..214d1b6fdd 100755 --- a/crates/openshell-driver-tensorlake/build-images.sh +++ b/crates/openshell-driver-tensorlake/build-images.sh @@ -10,21 +10,20 @@ # work as a pair. # # Optional: -# VERSION added to the default names as `-` (for example 0-1-5) -# SANDBOX_IMAGE full sandbox image name (default: openshell-tensorlake[-VERSION]) -# CONTROL_IMAGE full control image name (default: openshell-control[-VERSION]) # 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)" -# 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}}" 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; } @@ -42,6 +41,27 @@ 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 @@ -77,6 +97,7 @@ cat <