From b39af3da852f542f3393e1a9813df6ecfa05fdad Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Fri, 1 May 2026 07:18:49 -0700 Subject: [PATCH 1/9] chore(ci): label mon maintainer issues for triage (#1102) Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --- .github/workflows/issue-triage.yml | 57 ++++++++++++++++++++++++++++++ CONTRIBUTING.md | 1 + 2 files changed, 58 insertions(+) diff --git a/.github/workflows/issue-triage.yml b/.github/workflows/issue-triage.yml index 10732b8c28..d5488cd41c 100644 --- a/.github/workflows/issue-triage.yml +++ b/.github/workflows/issue-triage.yml @@ -8,6 +8,63 @@ permissions: issues: write jobs: + label-mon-maintainer-issues: + runs-on: ubuntu-latest + if: github.repository_owner == 'NVIDIA' + env: + ORG_READ_TOKEN: ${{ secrets.ORG_READ_TOKEN }} + steps: + - name: Require org read token + if: env.ORG_READ_TOKEN == '' + run: | + echo "::error::ORG_READ_TOKEN is required to check mon-maintainers membership." + exit 1 + + - name: Check mon-maintainers membership + id: mon-maintainer + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.ORG_READ_TOKEN }} + result-encoding: string + script: | + const author = context.payload.issue.user.login; + + try { + const { data } = await github.rest.teams.getMembershipForUserInOrg({ + org: context.repo.owner, + team_slug: 'mon-maintainers', + username: author, + }); + + if (data.state === 'active') { + console.log(`${author} is an active mon-maintainers member.`); + return 'true'; + } + + console.log(`${author} has mon-maintainers membership state: ${data.state}`); + } catch (e) { + if (e.status === 404) { + console.log(`${author} is not a mon-maintainers member.`); + return 'false'; + } + + throw e; + } + + return 'false'; + + - name: Add triage label + if: steps.mon-maintainer.outputs.result == 'true' + uses: actions/github-script@v7 + with: + script: | + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + labels: ['state:triage-needed'], + }); + check-agent-diagnostic: runs-on: ubuntu-latest # Only run on bug reports (title starts with "bug:") diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3a01d75eb0..64d9b1c772 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,6 +92,7 @@ Skills connect into pipelines. Individual skill files don't describe these relat - **Policy iteration:** `openshell-cli` → `generate-sandbox-policy` Workflow state labels use the `state:*` prefix, and security work uses `topic:security`. GitHub issue templates assign built-in issue types where applicable, and agent-created issues should use issue types or manual follow-up rather than type labels. +New issues opened by members of the `mon-maintainers` GitHub team are automatically labeled `state:triage-needed` by the issue triage workflow. ## Prerequisites From 9751872b2dd41d832f5b01207e2df292da46efb7 Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Fri, 1 May 2026 07:51:45 -0700 Subject: [PATCH 2/9] feat(release): add Debian package publishing (#1069) --- .github/workflows/deb-package.yml | 92 +++++++ .github/workflows/driver-vm-linux.yml | 254 +++++++++++++++++++ .github/workflows/release-dev.yml | 47 +++- .github/workflows/release-tag.yml | 32 ++- .gitignore | 3 + architecture/gateway.md | 7 +- crates/openshell-driver-vm/README.md | 6 +- crates/openshell-driver-vm/start.sh | 2 +- crates/openshell-server/src/cli.rs | 43 +++- crates/openshell-server/src/compute/vm.rs | 10 +- crates/openshell-server/src/lib.rs | 7 - deploy/deb/control.in | 16 ++ deploy/deb/openshell-gateway.service | 28 +++ deploy/deb/postinst.sh | 34 +++ deploy/deb/postrm.sh | 13 + deploy/deb/prerm.sh | 21 ++ install-dev.sh | 288 ++++++++++++++++++++++ tasks/package.toml | 25 ++ tasks/scripts/package-deb-install.sh | 90 +++++++ tasks/scripts/package-deb.sh | 188 ++++++++++++++ tasks/scripts/release.py | 16 ++ 21 files changed, 1189 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/deb-package.yml create mode 100644 .github/workflows/driver-vm-linux.yml create mode 100644 deploy/deb/control.in create mode 100644 deploy/deb/openshell-gateway.service create mode 100755 deploy/deb/postinst.sh create mode 100755 deploy/deb/postrm.sh create mode 100755 deploy/deb/prerm.sh create mode 100755 install-dev.sh create mode 100644 tasks/package.toml create mode 100755 tasks/scripts/package-deb-install.sh create mode 100755 tasks/scripts/package-deb.sh diff --git a/.github/workflows/deb-package.yml b/.github/workflows/deb-package.yml new file mode 100644 index 0000000000..75c206defe --- /dev/null +++ b/.github/workflows/deb-package.yml @@ -0,0 +1,92 @@ +name: Debian Package + +on: + workflow_call: + inputs: + deb-version: + required: true + type: string + checkout-ref: + required: true + type: string + +permissions: + contents: read + packages: read + +defaults: + run: + shell: bash + +jobs: + build-deb-linux: + name: Build Debian Package (Linux ${{ matrix.arch }}) + strategy: + matrix: + include: + - arch: amd64 + runner: build-amd64 + deb_arch: amd64 + cli_target: x86_64-unknown-linux-musl + gnu_target: x86_64-unknown-linux-gnu + - arch: arm64 + runner: build-arm64 + deb_arch: arm64 + cli_target: aarch64-unknown-linux-musl + gnu_target: aarch64-unknown-linux-gnu + runs-on: ${{ matrix.runner }} + timeout-minutes: 20 + container: + image: ghcr.io/nvidia/openshell/ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ inputs['checkout-ref'] }} + + - name: Download CLI artifact + uses: actions/download-artifact@v4 + with: + name: cli-linux-${{ matrix.arch }} + path: package-input/ + + - name: Download gateway artifact + uses: actions/download-artifact@v4 + with: + name: gateway-binary-linux-${{ matrix.arch }} + path: package-input/ + + - name: Download VM driver artifact + uses: actions/download-artifact@v4 + with: + name: driver-vm-linux-${{ matrix.arch }} + path: package-input/ + + - name: Extract package inputs + run: | + set -euo pipefail + mkdir -p package-binaries + tar -xzf "package-input/openshell-${{ matrix.cli_target }}.tar.gz" -C package-binaries + tar -xzf "package-input/openshell-gateway-${{ matrix.gnu_target }}.tar.gz" -C package-binaries + tar -xzf "package-input/openshell-driver-vm-${{ matrix.gnu_target }}.tar.gz" -C package-binaries + ls -lah package-binaries + + - name: Build Debian package + run: | + set -euo pipefail + OPENSHELL_CLI_BINARY="${PWD}/package-binaries/openshell" \ + OPENSHELL_GATEWAY_BINARY="${PWD}/package-binaries/openshell-gateway" \ + OPENSHELL_DRIVER_VM_BINARY="${PWD}/package-binaries/openshell-driver-vm" \ + OPENSHELL_DEB_VERSION="${{ inputs['deb-version'] }}" \ + OPENSHELL_DEB_ARCH="${{ matrix.deb_arch }}" \ + OPENSHELL_OUTPUT_DIR=artifacts \ + tasks/scripts/package-deb.sh + + - name: Upload Debian package artifact + uses: actions/upload-artifact@v4 + with: + name: deb-linux-${{ matrix.arch }} + path: artifacts/*.deb + retention-days: 5 diff --git a/.github/workflows/driver-vm-linux.yml b/.github/workflows/driver-vm-linux.yml new file mode 100644 index 0000000000..9f188c2601 --- /dev/null +++ b/.github/workflows/driver-vm-linux.yml @@ -0,0 +1,254 @@ +name: Driver VM Linux + +on: + workflow_call: + inputs: + cargo-version: + required: true + type: string + image-tag: + required: true + type: string + checkout-ref: + required: true + type: string + +permissions: + contents: read + packages: read + +defaults: + run: + shell: bash + +jobs: + download-kernel-runtime: + name: Download Kernel Runtime + runs-on: build-amd64 + timeout-minutes: 10 + container: + image: ghcr.io/nvidia/openshell/ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs['checkout-ref'] }} + + - name: Download Linux runtime tarballs + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + mkdir -p runtime-artifacts + + for platform in linux-aarch64 linux-x86_64; do + asset="vm-runtime-${platform}.tar.zst" + echo "Downloading ${asset}..." + asset_url=$(curl -fsSL \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer ${GH_TOKEN}" \ + "https://api.github.com/repos/${GITHUB_REPOSITORY}/releases/tags/vm-dev" \ + | jq -r --arg asset "$asset" '.assets[] | select(.name == $asset) | .browser_download_url' \ + | head -n1) + if [ -z "$asset_url" ]; then + echo "::error::No ${asset} asset found on vm-dev release" + exit 1 + fi + curl -fL -o "runtime-artifacts/${asset}" "$asset_url" + done + + ls -lah runtime-artifacts/ + + - name: Verify downloads + run: | + set -euo pipefail + for platform in linux-aarch64 linux-x86_64; do + test -f "runtime-artifacts/vm-runtime-${platform}.tar.zst" + done + + - name: Upload runtime artifacts + uses: actions/upload-artifact@v4 + with: + name: driver-vm-kernel-runtime-tarballs + path: runtime-artifacts/vm-runtime-*.tar.zst + retention-days: 1 + + build-rootfs: + name: Build Rootfs (${{ matrix.arch }}) + strategy: + matrix: + include: + - arch: arm64 + runner: build-arm64 + guest_arch: aarch64 + - arch: amd64 + runner: build-amd64 + guest_arch: x86_64 + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + container: + image: ghcr.io/nvidia/openshell/ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + options: --privileged + volumes: + - /var/run/docker.sock:/var/run/docker.sock + env: + MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + OPENSHELL_IMAGE_TAG: ${{ inputs['image-tag'] }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs['checkout-ref'] }} + + - name: Mark workspace safe for git + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + + - name: Log in to GHCR + run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin + + - name: Install tools + run: mise install --locked + + - name: Install zstd + run: apt-get update && apt-get install -y --no-install-recommends zstd && rm -rf /var/lib/apt/lists/* + + - name: Build base rootfs tarball + run: | + set -euo pipefail + crates/openshell-vm/scripts/build-rootfs.sh \ + --base \ + --arch ${{ matrix.guest_arch }} \ + target/rootfs-build + + mkdir -p target/vm-runtime-compressed + tar -C target/rootfs-build -cf - . \ + | zstd -19 -T0 -o target/vm-runtime-compressed/rootfs.tar.zst + + - name: Upload rootfs artifact + uses: actions/upload-artifact@v4 + with: + name: driver-vm-rootfs-${{ matrix.arch }} + path: target/vm-runtime-compressed/rootfs.tar.zst + retention-days: 1 + + build-driver-vm-linux: + name: Build Driver VM (Linux ${{ matrix.arch }}) + needs: [download-kernel-runtime, build-rootfs] + strategy: + matrix: + include: + - arch: arm64 + runner: build-arm64 + target: aarch64-unknown-linux-gnu + platform: linux-aarch64 + - arch: amd64 + runner: build-amd64 + target: x86_64-unknown-linux-gnu + platform: linux-x86_64 + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + container: + image: ghcr.io/nvidia/openshell/ci:latest + credentials: + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + options: --privileged + env: + MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SCCACHE_MEMCACHED_ENDPOINT: ${{ vars.SCCACHE_MEMCACHED_ENDPOINT }} + OPENSHELL_IMAGE_TAG: ${{ inputs['image-tag'] }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs['checkout-ref'] }} + fetch-depth: 0 + + - name: Mark workspace safe for git + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + + - name: Fetch tags + run: git fetch --tags --force + + - name: Install tools + run: mise install --locked + + - name: Cache Rust target and registry + uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2 + with: + shared-key: driver-vm-linux-${{ matrix.arch }} + cache-directories: .cache/sccache + cache-targets: "true" + + - name: Install zstd + run: apt-get update && apt-get install -y --no-install-recommends zstd && rm -rf /var/lib/apt/lists/* + + - name: Download kernel runtime tarball + uses: actions/download-artifact@v4 + with: + name: driver-vm-kernel-runtime-tarballs + path: runtime-download/ + + - name: Download rootfs tarball + uses: actions/download-artifact@v4 + with: + name: driver-vm-rootfs-${{ matrix.arch }} + path: rootfs-download/ + + - name: Stage compressed runtime for embedding + run: | + set -euo pipefail + COMPRESSED_DIR="${PWD}/target/vm-runtime-compressed" + mkdir -p "$COMPRESSED_DIR" + + EXTRACT_DIR=$(mktemp -d) + zstd -d "runtime-download/vm-runtime-${{ matrix.platform }}.tar.zst" --stdout \ + | tar -xf - -C "$EXTRACT_DIR" + + for file in "$EXTRACT_DIR"/*; do + [ -f "$file" ] || continue + name=$(basename "$file") + [ "$name" = "provenance.json" ] && continue + zstd -19 -f -q -T0 -o "${COMPRESSED_DIR}/${name}.zst" "$file" + done + + cp rootfs-download/rootfs.tar.zst "${COMPRESSED_DIR}/rootfs.tar.zst" + ls -lah "$COMPRESSED_DIR" + + - name: Scope workspace to driver-vm crates + run: | + set -euo pipefail + sed -i 's|members = \["crates/\*"\]|members = ["crates/openshell-driver-vm", "crates/openshell-core"]|' Cargo.toml + + - name: Patch workspace version + if: ${{ inputs['cargo-version'] != '' }} + run: | + set -euo pipefail + sed -i -E '/^\[workspace\.package\]/,/^\[/{s/^version[[:space:]]*=[[:space:]]*".*"/version = "'"${{ inputs['cargo-version'] }}"'"/}' Cargo.toml + + - name: Build openshell-driver-vm + run: | + set -euo pipefail + OPENSHELL_VM_RUNTIME_COMPRESSED_DIR="${PWD}/target/vm-runtime-compressed" \ + mise x -- cargo build --release -p openshell-driver-vm + + - name: sccache stats + if: always() + run: mise x -- sccache --show-stats + + - name: Package binary + run: | + set -euo pipefail + mkdir -p artifacts + tar -czf "artifacts/openshell-driver-vm-${{ matrix.target }}.tar.gz" \ + -C target/release openshell-driver-vm + + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: driver-vm-linux-${{ matrix.arch }} + path: artifacts/*.tar.gz + retention-days: 5 diff --git a/.github/workflows/release-dev.yml b/.github/workflows/release-dev.yml index b088ceb330..5563a67ebf 100644 --- a/.github/workflows/release-dev.yml +++ b/.github/workflows/release-dev.yml @@ -29,6 +29,7 @@ jobs: outputs: python_version: ${{ steps.v.outputs.python }} cargo_version: ${{ steps.v.outputs.cargo }} + deb_version: ${{ steps.v.outputs.deb }} steps: - uses: actions/checkout@v6 with: @@ -46,6 +47,7 @@ jobs: set -euo pipefail echo "python=$(uv run python tasks/scripts/release.py get-version --python)" >> "$GITHUB_OUTPUT" echo "cargo=$(uv run python tasks/scripts/release.py get-version --cargo)" >> "$GITHUB_OUTPUT" + echo "deb=$(uv run python tasks/scripts/release.py get-version --deb)" >> "$GITHUB_OUTPUT" build-gateway: needs: [compute-versions] @@ -615,12 +617,31 @@ jobs: path: artifacts/*.tar.gz retention-days: 5 + build-driver-vm-linux: + name: Build Driver VM Linux + needs: [compute-versions] + uses: ./.github/workflows/driver-vm-linux.yml + with: + cargo-version: ${{ needs.compute-versions.outputs.cargo_version }} + image-tag: dev + checkout-ref: ${{ github.sha }} + secrets: inherit + + build-deb: + name: Build Debian Packages + needs: [compute-versions, build-cli-linux, build-gateway-binary-linux, build-driver-vm-linux] + uses: ./.github/workflows/deb-package.yml + with: + deb-version: ${{ needs.compute-versions.outputs.deb_version }} + checkout-ref: ${{ github.sha }} + secrets: inherit + # --------------------------------------------------------------------------- # Create / update the dev GitHub Release with CLI binaries and wheels # --------------------------------------------------------------------------- release-dev: name: Release Dev - needs: [compute-versions, build-cli-linux, build-cli-macos, build-gateway-binary-linux, build-gateway-binary-macos, build-supervisor-binary-linux, build-python-wheels-linux, build-python-wheel-macos] + needs: [compute-versions, build-cli-linux, build-cli-macos, build-gateway-binary-linux, build-gateway-binary-macos, build-supervisor-binary-linux, build-python-wheels-linux, build-python-wheel-macos, build-deb] runs-on: build-amd64 timeout-minutes: 10 outputs: @@ -656,6 +677,13 @@ jobs: path: release/ merge-multiple: true + - name: Download Debian package artifacts + uses: actions/download-artifact@v4 + with: + pattern: deb-linux-* + path: release/ + merge-multiple: true + - name: Capture wheel filenames id: wheel_filenames run: | @@ -672,6 +700,7 @@ jobs: openshell-x86_64-unknown-linux-musl.tar.gz \ openshell-aarch64-unknown-linux-musl.tar.gz \ openshell-aarch64-apple-darwin.tar.gz \ + openshell_*.deb \ *.whl > openshell-checksums-sha256.txt cat openshell-checksums-sha256.txt sha256sum \ @@ -684,7 +713,7 @@ jobs: openshell-sandbox-aarch64-unknown-linux-gnu.tar.gz > openshell-sandbox-checksums-sha256.txt cat openshell-sandbox-checksums-sha256.txt - - name: Prune stale wheel assets from dev release + - name: Prune stale wheel and deb assets from dev release uses: actions/github-script@v7 env: WHEEL_VERSION: ${{ needs.compute-versions.outputs.python_version }} @@ -717,19 +746,22 @@ jobs: } // Delete stale wheels - let kept = 0, deleted = 0; + let kept = 0, deleted = 0, debDeleted = 0; for (const asset of assets) { - if (!asset.name.endsWith('.whl')) continue; - if (asset.name.startsWith(currentPrefix)) { + if (asset.name.endsWith('.deb')) { + core.info(`Deleting stale deb package: ${asset.name} (id=${asset.id})`); + await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id }); + debDeleted++; + } else if (asset.name.endsWith('.whl') && asset.name.startsWith(currentPrefix)) { core.info(`Keeping current wheel: ${asset.name}`); kept++; - } else { + } else if (asset.name.endsWith('.whl')) { core.info(`Deleting stale wheel: ${asset.name} (id=${asset.id})`); await github.rest.repos.deleteReleaseAsset({ owner, repo, asset_id: asset.id }); deleted++; } } - core.info(`Summary: kept=${kept}, deleted=${deleted}`); + core.info(`Summary: kept_wheels=${kept}, deleted_wheels=${deleted}, deleted_debs=${debDeleted}`); - name: Move dev tag run: | @@ -760,6 +792,7 @@ jobs: release/openshell-x86_64-unknown-linux-musl.tar.gz release/openshell-aarch64-unknown-linux-musl.tar.gz release/openshell-aarch64-apple-darwin.tar.gz + release/openshell_*.deb release/openshell-gateway-x86_64-unknown-linux-gnu.tar.gz release/openshell-gateway-aarch64-unknown-linux-gnu.tar.gz release/openshell-gateway-aarch64-apple-darwin.tar.gz diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index 453636444b..7df792cba2 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -40,6 +40,7 @@ jobs: outputs: python_version: ${{ steps.v.outputs.python }} cargo_version: ${{ steps.v.outputs.cargo }} + deb_version: ${{ steps.v.outputs.deb }} # Semver without 'v' prefix (e.g. 0.6.0), used for image tags and release body semver: ${{ steps.v.outputs.semver }} steps: @@ -60,6 +61,7 @@ jobs: set -euo pipefail echo "python=$(uv run python tasks/scripts/release.py get-version --python)" >> "$GITHUB_OUTPUT" echo "cargo=$(uv run python tasks/scripts/release.py get-version --cargo)" >> "$GITHUB_OUTPUT" + echo "deb=$(uv run python tasks/scripts/release.py get-version --deb)" >> "$GITHUB_OUTPUT" echo "semver=${RELEASE_TAG#v}" >> "$GITHUB_OUTPUT" build-gateway: @@ -642,12 +644,31 @@ jobs: path: artifacts/*.tar.gz retention-days: 5 + build-driver-vm-linux: + name: Build Driver VM Linux + needs: [compute-versions] + uses: ./.github/workflows/driver-vm-linux.yml + with: + cargo-version: ${{ needs.compute-versions.outputs.cargo_version }} + image-tag: ${{ needs.compute-versions.outputs.semver }} + checkout-ref: ${{ inputs.tag || github.ref }} + secrets: inherit + + build-deb: + name: Build Debian Packages + needs: [compute-versions, build-cli-linux, build-gateway-binary-linux, build-driver-vm-linux] + uses: ./.github/workflows/deb-package.yml + with: + deb-version: ${{ needs.compute-versions.outputs.deb_version }} + checkout-ref: ${{ inputs.tag || github.ref }} + secrets: inherit + # --------------------------------------------------------------------------- # Create a tagged GitHub Release with CLI binaries and wheels # --------------------------------------------------------------------------- release: name: Release - needs: [compute-versions, build-cli-linux, build-cli-macos, build-gateway-binary-linux, build-gateway-binary-macos, build-supervisor-binary-linux, build-python-wheels-linux, build-python-wheel-macos, tag-ghcr-release] + needs: [compute-versions, build-cli-linux, build-cli-macos, build-gateway-binary-linux, build-gateway-binary-macos, build-supervisor-binary-linux, build-python-wheels-linux, build-python-wheel-macos, tag-ghcr-release, build-deb] runs-on: build-amd64 timeout-minutes: 10 outputs: @@ -685,6 +706,13 @@ jobs: path: release/ merge-multiple: true + - name: Download Debian package artifacts + uses: actions/download-artifact@v4 + with: + pattern: deb-linux-* + path: release/ + merge-multiple: true + - name: Capture wheel filenames id: wheel_filenames run: | @@ -701,6 +729,7 @@ jobs: openshell-x86_64-unknown-linux-musl.tar.gz \ openshell-aarch64-unknown-linux-musl.tar.gz \ openshell-aarch64-apple-darwin.tar.gz \ + openshell_*.deb \ *.whl > openshell-checksums-sha256.txt cat openshell-checksums-sha256.txt sha256sum \ @@ -733,6 +762,7 @@ jobs: release/openshell-x86_64-unknown-linux-musl.tar.gz release/openshell-aarch64-unknown-linux-musl.tar.gz release/openshell-aarch64-apple-darwin.tar.gz + release/openshell_*.deb release/openshell-gateway-x86_64-unknown-linux-gnu.tar.gz release/openshell-gateway-aarch64-unknown-linux-gnu.tar.gz release/openshell-gateway-aarch64-apple-darwin.tar.gz diff --git a/.gitignore b/.gitignore index 1921454b21..915c90d9dd 100644 --- a/.gitignore +++ b/.gitignore @@ -190,6 +190,9 @@ deploy/docker/.build/ # SBOM generated output (JSON, CSV) — release artifacts, not committed deploy/sbom/output/ +# Debian package build output (default OPENSHELL_OUTPUT_DIR for tasks/scripts/package-deb.sh) +artifacts/ + # Local mise settings mise.local.toml diff --git a/architecture/gateway.md b/architecture/gateway.md index e83640a43b..8e2724bc62 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -118,11 +118,12 @@ The gateway boots in `cli::run_cli` (`crates/openshell-server/src/cli.rs`) and p ## Configuration -All configuration is via CLI flags with environment variable fallbacks. The `--db-url` flag is required. The `--ssh-handshake-secret` flag is required for non-Docker drivers; Docker sandboxes do not receive a handshake secret. +All configuration is via CLI flags with environment variable fallbacks. The `--db-url` flag is required. | Flag | Env Var | Default | Description | |------|---------|---------|-------------| -| `--port` | `OPENSHELL_SERVER_PORT` | `8080` | TCP listen port (binds `0.0.0.0`) | +| `--port` | `OPENSHELL_SERVER_PORT` | `8080` | TCP listen port | +| `--bind-address` | `OPENSHELL_BIND_ADDRESS` | `0.0.0.0` | Address for the main gateway listener | | `--log-level` | `OPENSHELL_LOG_LEVEL` | `info` | Tracing log level filter | | `--tls-cert` | `OPENSHELL_TLS_CERT` | None | Path to PEM certificate file | | `--tls-key` | `OPENSHELL_TLS_KEY` | None | Path to PEM private key file | @@ -136,7 +137,7 @@ All configuration is via CLI flags with environment variable fallbacks. The `--d | `--grpc-endpoint` | `OPENSHELL_GRPC_ENDPOINT` | None | gRPC endpoint reachable from within the cluster (for supervisor callbacks) | | `--drivers` | `OPENSHELL_DRIVERS` | `kubernetes` | Compute backend to use. Current options are `kubernetes`, `docker`, and `vm`. | | `--vm-driver-state-dir` | `OPENSHELL_VM_DRIVER_STATE_DIR` | `target/openshell-vm-driver` | Host directory for VM sandbox rootfs, console logs, and runtime state | -| `--driver-dir` | `OPENSHELL_DRIVER_DIR` | unset | Override directory for `openshell-driver-vm`. When unset, the gateway searches `~/.local/libexec/openshell`, `/usr/local/libexec/openshell`, `/usr/local/libexec`, then a sibling binary. | +| `--driver-dir` | `OPENSHELL_DRIVER_DIR` | unset | Override directory for `openshell-driver-vm`. When unset, the gateway searches `~/.local/libexec/openshell`, `/usr/libexec/openshell`, `/usr/local/libexec/openshell`, `/usr/local/libexec`, then a sibling binary. | | `--vm-krun-log-level` | `OPENSHELL_VM_KRUN_LOG_LEVEL` | `1` | libkrun log level for VM helper processes | | `--vm-driver-vcpus` | `OPENSHELL_VM_DRIVER_VCPUS` | `2` | Default vCPU count for VM sandboxes | | `--vm-driver-mem-mib` | `OPENSHELL_VM_DRIVER_MEM_MIB` | `2048` | Default memory allocation for VM sandboxes in MiB | diff --git a/crates/openshell-driver-vm/README.md b/crates/openshell-driver-vm/README.md index 39be02676e..a36f3ea44d 100644 --- a/crates/openshell-driver-vm/README.md +++ b/crates/openshell-driver-vm/README.md @@ -37,7 +37,7 @@ mise run gateway:vm First run takes a few minutes while `mise run vm:setup` stages libkrun/libkrunfw/gvproxy and `mise run vm:rootfs -- --base` builds the embedded rootfs. Subsequent runs are cached. To keep the Unix socket path under macOS `SUN_LEN`, `mise run gateway:vm` and `start.sh` default the state dir to `/tmp/openshell-vm-driver-dev-$USER-port-$PORT/` (SQLite DB + per-sandbox rootfs + `compute-driver.sock`) unless `OPENSHELL_VM_DRIVER_STATE_DIR` is set. The wrapper auto-registers the gateway with the CLI (`gateway destroy` + `gateway add`) so no manual registration step is needed. When running under `sudo`, it uses `sudo -u $SUDO_USER` for the registration so the config is written under the invoking user's home directory. Re-runs are idempotent. -It also exports `OPENSHELL_DRIVER_DIR=$PWD/target/debug` before starting the gateway so local dev runs use the freshly built `openshell-driver-vm` instead of an older installed copy from `~/.local/libexec/openshell` or `/usr/local/libexec`. +It also exports `OPENSHELL_DRIVER_DIR=$PWD/target/debug` before starting the gateway so local dev runs use the freshly built `openshell-driver-vm` instead of an older installed copy from `~/.local/libexec/openshell`, `/usr/libexec/openshell`, or `/usr/local/libexec`. For GPU passthrough (VFIO), pass `-- --gpu` and run with root privileges: @@ -51,7 +51,6 @@ Override via environment: ```shell OPENSHELL_SERVER_PORT=9090 \ -OPENSHELL_SSH_HANDSHAKE_SECRET=$(openssl rand -hex 32) \ crates/openshell-driver-vm/start.sh ``` @@ -110,13 +109,12 @@ target/debug/openshell-gateway \ --database-url sqlite:/tmp/openshell-vm-driver-dev-$USER-port-8080/openshell.db \ --driver-dir $PWD/target/debug \ --grpc-endpoint http://host.containers.internal:8080 \ - --ssh-handshake-secret dev-vm-driver-secret \ --ssh-gateway-host 127.0.0.1 \ --ssh-gateway-port 8080 \ --vm-driver-state-dir /tmp/openshell-vm-driver-dev-$USER-port-8080 ``` -The gateway resolves `openshell-driver-vm` in this order: `--driver-dir`, conventional install locations (`~/.local/libexec/openshell`, `/usr/local/libexec/openshell`, `/usr/local/libexec`), then a sibling of the gateway binary. +The gateway resolves `openshell-driver-vm` in this order: `--driver-dir`, conventional install locations (`~/.local/libexec/openshell`, `/usr/libexec/openshell`, `/usr/local/libexec/openshell`, `/usr/local/libexec`), then a sibling of the gateway binary. ## Flags diff --git a/crates/openshell-driver-vm/start.sh b/crates/openshell-driver-vm/start.sh index d98bb7b917..0eb305c7d1 100755 --- a/crates/openshell-driver-vm/start.sh +++ b/crates/openshell-driver-vm/start.sh @@ -126,7 +126,7 @@ export OPENSHELL_DRIVER_DIR="${DRIVER_DIR}" export OPENSHELL_GRPC_ENDPOINT="${OPENSHELL_GRPC_ENDPOINT:-http://${VM_HOST_GATEWAY_DEFAULT}:${SERVER_PORT}}" export OPENSHELL_SSH_GATEWAY_HOST="${OPENSHELL_SSH_GATEWAY_HOST:-127.0.0.1}" export OPENSHELL_SSH_GATEWAY_PORT="${OPENSHELL_SSH_GATEWAY_PORT:-${SERVER_PORT}}" -export OPENSHELL_SSH_HANDSHAKE_SECRET="${OPENSHELL_SSH_HANDSHAKE_SECRET:-dev-vm-driver-secret}" +export OPENSHELL_SSH_HANDSHAKE_SECRET="${OPENSHELL_SSH_HANDSHAKE_SECRET:-}" export OPENSHELL_VM_DRIVER_STATE_DIR="${STATE_DIR}" # Resolve the VM runtime directory (contains vmlinux, virtiofsd, etc.) diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index 6e64b596ee..ae90c8b346 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -9,7 +9,7 @@ use openshell_core::ComputeDriverKind; use openshell_core::config::{ DEFAULT_SERVER_PORT, DEFAULT_SSH_HANDSHAKE_SKEW_SECS, DEFAULT_SSH_PORT, }; -use std::net::SocketAddr; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::path::PathBuf; use tracing::info; use tracing_subscriber::EnvFilter; @@ -22,10 +22,18 @@ use crate::{run_server, tracing_bus::TracingLogBus}; #[command(version = openshell_core::VERSION)] #[command(about = "OpenShell gRPC/HTTP server", long_about = None)] struct Args { - /// Port to bind the server to (all interfaces). + /// Port to bind the server to. #[arg(long, default_value_t = DEFAULT_SERVER_PORT, env = "OPENSHELL_SERVER_PORT")] port: u16, + /// Address to bind the server to. + #[arg( + long, + default_value_t = IpAddr::V4(Ipv4Addr::UNSPECIFIED), + env = "OPENSHELL_BIND_ADDRESS" + )] + bind_address: IpAddr, + /// Port for unauthenticated health endpoints (healthz, readyz). /// Set to 0 to disable the dedicated health listener. #[arg(long, default_value_t = 0, env = "OPENSHELL_HEALTH_PORT")] @@ -138,8 +146,9 @@ struct Args { /// Directory searched for compute-driver binaries (e.g. /// `openshell-driver-vm`) when an explicit binary override isn't /// configured. When unset, the gateway searches - /// `$HOME/.local/libexec/openshell`, `/usr/local/libexec/openshell`, - /// `/usr/local/libexec`, then a sibling of the gateway binary. + /// `$HOME/.local/libexec/openshell`, `/usr/libexec/openshell`, + /// `/usr/local/libexec/openshell`, `/usr/local/libexec`, then a sibling + /// of the gateway binary. #[arg(long, env = "OPENSHELL_DRIVER_DIR")] driver_dir: Option, @@ -286,7 +295,7 @@ async fn run_from_args(args: Args) -> Result<()> { EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&args.log_level)), ); - let bind = SocketAddr::from(([0, 0, 0, 0], args.port)); + let bind = SocketAddr::from((args.bind_address, args.port)); let tls = if args.disable_tls { None @@ -428,7 +437,9 @@ fn parse_compute_driver(value: &str) -> std::result::Result Result { @@ -186,7 +187,7 @@ pub fn resolve_compute_driver_bin(vm_config: &VmComputeConfig) -> Result>() .join(", "); Err(Error::config(format!( - "vm compute driver binary not found (searched {searched_display}); install it under --driver-dir / OPENSHELL_DRIVER_DIR, a conventional libexec path such as ~/.local/libexec/openshell or /usr/local/libexec{{,/openshell}}, or place it next to the gateway binary" + "vm compute driver binary not found (searched {searched_display}); install it under --driver-dir / OPENSHELL_DRIVER_DIR, a conventional libexec path such as ~/.local/libexec/openshell, /usr/libexec/openshell, or /usr/local/libexec{{,/openshell}}, or place it next to the gateway binary" ))) } @@ -441,12 +442,13 @@ mod tests { } #[test] - fn resolve_driver_search_dirs_include_usr_local_libexec_fallbacks() { + fn resolve_driver_search_dirs_include_libexec_fallbacks() { let dirs = resolve_driver_search_dirs(&VmComputeConfig { driver_dir: None, ..Default::default() }); + assert!(dirs.contains(&PathBuf::from("/usr/libexec/openshell"))); assert!(dirs.contains(&PathBuf::from("/usr/local/libexec/openshell"))); assert!(dirs.contains(&PathBuf::from("/usr/local/libexec"))); } diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 18243dc5af..2a18e209a2 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -154,13 +154,6 @@ pub async fn run_server( if database_url.is_empty() { return Err(Error::config("database_url is required")); } - let driver = configured_compute_driver(&config)?; - if config.ssh_handshake_secret.is_empty() && driver != ComputeDriverKind::Docker { - return Err(Error::config( - "ssh_handshake_secret is required. Set --ssh-handshake-secret or OPENSHELL_SSH_HANDSHAKE_SECRET", - )); - } - let store = Arc::new(Store::connect(database_url).await?); let oidc_cache = if let Some(ref oidc) = config.oidc { diff --git a/deploy/deb/control.in b/deploy/deb/control.in new file mode 100644 index 0000000000..9f77f8775d --- /dev/null +++ b/deploy/deb/control.in @@ -0,0 +1,16 @@ +Package: openshell +Version: @VERSION@ +Architecture: @ARCH@ +Maintainer: NVIDIA OpenShell Maintainers +Section: utils +Priority: optional +Pre-Depends: init-system-helpers (>= 1.54~) +Homepage: https://github.com/NVIDIA/OpenShell +Description: Safe, sandboxed runtimes for autonomous AI agents + OpenShell provides host-side command-line and gateway components for + launching and managing policy-enforced AI agent sandboxes. The package + installs the openshell CLI, openshell-gateway daemon, and the VM compute + driver helper, plus a per-user systemd unit for running the gateway. + . + The systemd unit is user-scope (under /usr/lib/systemd/user/). To start + it, run `systemctl --user enable --now openshell-gateway`. diff --git a/deploy/deb/openshell-gateway.service b/deploy/deb/openshell-gateway.service new file mode 100644 index 0000000000..4705b547d2 --- /dev/null +++ b/deploy/deb/openshell-gateway.service @@ -0,0 +1,28 @@ +[Unit] +Description=OpenShell Gateway +Documentation=https://github.com/NVIDIA/OpenShell +After=default.target + +[Service] +Type=simple +StateDirectory=openshell/gateway +# %S resolves to $XDG_STATE_HOME for user services. +Environment=OPENSHELL_BIND_ADDRESS=127.0.0.1 +Environment=OPENSHELL_SERVER_PORT=17670 +Environment=OPENSHELL_DISABLE_TLS=true +Environment=OPENSHELL_DISABLE_GATEWAY_AUTH=true +Environment=OPENSHELL_DB_URL=sqlite:%S/openshell/gateway/openshell.db +Environment=OPENSHELL_DRIVERS=vm +Environment=OPENSHELL_GRPC_ENDPOINT=http://127.0.0.1:17670 +Environment=OPENSHELL_SSH_GATEWAY_HOST=127.0.0.1 +Environment=OPENSHELL_SSH_GATEWAY_PORT=17670 +Environment=OPENSHELL_VM_DRIVER_STATE_DIR=%S/openshell/vm-driver +EnvironmentFile=-%h/.config/openshell/gateway.env +ExecStart=/usr/bin/openshell-gateway +Restart=on-failure +RestartSec=5s +PrivateTmp=true +UMask=0077 + +[Install] +WantedBy=default.target diff --git a/deploy/deb/postinst.sh b/deploy/deb/postinst.sh new file mode 100755 index 0000000000..d9784214f9 --- /dev/null +++ b/deploy/deb/postinst.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# postinst for openshell. +# +# The packaged systemd unit is user-scope (installed under +# /usr/lib/systemd/user/) so dpkg cannot enable or start it on the user's +# behalf. Each user opts in by running: +# systemctl --user daemon-reload +# systemctl --user enable --now openshell-gateway +# +# Tell any running per-user systemd manager to re-scan its unit search +# path so already-logged-in users see the new unit without restarting +# their session. +set -e + +case "$1" in +configure | abort-upgrade | abort-deconfigure | abort-remove) + if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then + systemctl daemon-reload >/dev/null 2>&1 || true + # --global only refreshes per-user managers' generators on next + # session; existing managers pick up new unit files without it. + systemctl --global daemon-reload >/dev/null 2>&1 || true + fi + ;; + +*) + echo "postinst called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +exit 0 diff --git a/deploy/deb/postrm.sh b/deploy/deb/postrm.sh new file mode 100755 index 0000000000..7e1893abeb --- /dev/null +++ b/deploy/deb/postrm.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# postrm for openshell. +set -e + +if [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then + systemctl daemon-reload >/dev/null 2>&1 || true + systemctl --global daemon-reload >/dev/null 2>&1 || true +fi + +exit 0 diff --git a/deploy/deb/prerm.sh b/deploy/deb/prerm.sh new file mode 100755 index 0000000000..e9099eac64 --- /dev/null +++ b/deploy/deb/prerm.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# prerm for openshell. +# +# Per-user systemd units cannot be stopped from a system-scope dpkg hook. +# Users who want to stop their gateway before removing the package should +# run `systemctl --user stop openshell-gateway` themselves. +set -e + +case "$1" in +remove | upgrade | deconfigure | failed-upgrade) ;; + +*) + echo "prerm called with unknown argument \`$1'" >&2 + exit 1 + ;; +esac + +exit 0 diff --git a/install-dev.sh b/install-dev.sh new file mode 100755 index 0000000000..f1f8501263 --- /dev/null +++ b/install-dev.sh @@ -0,0 +1,288 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Install the OpenShell development build from the rolling GitHub `dev` release. +# +# This script is intended as a convenient installer for development builds. It +# currently supports Debian packages on Linux amd64 and arm64 only. +# +set -e + +APP_NAME="openshell" +REPO="NVIDIA/OpenShell" +GITHUB_URL="https://github.com/${REPO}" +RELEASE_TAG="dev" +CHECKSUMS_NAME="openshell-checksums-sha256.txt" + +info() { + printf '%s: %s\n' "$APP_NAME" "$*" >&2 +} + +error() { + printf '%s: error: %s\n' "$APP_NAME" "$*" >&2 + exit 1 +} + +usage() { + cat </dev/null 2>&1 +} + +require_cmd() { + if ! has_cmd "$1"; then + error "'$1' is required" + fi +} + +download() { + _url="$1" + _output="$2" + curl -fLsS --retry 3 --max-redirs 5 -o "$_output" "$_url" +} + +download_release_asset() { + _filename="$1" + _output="$2" + + if curl -fLs --retry 3 --max-redirs 5 -o "$_output" \ + "${GITHUB_URL}/releases/download/${RELEASE_TAG}/${_filename}"; then + return 0 + fi + + # GitHub normalizes `~` to `.` in release asset names, while the checksum file + # still records the Debian package filename with `~dev` for correct version + # ordering. Download the normalized asset but verify it against the checksum + # entry for the original package filename. + _normalized="$(printf '%s' "$_filename" | tr '~' '.')" + if [ "$_normalized" != "$_filename" ]; then + if download "${GITHUB_URL}/releases/download/${RELEASE_TAG}/${_normalized}" "$_output"; then + info "using GitHub-normalized asset name ${_normalized}" + return 0 + fi + fi + + return 1 +} + +as_root() { + if [ "$(id -u)" -eq 0 ]; then + "$@" + elif has_cmd sudo; then + sudo "$@" + else + error "this installer needs root privileges; rerun as root or install sudo" + fi +} + +target_user() { + if [ "$(id -u)" -eq 0 ] && [ -n "${SUDO_USER:-}" ] && [ "${SUDO_USER}" != "root" ]; then + echo "$SUDO_USER" + else + id -un + fi +} + +user_home() { + _user="$1" + if has_cmd getent; then + _home="$(getent passwd "$_user" | awk -F: '{ print $6 }')" + if [ -n "$_home" ]; then + echo "$_home" + return 0 + fi + fi + + if [ "$(id -un)" = "$_user" ]; then + echo "${HOME:-}" + return 0 + fi + + echo "/home/${_user}" +} + +as_target_user() { + _bus="unix:path=${TARGET_RUNTIME_DIR}/bus" + if [ "$(id -u)" -eq "$TARGET_UID" ]; then + env HOME="$TARGET_HOME" XDG_RUNTIME_DIR="$TARGET_RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$_bus" "$@" + elif has_cmd sudo; then + sudo -u "$TARGET_USER" env HOME="$TARGET_HOME" XDG_RUNTIME_DIR="$TARGET_RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$_bus" "$@" + elif has_cmd runuser; then + runuser -u "$TARGET_USER" -- env HOME="$TARGET_HOME" XDG_RUNTIME_DIR="$TARGET_RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$_bus" "$@" + else + error "cannot run user service commands as ${TARGET_USER}; install sudo or run as ${TARGET_USER}" + fi +} + +check_platform() { + if [ "$(uname -s)" != "Linux" ]; then + error "unsupported OS: $(uname -s); dev Debian packages require Linux" + fi + + require_cmd dpkg +} + +get_deb_arch() { + _arch="$(dpkg --print-architecture)" + + case "$_arch" in + amd64|arm64) + echo "$_arch" + ;; + *) + error "no dev Debian package is published for architecture: ${_arch}" + ;; + esac +} + +find_deb_asset() { + _checksums="$1" + _arch="$2" + + awk -v arch="$_arch" ' + $2 ~ "^\\*?openshell_.*_" arch "\\.deb$" { + sub("^\\*", "", $2) + print $2 + exit + } + ' "$_checksums" +} + +verify_checksum() { + _archive="$1" + _checksums="$2" + _filename="$3" + + if has_cmd sha256sum; then + _expected="$(awk -v name="$_filename" '($2 == name || $2 == "*" name) { print $1; exit }' "$_checksums")" + [ -n "$_expected" ] || error "no checksum entry found for ${_filename}" + echo "$_expected $_archive" | sha256sum -c --quiet + elif has_cmd shasum; then + _expected="$(awk -v name="$_filename" '($2 == name || $2 == "*" name) { print $1; exit }' "$_checksums")" + [ -n "$_expected" ] || error "no checksum entry found for ${_filename}" + echo "$_expected $_archive" | shasum -a 256 -c --quiet + else + error "neither 'sha256sum' nor 'shasum' found; cannot verify download integrity" + fi +} + +install_deb_package() { + _deb_path="$1" + + if has_cmd apt-get; then + as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y \ + -o Dpkg::Options::=--force-confdef \ + -o Dpkg::Options::=--force-confnew \ + "$_deb_path" + elif has_cmd apt; then + as_root env DEBIAN_FRONTEND=noninteractive apt install -y \ + -o Dpkg::Options::=--force-confdef \ + -o Dpkg::Options::=--force-confnew \ + "$_deb_path" + else + as_root dpkg --force-confdef --force-confnew -i "$_deb_path" + fi +} + +start_user_gateway() { + info "starting openshell-gateway user service as ${TARGET_USER}..." + + if ! as_target_user systemctl --user daemon-reload; then + info "could not reach the user systemd manager for ${TARGET_USER}" + info "start the gateway later with: systemctl --user enable --now openshell-gateway" + info "then register it with: openshell gateway add http://127.0.0.1:17670 --local --name local" + return 0 + fi + + as_target_user systemctl --user enable --now openshell-gateway + as_target_user systemctl --user is-active --quiet openshell-gateway + + info "registering local gateway as ${TARGET_USER}..." + as_target_user openshell gateway add http://127.0.0.1:17670 --local --name local \ + || as_target_user openshell gateway select local +} + +main() { + while [ "$#" -gt 0 ]; do + case "$1" in + --help) + usage + exit 0 + ;; + *) + error "unknown option: $1" + ;; + esac + shift + done + + require_cmd curl + check_platform + + TARGET_USER="$(target_user)" + TARGET_UID="$(id -u "$TARGET_USER" 2>/dev/null || true)" + [ -n "$TARGET_UID" ] || error "cannot resolve uid for ${TARGET_USER}" + TARGET_HOME="$(user_home "$TARGET_USER")" + if [ "$(id -u)" -eq "$TARGET_UID" ] && [ -n "${XDG_RUNTIME_DIR:-}" ]; then + TARGET_RUNTIME_DIR="$XDG_RUNTIME_DIR" + else + TARGET_RUNTIME_DIR="/run/user/${TARGET_UID}" + fi + + _arch="$(get_deb_arch)" + _tmpdir="$(mktemp -d)" + chmod 0755 "$_tmpdir" + trap 'rm -rf "$_tmpdir"' EXIT + + _checksums_url="${GITHUB_URL}/releases/download/${RELEASE_TAG}/${CHECKSUMS_NAME}" + info "downloading ${RELEASE_TAG} release checksums..." + download "$_checksums_url" "${_tmpdir}/${CHECKSUMS_NAME}" || { + error "failed to download ${_checksums_url}" + } + + _deb_file="$(find_deb_asset "${_tmpdir}/${CHECKSUMS_NAME}" "$_arch")" + if [ -z "$_deb_file" ]; then + error "no dev Debian package found for architecture: ${_arch}" + fi + + _deb_url="${GITHUB_URL}/releases/download/${RELEASE_TAG}/${_deb_file}" + _deb_path="${_tmpdir}/${_deb_file}" + + info "selected ${_deb_file}" + + info "downloading ${_deb_file}..." + download_release_asset "$_deb_file" "$_deb_path" || { + error "failed to download ${_deb_url}" + } + chmod 0644 "$_deb_path" + + info "verifying checksum..." + verify_checksum "$_deb_path" "${_tmpdir}/${CHECKSUMS_NAME}" "$_deb_file" + + info "installing ${_deb_file}..." + install_deb_package "$_deb_path" + info "installed ${APP_NAME} development package" + start_user_gateway +} + +main "$@" diff --git a/tasks/package.toml b/tasks/package.toml new file mode 100644 index 0000000000..496f93de27 --- /dev/null +++ b/tasks/package.toml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Distribution package tasks + +["package:deb"] +description = "Build a Debian package from supplied OpenShell binaries" +run = "tasks/scripts/package-deb.sh" +hide = true + +["package:deb:amd64"] +description = "Build an amd64 Debian package from supplied OpenShell binaries" +env = { OPENSHELL_DEB_ARCH = "amd64" } +run = "tasks/scripts/package-deb.sh" +hide = true + +["package:deb:arm64"] +description = "Build an arm64 Debian package from supplied OpenShell binaries" +env = { OPENSHELL_DEB_ARCH = "arm64" } +run = "tasks/scripts/package-deb.sh" +hide = true + +["package:deb:install"] +description = "Build OpenShell from source and install the deb locally (requires sudo)" +run = "tasks/scripts/package-deb-install.sh" diff --git a/tasks/scripts/package-deb-install.sh b/tasks/scripts/package-deb-install.sh new file mode 100755 index 0000000000..735ce70a93 --- /dev/null +++ b/tasks/scripts/package-deb-install.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Build OpenShell from source and install the resulting Debian package +# locally for testing. Intended for developers iterating on the deb itself +# or on the gateway-as-a-service flow. +# +# Steps: +# 1. cargo build --release the three binaries that go into the deb. +# 2. Run tasks/scripts/package-deb.sh against those binaries. +# 3. sudo dpkg -i the resulting artifact. +# 4. Start the packaged user gateway service and register it locally. +# +# Usage: +# mise run package:deb:install +# +# Optional env: +# OPENSHELL_DEB_VERSION override the package version (default: 0.0.0-local) +# OPENSHELL_DEB_ARCH override the deb architecture (default: host) +# OPENSHELL_OUTPUT_DIR override the artifact directory (default: artifacts) + +set -euo pipefail + +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +cd "$repo_root" + +VERSION="${OPENSHELL_DEB_VERSION:-0.0.0-local}" +OUTPUT_DIR="${OPENSHELL_OUTPUT_DIR:-artifacts}" +ARCH="${OPENSHELL_DEB_ARCH:-$(dpkg --print-architecture 2>/dev/null || uname -m)}" +GATEWAY_NAME="local" +GATEWAY_ENDPOINT="http://127.0.0.1:17670" + +remove_existing_gateway_registration() { + local config_home="${XDG_CONFIG_HOME:-${HOME}/.config}" + local openshell_config_dir="${config_home}/openshell" + local gateway_dir="${openshell_config_dir}/gateways/${GATEWAY_NAME}" + local active_gateway_path="${openshell_config_dir}/active_gateway" + + if [ ! -f "${gateway_dir}/metadata.json" ]; then + return + fi + + echo "==> Removing existing ${GATEWAY_NAME} gateway registration" + rm -f \ + "${gateway_dir}/metadata.json" \ + "${gateway_dir}/edge_token" \ + "${gateway_dir}/cf_token" \ + "${gateway_dir}/oidc_token.json" + + if [ -f "$active_gateway_path" ] && [ "$(cat "$active_gateway_path")" = "$GATEWAY_NAME" ]; then + rm -f "$active_gateway_path" + fi +} + +echo "==> Building release binaries" +cargo build --release \ + -p openshell-cli \ + -p openshell-server \ + -p openshell-driver-vm + +echo "==> Building Debian package" +OPENSHELL_CLI_BINARY="${repo_root}/target/release/openshell" \ + OPENSHELL_GATEWAY_BINARY="${repo_root}/target/release/openshell-gateway" \ + OPENSHELL_DRIVER_VM_BINARY="${repo_root}/target/release/openshell-driver-vm" \ + OPENSHELL_DEB_VERSION="$VERSION" \ + OPENSHELL_DEB_ARCH="$ARCH" \ + OPENSHELL_OUTPUT_DIR="$OUTPUT_DIR" \ + "${repo_root}/tasks/scripts/package-deb.sh" + +deb_path="${OUTPUT_DIR}/openshell_${VERSION}_${ARCH}.deb" +case "$deb_path" in +/*) ;; +*) deb_path="${repo_root}/${deb_path}" ;; +esac + +echo "==> Installing ${deb_path}" +sudo dpkg -i "$deb_path" + +openshell --version +openshell-gateway --version + +echo "==> Starting user gateway service" +systemctl --user daemon-reload +systemctl --user enable --now openshell-gateway +systemctl --user is-active --quiet openshell-gateway + +echo "==> Registering local gateway" +remove_existing_gateway_registration +openshell gateway add "$GATEWAY_ENDPOINT" --local --name "$GATEWAY_NAME" diff --git a/tasks/scripts/package-deb.sh b/tasks/scripts/package-deb.sh new file mode 100755 index 0000000000..9d7e3d3281 --- /dev/null +++ b/tasks/scripts/package-deb.sh @@ -0,0 +1,188 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Build the openshell Debian package by staging pre-built binaries alongside +# the authoring tree under deploy/deb/, then invoking dpkg-deb --build. +# +# All static content (systemd unit, /etc/default file, maintainer scripts, +# default gateway metadata, control template) lives under deploy/deb/. This +# script only renders the version/arch into control.in and copies files into +# the package staging tree. + +set -euo pipefail + +APP_NAME="openshell" + +usage() { + cat <<'EOF' +Build the openshell Debian package. + +Required environment: + OPENSHELL_CLI_BINARY Path to openshell + OPENSHELL_GATEWAY_BINARY Path to openshell-gateway + OPENSHELL_DRIVER_VM_BINARY Path to openshell-driver-vm + OPENSHELL_DEB_VERSION Debian package version + +Optional environment: + OPENSHELL_DEB_ARCH Debian architecture (amd64 or arm64; defaults to host arch) + OPENSHELL_OUTPUT_DIR Output directory (default: artifacts) +EOF +} + +require_env() { + local name="$1" + if [ -z "${!name:-}" ]; then + echo "error: ${name} is required" >&2 + usage >&2 + exit 2 + fi +} + +stage_binary() { + local src="$1" + local dst="$2" + if [ ! -x "$src" ]; then + echo "error: binary is missing or not executable: ${src}" >&2 + exit 1 + fi + mkdir -p "$(dirname "$dst")" + install -m 0755 "$src" "$dst" +} + +infer_deb_arch() { + if command -v dpkg >/dev/null 2>&1; then + dpkg --print-architecture + return + fi + + case "$(uname -m)" in + x86_64 | amd64) echo "amd64" ;; + aarch64 | arm64) echo "arm64" ;; + *) uname -m ;; + esac +} + +# --------------------------------------------------------------------------- +# Inputs +# --------------------------------------------------------------------------- + +require_env OPENSHELL_CLI_BINARY +require_env OPENSHELL_GATEWAY_BINARY +require_env OPENSHELL_DRIVER_VM_BINARY +require_env OPENSHELL_DEB_VERSION + +OPENSHELL_DEB_ARCH="${OPENSHELL_DEB_ARCH:-$(infer_deb_arch)}" + +case "$OPENSHELL_DEB_ARCH" in +amd64 | arm64) ;; +*) + echo "error: OPENSHELL_DEB_ARCH must be amd64 or arm64, got ${OPENSHELL_DEB_ARCH}" >&2 + exit 2 + ;; +esac + +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +src_dir="${repo_root}/deploy/deb" +output_dir_input="${OPENSHELL_OUTPUT_DIR:-artifacts}" +case "$output_dir_input" in +/*) output_dir="$output_dir_input" ;; +*) output_dir="${repo_root}/${output_dir_input}" ;; +esac +mkdir -p "$output_dir" + +if [ ! -d "$src_dir" ]; then + echo "error: deb source directory not found: ${src_dir}" >&2 + exit 1 +fi + +package_file="${output_dir}/${APP_NAME}_${OPENSHELL_DEB_VERSION}_${OPENSHELL_DEB_ARCH}.deb" +tmpdir="$(mktemp -d)" +trap 'rm -rf "$tmpdir"' EXIT + +pkgroot="${tmpdir}/pkg" +mkdir -p "$pkgroot/DEBIAN" + +# --------------------------------------------------------------------------- +# Stage the package payload +# --------------------------------------------------------------------------- + +# Binaries. +stage_binary "$OPENSHELL_CLI_BINARY" "$pkgroot/usr/bin/openshell" +stage_binary "$OPENSHELL_GATEWAY_BINARY" "$pkgroot/usr/bin/openshell-gateway" +stage_binary "$OPENSHELL_DRIVER_VM_BINARY" "$pkgroot/usr/libexec/openshell/openshell-driver-vm" + +# Per-user systemd unit. Each user enables it via `systemctl --user`. +install -D -m 0644 "$src_dir/openshell-gateway.service" \ + "$pkgroot/usr/lib/systemd/user/openshell-gateway.service" + +# --------------------------------------------------------------------------- +# DEBIAN/ control directory +# --------------------------------------------------------------------------- + +# Render control from template. +sed \ + -e "s|@VERSION@|${OPENSHELL_DEB_VERSION}|g" \ + -e "s|@ARCH@|${OPENSHELL_DEB_ARCH}|g" \ + "$src_dir/control.in" >"$pkgroot/DEBIAN/control" + +# No conffiles: the package owns no /etc files. Per-user configuration +# lives under $XDG_CONFIG_HOME/openshell/. + +# Maintainer scripts. +install -m 0755 "$src_dir/postinst.sh" "$pkgroot/DEBIAN/postinst" +install -m 0755 "$src_dir/prerm.sh" "$pkgroot/DEBIAN/prerm" +install -m 0755 "$src_dir/postrm.sh" "$pkgroot/DEBIAN/postrm" + +# --------------------------------------------------------------------------- +# Documentation +# --------------------------------------------------------------------------- + +doc_dir="$pkgroot/usr/share/doc/openshell" +mkdir -p "$doc_dir" + +if [ -f "${repo_root}/LICENSE" ]; then + install -m 0644 "${repo_root}/LICENSE" "$doc_dir/copyright" +else + cat >"$doc_dir/copyright" <<'EOF' +OpenShell is distributed under the Apache-2.0 license. +EOF + chmod 0644 "$doc_dir/copyright" +fi + +# Real RFC2822 date so lintian doesn't complain about epoch-zero changelogs. +gzip -n -9 -c >"$doc_dir/changelog.gz" < $(date -uR) +EOF + +# --------------------------------------------------------------------------- +# Build +# --------------------------------------------------------------------------- + +dpkg-deb --build --root-owner-group "$pkgroot" "$package_file" +dpkg-deb --info "$package_file" +dpkg-deb --contents "$package_file" + +# --------------------------------------------------------------------------- +# Smoke tests +# --------------------------------------------------------------------------- + +extract_dir="${tmpdir}/extract" +mkdir -p "$extract_dir" +dpkg-deb -x "$package_file" "$extract_dir" +"$extract_dir/usr/bin/openshell" --version +"$extract_dir/usr/bin/openshell-gateway" --version +"$extract_dir/usr/libexec/openshell/openshell-driver-vm" --version + +if command -v systemd-analyze >/dev/null 2>&1; then + # verify --user catches user-scope-specific issues like StateDirectory= + # resolution and the %h/%S specifiers used in this unit. + systemd-analyze --user verify "$extract_dir/usr/lib/systemd/user/openshell-gateway.service" \ + || echo "warning: systemd-analyze verify failed in the build environment" >&2 +fi + +echo "Wrote ${package_file}" diff --git a/tasks/scripts/release.py b/tasks/scripts/release.py index 57e8fbf515..0e1772b8a6 100644 --- a/tasks/scripts/release.py +++ b/tasks/scripts/release.py @@ -19,6 +19,7 @@ class Versions: python: str cargo: str docker: str + deb: str git_tag: str git_sha: str @@ -55,6 +56,12 @@ def _compute_versions() -> Versions: # Docker tags can't contain '+'. docker_version = cargo_version.replace("+", "-") + # Debian versions use '~' so prereleases sort before the eventual release. + deb_version = cargo_version + deb_version = deb_version[1:] if deb_version.startswith("v") else deb_version + deb_version = deb_version.replace("-dev.", "~dev.", 1) + deb_version = f"{deb_version}-1" + git_tag = _git(["describe", "--tags", "--abbrev=0"]) git_sha = _git(["rev-parse", "--short", "HEAD"]) @@ -62,6 +69,7 @@ def _compute_versions() -> Versions: python=python_version, cargo=cargo_version, docker=docker_version, + deb=deb_version, git_tag=git_tag, git_sha=git_sha, ) @@ -75,10 +83,13 @@ def get_version(format: str) -> None: print(versions.cargo) elif format == "docker": print(versions.docker) + elif format == "deb": + print(versions.deb) else: print(f"VERSION_PY={versions.python}") print(f"VERSION_CARGO={versions.cargo}") print(f"VERSION_DOCKER={versions.docker}") + print(f"VERSION_DEB={versions.deb}") print(f"GIT_TAG={versions.git_tag}") print(f"GIT_SHA={versions.git_sha}") @@ -97,6 +108,9 @@ def build_parser() -> argparse.ArgumentParser: get_version_parser.add_argument( "--docker", action="store_true", help="Print Docker version only." ) + get_version_parser.add_argument( + "--deb", action="store_true", help="Print Debian package version only." + ) return parser @@ -112,6 +126,8 @@ def main() -> None: get_version("cargo") elif args.docker: get_version("docker") + elif args.deb: + get_version("deb") else: get_version("all") From fcefdd53b7d1aba518a591d6fde2ff3461cfe3a1 Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Fri, 1 May 2026 08:09:11 -0700 Subject: [PATCH 3/9] feat(driver-docker): use host networking for sandboxes (#1080) --- Cargo.lock | 1 - architecture/README.md | 1 + architecture/docker-driver.md | 129 ++++++++++++++++++++ crates/openshell-core/src/config.rs | 23 ++++ crates/openshell-driver-docker/Cargo.toml | 1 - crates/openshell-driver-docker/src/lib.rs | 55 ++++----- crates/openshell-driver-docker/src/tests.rs | 40 ++++-- crates/openshell-server/src/lib.rs | 80 +++++++++--- 8 files changed, 264 insertions(+), 66 deletions(-) create mode 100644 architecture/docker-driver.md diff --git a/Cargo.lock b/Cargo.lock index bfaa55d934..c6409ab125 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3188,7 +3188,6 @@ dependencies = [ "tokio-stream", "tonic", "tracing", - "url", ] [[package]] diff --git a/architecture/README.md b/architecture/README.md index 36b0a4978f..96e5f49e2d 100644 --- a/architecture/README.md +++ b/architecture/README.md @@ -299,6 +299,7 @@ This opens an interactive SSH session into the sandbox, with all provider creden | [Docs Site Architecture](docs-site.md) | Documentation source layout, navigation structure, local validation and preview workflow, and publish pipeline. | | [Policy Language](security-policy.md) | The YAML/Rego policy system that governs sandbox behavior. | | [Inference Routing](inference-routing.md) | Transparent interception and sandbox-local routing of AI inference API calls to configured backends. | +| [Docker Driver](docker-driver.md) | Docker compute driver implementation, host networking, loopback gateway connectivity. | | [System Architecture](system-architecture.md) | Top-level system architecture diagram with all deployable components and communication flows. | | [Gateway Settings Channel](gateway-settings.md) | Runtime settings channel: two-tier key-value configuration, global policy override, settings registry, CLI/TUI commands. | | [TUI](tui.md) | Terminal user interface for sandbox interaction. | diff --git a/architecture/docker-driver.md b/architecture/docker-driver.md new file mode 100644 index 0000000000..25d48f740a --- /dev/null +++ b/architecture/docker-driver.md @@ -0,0 +1,129 @@ +# Docker Driver + +The Docker compute driver manages sandbox containers through the local Docker +daemon using the `bollard` client. It targets local developer environments +where running a full Kubernetes cluster is unnecessary but Docker is already +available. + +The gateway remains a host process. Each sandbox container bind-mounts a Linux +`openshell-sandbox` supervisor binary and uses Docker host networking so the +supervisor can connect to a gateway that is listening on host loopback without +requiring an additional bridge-reachable listener on Linux. + +## Source Map + +| Path | Purpose | +|---|---| +| `crates/openshell-driver-docker/src/lib.rs` | Docker compute driver implementation | +| `crates/openshell-driver-docker/src/tests.rs` | Unit tests for container spec, env, TLS paths, GPU, resource limits, and cache helpers | +| `crates/openshell-server/src/cli.rs` | Gateway CLI flags for Docker driver configuration | +| `crates/openshell-server/src/lib.rs` | In-process Docker compute runtime wiring | + +## Runtime Model + +```mermaid +flowchart LR + CLI["OpenShell CLI
host"] -->|gRPC/HTTP
127.0.0.1:8080| GW["Gateway
host process"] + GW -->|Docker API| DA["Docker daemon"] + DA --> C["Sandbox container
network_mode=host"] + C --> SV["openshell-sandbox
supervisor"] + SV -->|ConnectSupervisor
OPENSHELL_ENDPOINT| GW + SV --> NS["Nested sandbox netns
workload + policy proxy"] +``` + +The Docker container itself uses `network_mode = "host"`. This is intentional +for now: it makes a gateway bound to `127.0.0.1` reachable from the supervisor +as `127.0.0.1`, matching the host process' endpoint without a bridge listener, +NAT rule, or userland proxy. + +The container also gets a Docker-managed `/etc/hosts` entry for +`host.openshell.internal` that resolves to `127.0.0.1`. This gives callers a +stable OpenShell-owned hostname for host services without requiring changes to +the host machine's hosts file. + +The supervisor still creates a nested network namespace for the actual workload +and routes workload traffic through its policy proxy. Agent network requests are +enforced by the supervisor in that nested namespace. + +## Container Spec + +`build_container_create_body()` constructs the Docker container: + +| Field | Value | Reason | +|---|---|---| +| `image` | Sandbox template image | User-selected runtime image | +| `user` | `"0"` | Supervisor needs root inside the container for namespace and mount setup | +| `entrypoint` | `/opt/openshell/bin/openshell-sandbox` | Bind-mounted supervisor binary | +| `cmd` | Empty vector | Prevents image CMD args from being appended to the supervisor entrypoint | +| `network_mode` | `"host"` | Lets supervisor connect to host loopback gateway endpoints | +| `extra_hosts` | `host.openshell.internal:127.0.0.1` | Stable container-local alias for host loopback services | +| `cap_add` | `SYS_ADMIN`, `NET_ADMIN`, `SYS_PTRACE`, `SYSLOG` | Required for supervisor isolation setup and process inspection | +| `security_opt` | `apparmor=unconfined` | Docker's default AppArmor profile blocks mount operations required by network namespace setup | +| `restart_policy` | `unless-stopped` | Resume managed sandboxes after Docker or gateway restarts | +| `device_requests` | CDI all-GPU request when `spec.gpu` is true | Enables Docker CDI GPU sandboxes when daemon support is detected | + +## Gateway Callback + +The Docker driver injects `OPENSHELL_ENDPOINT` into each sandbox container from +`Config::grpc_endpoint` without rewriting it. This is the key difference from a +bridge-network design. + +Examples: + +```shell +OPENSHELL_GRPC_ENDPOINT=http://127.0.0.1:8080 +``` + +and: + +```shell +OPENSHELL_GRPC_ENDPOINT=https://127.0.0.1:8080 +``` + +are passed into the supervisor as-is. Because the container shares the host +network namespace, `127.0.0.1` resolves to the host loopback interface and the +gateway is reachable when it binds loopback. + +The endpoint can also use the stable alias: + +```shell +OPENSHELL_GRPC_ENDPOINT=http://host.openshell.internal:8080 +``` + +In host network mode this name resolves to `127.0.0.1` inside the container. + +For TLS endpoints, the gateway certificate must include the exact endpoint host +as a subject alternative name. For `https://127.0.0.1:8080`, the certificate +needs an IP SAN for `127.0.0.1`. For `https://localhost:8080`, it needs a DNS +SAN for `localhost`. For `https://host.openshell.internal:8080`, it needs a DNS +SAN for `host.openshell.internal`. Docker sandboxes also require client TLS +material: + +| Env / flag | Purpose | +|---|---| +| `OPENSHELL_DOCKER_TLS_CA` / `--docker-tls-ca` | CA certificate mounted at `/etc/openshell/tls/client/ca.crt` | +| `OPENSHELL_DOCKER_TLS_CERT` / `--docker-tls-cert` | Client certificate mounted at `/etc/openshell/tls/client/tls.crt` | +| `OPENSHELL_DOCKER_TLS_KEY` / `--docker-tls-key` | Client private key mounted at `/etc/openshell/tls/client/tls.key` | + +When `OPENSHELL_GRPC_ENDPOINT` uses `http://`, these TLS mounts are not +required and providing them is rejected. When it uses `https://`, all three are +required. + +## Environment + +`build_environment()` merges template environment, spec environment, and +driver-controlled keys. Driver-controlled keys win: + +| Variable | Value | +|---|---| +| `OPENSHELL_ENDPOINT` | Exact configured gateway endpoint | +| `OPENSHELL_SANDBOX_ID` | Sandbox id | +| `OPENSHELL_SANDBOX` | Sandbox name | +| `OPENSHELL_SSH_SOCKET_PATH` | Unix socket path used by the supervisor's embedded SSH daemon | +| `OPENSHELL_SANDBOX_COMMAND` | `sleep infinity` | +| `OPENSHELL_TLS_CA` | Mounted CA path when HTTPS is enabled | +| `OPENSHELL_TLS_CERT` | Mounted client cert path when HTTPS is enabled | +| `OPENSHELL_TLS_KEY` | Mounted client key path when HTTPS is enabled | + +The Docker driver does not inject `OPENSHELL_SSH_HANDSHAKE_SECRET`; the +supervisor-to-gateway path relies on mTLS for the Docker callback. diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 8d59cb79b6..cf41909753 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -140,6 +140,15 @@ pub struct Config { #[serde(default)] pub metrics_bind_address: Option, + /// Additional bind addresses that serve the same multiplexed gRPC/HTTP + /// surface as `bind_address`. + /// + /// Compute drivers may register extra listeners during startup so that + /// sandbox workloads can call back into the gateway over an interface + /// that the operator-supplied `bind_address` does not expose. + #[serde(default)] + pub extra_bind_addresses: Vec, + /// Log level (trace, debug, info, warn, error). #[serde(default = "default_log_level")] pub log_level: String, @@ -327,6 +336,7 @@ impl Config { bind_address: default_bind_address(), health_bind_address: None, metrics_bind_address: None, + extra_bind_addresses: Vec::new(), log_level: default_log_level(), tls, oidc: None, @@ -368,6 +378,19 @@ impl Config { self } + /// Append an extra listener address to the multiplex service. + /// + /// Duplicate entries (matching `bind_address` or any existing entry) are + /// silently dropped so callers can naively push driver-derived addresses + /// without checking for collisions. + #[must_use] + pub fn with_extra_bind_address(mut self, addr: SocketAddr) -> Self { + if addr != self.bind_address && !self.extra_bind_addresses.contains(&addr) { + self.extra_bind_addresses.push(addr); + } + self + } + /// Create a new configuration with the given log level. #[must_use] pub fn with_log_level(mut self, level: impl Into) -> Self { diff --git a/crates/openshell-driver-docker/Cargo.toml b/crates/openshell-driver-docker/Cargo.toml index 8e2fd17777..ee917b78d7 100644 --- a/crates/openshell-driver-docker/Cargo.toml +++ b/crates/openshell-driver-docker/Cargo.toml @@ -19,7 +19,6 @@ futures = { workspace = true } tokio-stream = { workspace = true } tracing = { workspace = true } bytes = { workspace = true } -url = { workspace = true } bollard = { version = "0.20" } tar = "0.4" tempfile = "3" diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index 870a51ca6c..8b8df5b896 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -38,7 +38,6 @@ use tokio::sync::{broadcast, mpsc}; use tokio_stream::wrappers::ReceiverStream; use tonic::{Request, Response, Status}; use tracing::{info, warn}; -use url::{Host, Url}; const WATCH_BUFFER: usize = 128; const WATCH_POLL_INTERVAL: Duration = Duration::from_secs(2); @@ -55,8 +54,7 @@ const TLS_CA_MOUNT_PATH: &str = "/etc/openshell/tls/client/ca.crt"; const TLS_CERT_MOUNT_PATH: &str = "/etc/openshell/tls/client/tls.crt"; const TLS_KEY_MOUNT_PATH: &str = "/etc/openshell/tls/client/tls.key"; const SANDBOX_COMMAND: &str = "sleep infinity"; -const HOST_OPENSHELL_INTERNAL: &str = "host.openshell.internal"; -const HOST_DOCKER_INTERNAL: &str = "host.docker.internal"; +const HOST_OPENSHELL_INTERNAL_HOSTS_ENTRY: &str = "host.openshell.internal:127.0.0.1"; /// Default image holding the Linux `openshell-sandbox` binary. The gateway /// pulls this image and extracts the binary to a host-side cache when no @@ -852,7 +850,7 @@ fn build_environment(sandbox: &DriverSandbox, config: &DockerDriverRuntimeConfig environment.insert( "OPENSHELL_ENDPOINT".to_string(), - container_visible_openshell_endpoint(&config.grpc_endpoint), + config.grpc_endpoint.clone(), ); environment.insert("OPENSHELL_SANDBOX_ID".to_string(), sandbox.id.clone()); environment.insert("OPENSHELL_SANDBOX".to_string(), sandbox.name.clone()); @@ -950,17 +948,27 @@ fn build_container_create_body( "SYS_PTRACE".to_string(), "SYSLOG".to_string(), ]), - // AppArmor's default Docker profile blocks mount(2) with MS_SHARED - // even when SYS_ADMIN is granted, which prevents ip-netns from - // creating network namespaces for proxy-mode isolation. The sandbox - // enforces its own isolation via seccomp, Landlock, and network - // namespaces, so the host AppArmor profile adds no meaningful - // defence here. + // The sandbox supervisor needs to bind-mount `/run/netns`, + // mark it shared, and create per-process network namespaces. + // Docker's default AppArmor profile (`docker-default`) denies + // these mount operations even with CAP_SYS_ADMIN, so we opt + // out of AppArmor confinement for sandbox containers. The + // sandbox enforces its own security boundary via Landlock, + // seccomp, OPA policy evaluation, and the dedicated network + // namespace it sets up for the agent — AppArmor at the + // container layer is redundant relative to those controls + // and conflicts with them in this case. security_opt: Some(vec!["apparmor=unconfined".to_string()]), - extra_hosts: Some(vec![ - format!("{HOST_DOCKER_INTERNAL}:host-gateway"), - format!("{HOST_OPENSHELL_INTERNAL}:host-gateway"), - ]), + // Run in the host network namespace so a gateway bound to + // 127.0.0.1 is reachable from the supervisor as 127.0.0.1. + // The supervisor still creates a nested network namespace for + // the sandboxed workload and forces workload traffic through + // its policy proxy. + network_mode: Some("host".to_string()), + // Keep a stable host alias available inside the container without + // requiring users to edit the host's /etc/hosts. In host network + // mode this resolves back to the host loopback gateway. + extra_hosts: Some(vec![HOST_OPENSHELL_INTERNAL_HOSTS_ENTRY.to_string()]), ..Default::default() }), ..Default::default() @@ -991,25 +999,6 @@ fn sandbox_log_level(sandbox: &DriverSandbox, default_level: &str) -> String { .to_string() } -fn container_visible_openshell_endpoint(endpoint: &str) -> String { - let Ok(mut url) = Url::parse(endpoint) else { - return endpoint.to_string(); - }; - - let should_rewrite = match url.host() { - Some(Host::Ipv4(ip)) => ip.is_loopback() || ip.is_unspecified(), - Some(Host::Ipv6(ip)) => ip.is_loopback() || ip.is_unspecified(), - Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), - None => false, - }; - - if should_rewrite && url.set_host(Some(HOST_OPENSHELL_INTERNAL)).is_ok() { - return url.to_string(); - } - - endpoint.to_string() -} - fn docker_resource_limits( template: &DriverSandboxTemplate, ) -> Result { diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index 16dc3f733f..b016b31eb6 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -57,19 +57,16 @@ fn runtime_config() -> DockerDriverRuntimeConfig { } #[test] -fn container_visible_endpoint_rewrites_loopback_hosts() { - assert_eq!( - container_visible_openshell_endpoint("https://localhost:8443"), - "https://host.openshell.internal:8443/" - ); - assert_eq!( - container_visible_openshell_endpoint("http://127.0.0.1:8080"), - "http://host.openshell.internal:8080/" - ); - assert_eq!( - container_visible_openshell_endpoint("https://gateway.internal:8443"), - "https://gateway.internal:8443" - ); +fn build_environment_preserves_loopback_endpoint_for_host_network() { + let mut config = runtime_config(); + config.grpc_endpoint = "http://127.0.0.1:8080".to_string(); + + let env = build_environment(&test_sandbox(), &config); + assert!(env.contains(&"OPENSHELL_ENDPOINT=http://127.0.0.1:8080".to_string())); + + config.grpc_endpoint = "https://localhost:8443".to_string(); + let env = build_environment(&test_sandbox(), &config); + assert!(env.contains(&"OPENSHELL_ENDPOINT=https://localhost:8443".to_string())); } #[test] @@ -231,6 +228,23 @@ fn require_sandbox_identifier_rejects_when_id_and_name_are_empty() { require_sandbox_identifier("sbx-1", "demo").expect("id and name is accepted"); } +#[test] +fn build_container_create_body_uses_host_network() { + let create_body = build_container_create_body(&test_sandbox(), &runtime_config()).unwrap(); + let host_config = create_body.host_config.expect("host_config is populated"); + + assert_eq!( + host_config.network_mode, + Some("host".to_string()), + "sandbox must use host networking so 127.0.0.1 reaches the host gateway" + ); + assert_eq!( + host_config.extra_hosts, + Some(vec!["host.openshell.internal:127.0.0.1".to_string()]), + "sandbox should expose a stable host alias without host /etc/hosts edits" + ); +} + #[test] fn build_container_create_body_uses_runtime_namespace_label() { // Regression test: the namespace label must come from the driver's diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 2a18e209a2..f37ba472f1 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -40,9 +40,11 @@ use metrics_exporter_prometheus::PrometheusBuilder; use openshell_core::{ComputeDriverKind, Config, Error, Result}; use std::collections::HashMap; use std::io::ErrorKind; +use std::net::SocketAddr; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::net::TcpListener; +use tokio::sync::broadcast; use tracing::{debug, error, info, warn}; use compute::{ComputeRuntime, DockerComputeConfig, VmComputeConfig}; @@ -214,12 +216,24 @@ pub async fn run_server( // Create the multiplexed service let service = MultiplexService::new(state.clone()); - // Bind the TCP listener - let listener = TcpListener::bind(config.bind_address) + // Bind the primary TCP listener plus any extras requested by drivers. + // The same multiplex service is served on each address so the CLI on + // loopback and sandboxes on a driver-supplied interface can both reach + // the gateway with identical semantics. + let mut listeners: Vec<(SocketAddr, TcpListener)> = Vec::new(); + let primary_listener = TcpListener::bind(config.bind_address) .await .map_err(|e| Error::transport(format!("failed to bind to {}: {e}", config.bind_address)))?; - info!(address = %config.bind_address, "Server listening"); + listeners.push((config.bind_address, primary_listener)); + + for extra in &config.extra_bind_addresses { + let extra_listener = TcpListener::bind(*extra) + .await + .map_err(|e| Error::transport(format!("failed to bind extra address {extra}: {e}")))?; + info!(address = %extra, "Server listening on extra address"); + listeners.push((*extra, extra_listener)); + } // Bind the unauthenticated health endpoint on a separate port when configured. if let Some(health_bind_address) = config.health_bind_address { @@ -277,21 +291,59 @@ pub async fn run_server( None }; - let shutdown = shutdown_signal(); - tokio::pin!(shutdown); + // Coordinate graceful shutdown across every listener: a single broadcast + // channel notifies all accept loops, and a `JoinSet` lets us wait for + // them to drain before returning. + let (shutdown_tx, _) = broadcast::channel::<()>(1); + let mut accept_tasks = tokio::task::JoinSet::new(); + for (addr, listener) in listeners { + let service = service.clone(); + let tls_acceptor = tls_acceptor.clone(); + let mut shutdown_rx = shutdown_tx.subscribe(); + accept_tasks.spawn(async move { + run_accept_loop(addr, listener, service, tls_acceptor, &mut shutdown_rx).await; + }); + } + + shutdown_signal().await; + info!("Shutdown signal received; stopping gateway"); + let _ = shutdown_tx.send(()); + while accept_tasks.join_next().await.is_some() {} + + state + .compute + .cleanup_on_shutdown() + .await + .map_err(|err| Error::execution(format!("gateway shutdown cleanup failed: {err}")))?; + + Ok(()) +} - // Accept connections until the gateway receives a graceful shutdown signal. +/// Drive a single listener until either the listener errors fatally or the +/// gateway receives a shutdown signal. +/// +/// All listeners share the same `MultiplexService` and (optional) TLS +/// acceptor, so callers can run multiple instances of this loop in parallel +/// to expose the gateway on more than one bind address without forking the +/// service definition. +async fn run_accept_loop( + bind_addr: SocketAddr, + listener: TcpListener, + service: MultiplexService, + tls_acceptor: Option, + shutdown_rx: &mut broadcast::Receiver<()>, +) { loop { let (stream, addr) = tokio::select! { - () = &mut shutdown => { - info!("Shutdown signal received; stopping gateway"); - break; + _ = shutdown_rx.recv() => { + debug!(bind = %bind_addr, "Listener received shutdown"); + return; } accepted = listener.accept() => { match accepted { Ok(conn) => conn, Err(e) => { - error!(error = %e, "Failed to accept connection"); + error!(error = %e, bind = %bind_addr, "Failed to accept connection"); continue; } } @@ -326,14 +378,6 @@ pub async fn run_server( }); } } - - state - .compute - .cleanup_on_shutdown() - .await - .map_err(|err| Error::execution(format!("gateway shutdown cleanup failed: {err}")))?; - - Ok(()) } async fn shutdown_signal() { From 230824e74ac37774fd0cb82028cf6c53384e067b Mon Sep 17 00:00:00 2001 From: Drew Newberry Date: Fri, 1 May 2026 08:34:00 -0700 Subject: [PATCH 4/9] fix(install): refresh dev gateway registration (#1110) --- install-dev.sh | 47 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/install-dev.sh b/install-dev.sh index f1f8501263..dc0666cd6d 100755 --- a/install-dev.sh +++ b/install-dev.sh @@ -205,21 +205,58 @@ install_deb_package() { } start_user_gateway() { - info "starting openshell-gateway user service as ${TARGET_USER}..." + info "restarting openshell-gateway user service as ${TARGET_USER}..." if ! as_target_user systemctl --user daemon-reload; then info "could not reach the user systemd manager for ${TARGET_USER}" - info "start the gateway later with: systemctl --user enable --now openshell-gateway" + info "restart the gateway later with: systemctl --user enable openshell-gateway && systemctl --user restart openshell-gateway" info "then register it with: openshell gateway add http://127.0.0.1:17670 --local --name local" return 0 fi - as_target_user systemctl --user enable --now openshell-gateway + as_target_user systemctl --user enable openshell-gateway + as_target_user systemctl --user restart openshell-gateway as_target_user systemctl --user is-active --quiet openshell-gateway info "registering local gateway as ${TARGET_USER}..." - as_target_user openshell gateway add http://127.0.0.1:17670 --local --name local \ - || as_target_user openshell gateway select local + register_local_gateway +} + +remove_local_gateway_registration() { + [ -n "$TARGET_HOME" ] || error "cannot resolve home directory for ${TARGET_USER}" + _config_dir="${TARGET_HOME}/.config/openshell" + + # The install-dev gateway is a user service. Replace the CLI registration + # directly instead of asking `gateway destroy` to tear down Docker resources. + as_target_user sh -c ' + config_dir=$1 + rm -rf "${config_dir}/gateways/local" + active="${config_dir}/active_gateway" + if [ "$(cat "$active" 2>/dev/null || true)" = "local" ]; then + rm -f "$active" + fi + ' sh "$_config_dir" +} + +register_local_gateway() { + if _add_output="$(as_target_user openshell gateway add http://127.0.0.1:17670 --local --name local 2>&1)"; then + [ -z "$_add_output" ] || printf '%s\n' "$_add_output" >&2 + return 0 + else + _add_status=$? + fi + + case "$_add_output" in + *"already exists"*) + info "local gateway already exists; removing and re-adding it..." + remove_local_gateway_registration + as_target_user openshell gateway add http://127.0.0.1:17670 --local --name local + ;; + *) + printf '%s\n' "$_add_output" >&2 + return "$_add_status" + ;; + esac } main() { From 8e28209587e927700e54cca38dda7b64fc0ec855 Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Fri, 1 May 2026 09:09:30 -0700 Subject: [PATCH 5/9] chore(ci): label maintainer issues by repo permission (#1116) Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --- .github/workflows/issue-triage.yml | 31 +++++++++++------------------- CONTRIBUTING.md | 2 +- 2 files changed, 12 insertions(+), 21 deletions(-) diff --git a/.github/workflows/issue-triage.yml b/.github/workflows/issue-triage.yml index d5488cd41c..122fab3551 100644 --- a/.github/workflows/issue-triage.yml +++ b/.github/workflows/issue-triage.yml @@ -8,43 +8,34 @@ permissions: issues: write jobs: - label-mon-maintainer-issues: + label-maintainer-issues: runs-on: ubuntu-latest if: github.repository_owner == 'NVIDIA' - env: - ORG_READ_TOKEN: ${{ secrets.ORG_READ_TOKEN }} steps: - - name: Require org read token - if: env.ORG_READ_TOKEN == '' - run: | - echo "::error::ORG_READ_TOKEN is required to check mon-maintainers membership." - exit 1 - - - name: Check mon-maintainers membership - id: mon-maintainer + - name: Check maintainer permissions + id: maintainer uses: actions/github-script@v7 with: - github-token: ${{ secrets.ORG_READ_TOKEN }} result-encoding: string script: | const author = context.payload.issue.user.login; try { - const { data } = await github.rest.teams.getMembershipForUserInOrg({ - org: context.repo.owner, - team_slug: 'mon-maintainers', + const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, username: author, }); - if (data.state === 'active') { - console.log(`${author} is an active mon-maintainers member.`); + if (['admin', 'maintain', 'write'].includes(data.permission)) { + console.log(`${author} has maintainer permissions: ${data.permission}.`); return 'true'; } - console.log(`${author} has mon-maintainers membership state: ${data.state}`); + console.log(`${author} does not have maintainer permissions: ${data.permission}.`); } catch (e) { if (e.status === 404) { - console.log(`${author} is not a mon-maintainers member.`); + console.log(`${author} is not a repository collaborator.`); return 'false'; } @@ -54,7 +45,7 @@ jobs: return 'false'; - name: Add triage label - if: steps.mon-maintainer.outputs.result == 'true' + if: steps.maintainer.outputs.result == 'true' uses: actions/github-script@v7 with: script: | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 64d9b1c772..540e48b8cc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,7 +92,7 @@ Skills connect into pipelines. Individual skill files don't describe these relat - **Policy iteration:** `openshell-cli` → `generate-sandbox-policy` Workflow state labels use the `state:*` prefix, and security work uses `topic:security`. GitHub issue templates assign built-in issue types where applicable, and agent-created issues should use issue types or manual follow-up rather than type labels. -New issues opened by members of the `mon-maintainers` GitHub team are automatically labeled `state:triage-needed` by the issue triage workflow. +New issues opened by repository collaborators with `write`, `maintain`, or `admin` permission are automatically labeled `state:triage-needed` by the issue triage workflow. ## Prerequisites From 55f0e37127426c3cf6a2cf154062ba497e4aa13e Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Fri, 1 May 2026 11:08:56 -0700 Subject: [PATCH 6/9] chore(ci): label non-maintainer issues for triage (#1120) Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --- .github/workflows/issue-triage.yml | 60 ++++++------------------------ CONTRIBUTING.md | 2 +- 2 files changed, 12 insertions(+), 50 deletions(-) diff --git a/.github/workflows/issue-triage.yml b/.github/workflows/issue-triage.yml index 122fab3551..2549172596 100644 --- a/.github/workflows/issue-triage.yml +++ b/.github/workflows/issue-triage.yml @@ -8,17 +8,18 @@ permissions: issues: write jobs: - label-maintainer-issues: + label-non-maintainer-issues: runs-on: ubuntu-latest if: github.repository_owner == 'NVIDIA' steps: - - name: Check maintainer permissions - id: maintainer + - name: Check contributor permissions + id: contributor uses: actions/github-script@v7 with: result-encoding: string script: | const author = context.payload.issue.user.login; + const maintainerPermissions = ['admin', 'maintain', 'write']; try { const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ @@ -27,25 +28,24 @@ jobs: username: author, }); - if (['admin', 'maintain', 'write'].includes(data.permission)) { + if (maintainerPermissions.includes(data.permission)) { console.log(`${author} has maintainer permissions: ${data.permission}.`); - return 'true'; + return 'false'; } - console.log(`${author} does not have maintainer permissions: ${data.permission}.`); + console.log(`${author} is not a maintainer; permission is ${data.permission}.`); + return 'true'; } catch (e) { if (e.status === 404) { - console.log(`${author} is not a repository collaborator.`); - return 'false'; + console.log(`${author} is not a repository collaborator; labeling for triage.`); + return 'true'; } throw e; } - return 'false'; - - name: Add triage label - if: steps.maintainer.outputs.result == 'true' + if: steps.contributor.outputs.result == 'true' uses: actions/github-script@v7 with: script: | @@ -55,41 +55,3 @@ jobs: issue_number: context.issue.number, labels: ['state:triage-needed'], }); - - check-agent-diagnostic: - runs-on: ubuntu-latest - # Only run on bug reports (title starts with "bug:") - if: startsWith(github.event.issue.title, 'bug:') - steps: - - name: Check for agent diagnostic section - uses: actions/github-script@v7 - with: - script: | - const body = context.payload.issue.body || ''; - - // Check if the Agent Diagnostic section has substantive content. - // GitHub issue forms render textarea labels as h3 headings, but - // issues created through gh or API clients often use h2 headings. - const diagnosticMatch = body.match( - /^#{2,4}\s+Agent Diagnostic[s]?\s*\n([\s\S]*?)(?=\n#{2,4}\s+|$)/im - ); - - const diagnosticText = diagnosticMatch?.[1].trim() || ''; - const hasSubstantiveDiagnostic = diagnosticText.length > 0 - && !diagnosticText.toLowerCase().startsWith('example:') - && !['n/a', 'none', 'no', 'not applicable'].includes(diagnosticText.toLowerCase()); - - if (hasSubstantiveDiagnostic) { - console.log('Agent diagnostic section found with content. Passing.'); - return; - } - - console.log('Agent diagnostic section missing or placeholder. Flagging.'); - - // Add state:triage-needed label - await github.rest.issues.addLabels({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - labels: ['state:triage-needed'] - }); diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 540e48b8cc..fc5ad6c803 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,7 +92,7 @@ Skills connect into pipelines. Individual skill files don't describe these relat - **Policy iteration:** `openshell-cli` → `generate-sandbox-policy` Workflow state labels use the `state:*` prefix, and security work uses `topic:security`. GitHub issue templates assign built-in issue types where applicable, and agent-created issues should use issue types or manual follow-up rather than type labels. -New issues opened by repository collaborators with `write`, `maintain`, or `admin` permission are automatically labeled `state:triage-needed` by the issue triage workflow. +New issues opened by users without `write`, `maintain`, or `admin` repository permission are automatically labeled `state:triage-needed` by the issue triage workflow. ## Prerequisites From a3aed62cb271e599c2cab4e84f8ac0fc03cec57a Mon Sep 17 00:00:00 2001 From: ddurst-nvidia <267424412+ddurst-nvidia@users.noreply.github.com> Date: Fri, 1 May 2026 12:04:55 -0700 Subject: [PATCH 7/9] chore(openshell-core): discover proto files in build script (#1122) Walk ../../proto recursively instead of maintaining a hard-coded list. Sort paths for deterministic codegen and keep cargo:rerun-if-changed scoped to the proto tree. Signed-off-by: ddurst <267424412+ddurst-nvidia@users.noreply.github.com> --- crates/openshell-core/build.rs | 36 ++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/crates/openshell-core/build.rs b/crates/openshell-core/build.rs index e57de44654..7613c8754b 100644 --- a/crates/openshell-core/build.rs +++ b/crates/openshell-core/build.rs @@ -2,6 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 use std::env; +use std::path::{Path, PathBuf}; + +const PROTO_REL: &str = "../../proto"; fn main() -> Result<(), Box> { // --- Git-derived version --- @@ -17,6 +20,8 @@ fn main() -> Result<(), Box> { } // --- Protobuf compilation --- + // Re-run when anything under proto/ changes (including newly added .proto files). + println!("cargo:rerun-if-changed={PROTO_REL}"); // Use bundled protoc from protobuf-src. The system protoc (from apt-get) // does not bundle the well-known type includes (google/protobuf/struct.proto // etc.), so we must use protobuf-src which ships both the binary and the @@ -28,26 +33,31 @@ fn main() -> Result<(), Box> { env::set_var("PROTOC", protobuf_src::protoc()); } - let proto_files = [ - "../../proto/openshell.proto", - "../../proto/datamodel.proto", - "../../proto/sandbox.proto", - "../../proto/compute_driver.proto", - "../../proto/inference.proto", - "../../proto/test.proto", - ]; + let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR")?); + let proto_root = manifest_dir.join(PROTO_REL); + + let mut proto_files = Vec::new(); + collect_proto_files(&proto_root, &mut proto_files)?; + proto_files.sort(); // Configure tonic-build tonic_build::configure() .build_server(true) .build_client(true) - .compile_protos(&proto_files, &["../../proto"])?; + .compile_protos(&proto_files, &[proto_root.as_path()])?; - // Tell cargo to rerun if the proto file changes - for proto_file in proto_files { - println!("cargo:rerun-if-changed={proto_file}"); - } + Ok(()) +} +fn collect_proto_files(dir: &Path, out: &mut Vec) -> std::io::Result<()> { + for entry in std::fs::read_dir(dir)? { + let path = entry?.path(); + if path.is_dir() { + collect_proto_files(&path, out)?; + } else if path.extension().is_some_and(|ext| ext == "proto") { + out.push(path); + } + } Ok(()) } From 4c2564892b3b76ae344449a85037791634d5ab8e Mon Sep 17 00:00:00 2001 From: ddurst-nvidia <267424412+ddurst-nvidia@users.noreply.github.com> Date: Fri, 1 May 2026 13:01:10 -0700 Subject: [PATCH 8/9] fix(sandbox): accept ENOENT in drop_privileges identity lookup tests (#1123) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User::from_name / Group::from_name may return Ok(None), producing our explicit "Sandbox … not found" errors, or Err when NSS fails first with ENOENT ("ENOENT: No such file or directory") before a definitive unknown-name result. Accept either wording so nonexistent user/group tests stay meaningful across environments. Signed-off-by: ddurst <267424412+ddurst-nvidia@users.noreply.github.com> --- crates/openshell-sandbox/src/process.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index d13a99a45f..0dc5138366 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -614,6 +614,17 @@ mod tests { } } + /// Unknown names may yield `Ok(None)` (`… not found …`) or `Err` when NSS fails first + /// (e.g. `ENOENT: No such file or directory`). + fn assert_unknown_identity_lookup_failed(msg: &str) { + assert!( + msg.contains("not found") + || msg.contains("ENOENT") + || msg.contains("No such file or directory"), + "expected unknown user/group lookup failure (…not found… or ENOENT): {msg}" + ); + } + #[test] fn drop_privileges_noop_when_no_user_or_group() { let policy = policy_with_process(ProcessPolicy { @@ -696,10 +707,7 @@ mod tests { let result = drop_privileges(&policy); assert!(result.is_err()); let msg = format!("{}", result.unwrap_err()); - assert!( - msg.contains("not found"), - "expected 'not found' in error: {msg}" - ); + assert_unknown_identity_lookup_failed(&msg); } #[test] @@ -712,10 +720,7 @@ mod tests { let result = drop_privileges(&policy); assert!(result.is_err()); let msg = format!("{}", result.unwrap_err()); - assert!( - msg.contains("not found"), - "expected 'not found' in error: {msg}" - ); + assert_unknown_identity_lookup_failed(&msg); } #[cfg(unix)] From 5d0a44cbac58f47f62f2acedcc621dac7e8b0aed Mon Sep 17 00:00:00 2001 From: "John T. Myers" <9696606+johntmyers@users.noreply.github.com> Date: Fri, 1 May 2026 13:01:30 -0700 Subject: [PATCH 9/9] fix(sandbox): invalidate stale l7 tunnels after reload (#1118) Signed-off-by: John Myers <9696606+johntmyers@users.noreply.github.com> --- architecture/sandbox.md | 26 +- architecture/security-policy.md | 27 +- crates/openshell-sandbox/src/l7/relay.rs | 306 +++++++++++++++++- crates/openshell-sandbox/src/l7/rest.rs | 108 ++++++- crates/openshell-sandbox/src/opa.rs | 218 ++++++++++++- crates/openshell-sandbox/src/proxy.rs | 384 +++++++++++++++++++---- docs/sandboxes/policies.mdx | 4 +- 7 files changed, 960 insertions(+), 113 deletions(-) diff --git a/architecture/sandbox.md b/architecture/sandbox.md index cbb6b77f09..d5485fdc10 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -292,18 +292,22 @@ The proxy calls `evaluate_network_action()` (not `evaluate_network()`) as its ma ### L7 endpoint config query -After L4 allows a connection, `query_endpoint_config(input)` evaluates `data.openshell.sandbox.matched_endpoint_config` to get the full endpoint object. If the endpoint has a `protocol` field, `l7::parse_l7_config()` extracts the L7 config for protocol-aware inspection. +After L4 allows a connection, `query_endpoint_config_with_generation(input)` evaluates `data.openshell.sandbox.matched_endpoint_config` to get the full endpoint object and the policy generation used for the query. If the endpoint has a `protocol` field, `l7::parse_l7_config()` extracts the L7 config for protocol-aware inspection. ### Engine cloning for L7 -`clone_engine_for_tunnel()` clones the inner `regorus::Engine`. With the `arc` feature, this shares compiled policy via `Arc` and only duplicates interpreter state (microseconds). The cloned engine is wrapped in its own `std::sync::Mutex` and used by the L7 relay without contention on the main engine. +`clone_engine_for_tunnel(expected_generation)` clones the inner `regorus::Engine` only if the current policy generation still matches the endpoint config generation captured above. With the `arc` feature, this shares compiled policy via `Arc` and only duplicates interpreter state (microseconds). The cloned engine is wrapped in a generation-bound `TunnelPolicyEngine` and used by the L7 relay without contention on the main engine. + +The L7 relay checks the captured generation before parsing, evaluating, and forwarding each request. If a policy reload has advanced the shared generation, the relay closes the tunnel before forwarding more bytes. This applies live policy changes to the next L7 request on a keep-alive tunnel and avoids pairing stale endpoint config with a newer policy engine. HTTP passthrough tunnels without endpoint `protocol` are also generation-bound so credential-injection-only keep-alive tunnels close after a reload before forwarding another request. + +Raw streams are connection-scoped and outside the L7 live-reload guarantee. This includes `tls: skip`, binary/non-HTTP CONNECT tunnels, SQL audit fallback passthrough, HTTP upgrades such as WebSocket after `101 Switching Protocols`, and already-forwarded long-lived response bodies such as SSE. Policy reloads affect the next connection or the next parsed HTTP request; they do not interrupt raw byte streams that have already moved outside the request parser. ### Hot reload Two reload methods exist: - **`reload(policy, data_yaml)`**: Builds a new engine from raw Rego + YAML strings and atomically replaces the inner engine. Used in tests and by the file-mode path. -- **`reload_from_proto(proto)`**: Builds a new engine through the same validated pipeline as `from_proto()` -- proto-to-JSON conversion, L7 validation, access preset expansion -- then atomically swaps the inner `regorus::Engine`. On success, all subsequent `evaluate_network_action()` and `query_endpoint_config()` calls use the new policy. On failure (e.g., L7 validation errors), the previous engine is untouched (last-known-good behavior). This is the method used by the policy poll loop for live reloads in gRPC mode. +- **`reload_from_proto(proto)`**: Builds a new engine through the same validated pipeline as `from_proto()` -- proto-to-JSON conversion, L7 validation, access preset expansion -- then atomically swaps the inner `regorus::Engine`. On success, all subsequent `evaluate_network_action()` and `query_endpoint_config()` calls use the new policy, and the engine generation increments so active L7 tunnels close before forwarding another request under stale state. On failure (e.g., L7 validation errors), the previous engine and generation are untouched (last-known-good behavior). This is the method used by the policy poll loop for live reloads in gRPC mode. Both methods hold the `Mutex` only for the final swap (`*engine = new_engine`), so evaluation is blocked for only the duration of a pointer-sized assignment. @@ -962,7 +966,7 @@ flowchart TD After a CONNECT is allowed, the SSRF check passes, and the upstream TCP connection is established, the proxy determines how to handle the tunnel traffic. TLS detection is automatic — the proxy peeks the first bytes of the client stream to decide. -1. **Query L7 config**: `query_l7_config()` asks the OPA engine for `matched_endpoint_config`. If the endpoint has a `protocol` field, parse it into `L7EndpointConfig`. +1. **Query L7 route**: `query_l7_route_snapshot()` asks the OPA engine for `matched_endpoint_config` and the current policy generation. If the endpoint has a `protocol` field, parse it into a generation-bound `L7ConfigSnapshot`. If the endpoint has no `protocol`, retain the generation for HTTP passthrough keep-alive tunnels. 2. **Check for `tls: skip`**: If the endpoint has `tls: skip`, bypass all auto-detection and relay raw bytes via `copy_bidirectional()`. This is the escape hatch for client-cert mTLS or non-standard protocols. @@ -970,15 +974,15 @@ After a CONNECT is allowed, the SSRF check passes, and the upstream TCP connecti 4. **TLS detected** (`is_tls = true`): - Terminate TLS unconditionally via `tls_terminate_client()` + `tls_connect_upstream()`. This happens for all HTTPS endpoints, not just those with L7 config. - - If L7 config is present: clone the OPA engine (`clone_engine_for_tunnel()`), run `relay_with_inspection()` for per-request policy evaluation. - - If no L7 config: run `relay_passthrough_with_credentials()` — parses HTTP minimally to inject credentials (via `SecretResolver`) and log requests, but does not evaluate L7 OPA rules. This enables credential injection on all HTTPS endpoints without requiring `protocol` in the policy. + - If L7 config is present: clone the OPA engine for the captured generation (`clone_engine_for_tunnel(generation)`), run `relay_with_inspection()` for per-request policy evaluation. If the generation changed between config lookup and clone, close the tunnel before inspection. + - If no L7 config: run `relay_passthrough_with_credentials()` — parses HTTP minimally to inject credentials (via `SecretResolver`) and log requests, but does not evaluate L7 OPA rules. The passthrough relay is bound to the policy generation captured at connection setup and closes before forwarding another request after a reload. This enables credential injection on all HTTPS endpoints without requiring `protocol` in the policy. - If TLS state is not configured: fall back to raw `copy_bidirectional()` with a warning. 5. **Plaintext HTTP detected** (`is_http = true`, `is_tls = false`): - - If L7 config present: clone OPA engine, run `relay_with_inspection()` directly on the plaintext streams. - - If no L7 config: run `relay_passthrough_with_credentials()` for credential injection and observability. + - If L7 config present: clone the OPA engine for the captured generation, run `relay_with_inspection()` directly on the plaintext streams. + - If no L7 config: run `relay_passthrough_with_credentials()` for credential injection and observability, with the same per-request generation guard. -6. **Neither TLS nor HTTP**: Raw `copy_bidirectional()` tunnel (binary protocols, SSH-over-CONNECT, etc.). +6. **Neither TLS nor HTTP**: Raw `copy_bidirectional()` tunnel (binary protocols, SSH-over-CONNECT, etc.). These raw streams are connection-scoped and continue until either side closes; live policy reload does not interrupt them. ```mermaid flowchart TD @@ -1002,7 +1006,7 @@ flowchart TD **Files:** `crates/openshell-sandbox/src/l7/` -The L7 subsystem inspects application-layer traffic within CONNECT tunnels. Instead of raw `copy_bidirectional`, each request is parsed, evaluated against OPA rules, and either forwarded or blocked. +The L7 subsystem inspects application-layer traffic within CONNECT tunnels. Instead of raw `copy_bidirectional`, each request is parsed, evaluated against OPA rules, and either forwarded or blocked. The relay uses a generation-bound policy snapshot; after a successful policy reload, an existing L7 keep-alive tunnel closes before forwarding another request. Once an HTTP request has upgraded into a raw stream, or when a response body is a long-lived stream, that stream is connection-scoped and is not interrupted by L7 live reload. ### Architecture @@ -1245,6 +1249,8 @@ Implements `L7Provider` for HTTP/1.1: 6. If allowed (or audit mode): relay request to upstream via `relay_http_request_with_resolver()` (which rewrites all remaining credential placeholders in headers, query parameters, path segments, and Basic auth tokens) and relay the response back to client, then loop 7. If denied in enforce mode: send 403 (using redacted target in the response body) and close the connection +Before parsing, before evaluation, and before forwarding each request, the relay checks whether its captured policy generation still matches the shared engine generation. If not, it emits a denied OCSF network event and closes the tunnel without forwarding the request. + ## Process Identity ### SHA256 TOFU (Trust-On-First-Use) diff --git a/architecture/security-policy.md b/architecture/security-policy.md index aafee9987b..46ad727176 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -203,7 +203,7 @@ The poll loop: 2. Fetches the current policy via `GetSandboxSettings`, which returns the latest version, its policy payload, and a SHA-256 hash. 3. Compares the returned version against the locally tracked `current_version`. If the server version is not greater, the loop sleeps and retries. 4. On a new version, calls `OpaEngine::reload_from_proto()` which builds a complete new `regorus::Engine` through the same validated pipeline as the initial load (proto-to-JSON conversion, L7 validation, access preset expansion). -5. If the new engine builds successfully, it atomically replaces the inner `Mutex`. If it fails, the previous engine is untouched. +5. If the new engine builds successfully, it atomically replaces the inner `Mutex` and increments the policy generation. Active L7 keep-alive tunnels close before forwarding another request after they observe the new generation. If reload fails, the previous engine and generation are untouched. 6. Reports success or failure back to the server via `ReportPolicyStatus`. See `crates/openshell-sandbox/src/grpc_client.rs` -- `CachedOpenShellClient`. @@ -723,7 +723,11 @@ flowchart LR This is the single most important behavioral trigger in the policy language. An endpoint with no `protocol` field passes traffic opaquely after the L4 (CONNECT) check. Adding `protocol: rest` activates per-request HTTP parsing and policy evaluation inside the proxy. -**Implementation path**: After L4 CONNECT is allowed, the proxy calls `query_l7_config()` which evaluates the Rego rule `data.openshell.sandbox.matched_endpoint_config`. This rule only matches endpoints that have a `protocol` field set (see `sandbox-policy.rego` line `ep.protocol`). If a config is returned, the proxy enters `relay_with_inspection()` instead of `copy_bidirectional()`. See `crates/openshell-sandbox/src/proxy.rs` -- `handle_tcp_connection()`. +**Implementation path**: After L4 CONNECT is allowed, the proxy calls `query_l7_route_snapshot()` which evaluates the Rego rule `data.openshell.sandbox.matched_endpoint_config` and records the policy generation. If an endpoint `protocol` config is returned, the proxy enters `relay_with_inspection()` instead of `copy_bidirectional()`. See `crates/openshell-sandbox/src/proxy.rs` -- `handle_tcp_connection()`. + +For L7-inspected CONNECT tunnels, the proxy binds endpoint config and the per-tunnel policy engine clone to the policy generation observed at tunnel setup. If a live policy reload advances the generation, the relay closes the existing keep-alive tunnel before forwarding another request. HTTP passthrough tunnels without endpoint `protocol` use the same generation guard for parsed requests even though they do not evaluate L7 OPA rules. Clients should reconnect so the next request is evaluated under the current policy. + +Raw streams are connection-scoped and outside L7 live-reload guarantees. This includes endpoints with `tls: skip`, non-HTTP CONNECT payloads, SQL audit fallback passthrough, HTTP upgrades after `101 Switching Protocols`, and already-forwarded streaming response bodies such as SSE. A policy reload applies to the next connection or next parsed HTTP request; it does not terminate raw bytes already relayed outside the HTTP request parser. **Validation requirement**: When `protocol` is set, either `rules` or `access` must also be present. An endpoint with `protocol` but no rules/access is rejected at validation time because it would deny all traffic (no allow rules means nothing matches). See `crates/openshell-sandbox/src/l7/mod.rs` -- `validate_l7_policies()`. @@ -758,9 +762,9 @@ If any condition fails, the proxy returns `403 Forbidden`. 5. Resolves DNS and validates all IPs are private and within `allowed_ips` 6. Connects to upstream 7. Rewrites the request: absolute-form → origin-form (`GET /path HTTP/1.1`), strips hop-by-hop headers, adds `Via: 1.1 openshell-sandbox` and `Connection: close` -8. Forwards the rewritten request, then relays bidirectionally using `tokio::io::copy_bidirectional` (supports chunked transfer, SSE streams, and other long-lived responses with no idle timeout) +8. Relays the rewritten request and response through the shared guarded HTTP relay. This reuses the same request body framing, CL/TE rejection, credential rewrite fail-closed behavior, unsolicited `101` blocking, and policy-generation checks as CONNECT L7 HTTP. -**V1 simplifications**: Forward proxy v1 injects `Connection: close` (no keep-alive). Every forward proxy connection handles exactly one request-response exchange. When an endpoint has L7 rules configured, the forward proxy evaluates the single request's method and path against L7 policy before forwarding. +**V1 simplifications**: Forward proxy v1 injects `Connection: close` (no keep-alive). Every forward proxy connection handles exactly one request-response exchange. The request is bound to the policy generation used for the L4 allow decision and is checked again before upstream connect and request forwarding. When an endpoint has L7 rules configured, the forward proxy also evaluates the single request's method and path against L7 policy before forwarding. **Implementation**: See `crates/openshell-sandbox/src/proxy.rs` -- `handle_forward_proxy()`, `parse_proxy_uri()`, `rewrite_forward_request()`. @@ -785,7 +789,7 @@ flowchart TD K -- No --> L["403 Forbidden"] K -- Yes --> M["TCP connect to upstream"] M --> N["Rewrite request to origin-form
Add Via + Connection: close"] - N --> O["Forward request + copy_bidirectional"] + N --> O["Guarded HTTP relay"] ``` #### Example: Forward Proxy Policy @@ -836,7 +840,7 @@ TLS termination is automatic. The proxy peeks the first bytes of every CONNECT t **Certificate caching**: Per-hostname leaf certificates are cached (up to 256 entries, then the entire cache is cleared). See `crates/openshell-sandbox/src/l7/tls.rs` -- `CertCache`. -**Credential injection**: When TLS is auto-terminated but no L7 policy is configured (no `protocol` field), the proxy enters a passthrough relay that rewrites credential placeholders in HTTP headers (via `SecretResolver`) and logs requests for observability, but does not evaluate L7 OPA rules. This means credential injection works on all HTTPS endpoints automatically. +**Credential injection**: When TLS is auto-terminated but no L7 policy is configured (no `protocol` field), the proxy enters a passthrough relay that rewrites credential placeholders in HTTP headers (via `SecretResolver`) and logs requests for observability, but does not evaluate L7 OPA rules. The relay still closes parsed keep-alive HTTP tunnels after policy generation changes before forwarding another request. This means credential injection works on all HTTPS endpoints automatically. **Validation warnings**: @@ -972,9 +976,11 @@ sequenceDiagram OPA-->>Proxy: allowed=true, matched_policy="api_policy" Proxy-->>Client: 200 Connection Established - Note over Proxy: Query L7 config for matched endpoint - Proxy->>OPA: query_endpoint_config(host, port, binary) - OPA-->>Proxy: {protocol: rest, enforcement: enforce} + Note over Proxy: Query L7 config and generation for matched endpoint + Proxy->>OPA: query_endpoint_config_with_generation(host, port, binary) + OPA-->>Proxy: {protocol: rest, enforcement: enforce}, generation=N + Proxy->>OPA: clone_engine_for_tunnel(generation=N) + OPA-->>Proxy: generation-bound tunnel evaluator Note over Proxy: Auto-detect TLS (peek first bytes) Note over Proxy: TLS ClientHello detected → terminate @@ -988,9 +994,12 @@ sequenceDiagram loop Per HTTP request in tunnel Client->>Proxy: GET /repos/myorg/foo HTTP/1.1 + Note over Proxy: Close if policy generation changed Note over Proxy: Parse HTTP request line + headers + Note over Proxy: Close if policy generation changed Proxy->>OPA: allow_request(method=GET, path=/repos/myorg/foo) OPA-->>Proxy: allowed=true + Note over Proxy: Close if policy generation changed Proxy->>Upstream: GET /repos/myorg/foo HTTP/1.1 Upstream-->>Proxy: 200 OK (response body) Proxy-->>Client: 200 OK (response body) diff --git a/crates/openshell-sandbox/src/l7/relay.rs b/crates/openshell-sandbox/src/l7/relay.rs index 6a698ef375..c81ff0535b 100644 --- a/crates/openshell-sandbox/src/l7/relay.rs +++ b/crates/openshell-sandbox/src/l7/relay.rs @@ -9,13 +9,14 @@ use crate::l7::provider::{L7Provider, RelayOutcome}; use crate::l7::{EnforcementMode, L7EndpointConfig, L7Protocol, L7RequestInfo}; +use crate::opa::{PolicyGenerationGuard, TunnelPolicyEngine}; use crate::secrets::{self, SecretResolver}; use miette::{IntoDiagnostic, Result, miette}; use openshell_ocsf::{ ActionId, ActivityId, DispositionId, Endpoint, HttpActivityBuilder, HttpRequest, NetworkActivityBuilder, SeverityId, StatusId, Url as OcsfUrl, ocsf_emit, }; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt}; use tracing::{debug, warn}; @@ -90,7 +91,7 @@ fn emit_parse_rejection(ctx: &L7EvalContext, detail: &str, engine_type: &str) { /// caller peeks on the raw `TcpStream` before calling this. pub async fn relay_with_inspection( config: &L7EndpointConfig, - engine: Mutex, + engine: TunnelPolicyEngine, client: &mut C, upstream: &mut U, ctx: &L7EvalContext, @@ -102,6 +103,9 @@ where match config.protocol { L7Protocol::Rest => relay_rest(config, &engine, client, upstream, ctx).await, L7Protocol::Sql => { + if close_if_stale(engine.generation_guard(), ctx) { + return Ok(()); + } // SQL provider is Phase 3 — fall through to passthrough with warning { let event = NetworkActivityBuilder::new(crate::ocsf_ctx()) @@ -126,7 +130,7 @@ where /// switches to raw bidirectional TCP copy for the upgraded protocol (WebSocket, /// HTTP/2, etc.). L7 policy enforcement does not apply after the upgrade — /// the initial HTTP request was already evaluated. -async fn handle_upgrade( +pub(crate) async fn handle_upgrade( client: &mut C, upstream: &mut U, overflow: Vec, @@ -163,7 +167,7 @@ where /// REST relay loop: parse request -> evaluate -> allow/deny -> relay response -> repeat. async fn relay_rest( config: &L7EndpointConfig, - engine: &Mutex, + engine: &TunnelPolicyEngine, client: &mut C, upstream: &mut U, ctx: &L7EvalContext, @@ -181,6 +185,10 @@ where ..Default::default() }); loop { + if close_if_stale(engine.generation_guard(), ctx) { + return Ok(()); + } + // Parse one HTTP request from client let req = match provider.parse_request(client).await { Ok(Some(req)) => req, @@ -202,6 +210,10 @@ where } }; + if close_if_stale(engine.generation_guard(), ctx) { + return Ok(()); + } + // Rewrite credential placeholders in the request target BEFORE OPA // evaluation. OPA sees the redacted path; the resolved path goes only // to the upstream write. @@ -234,6 +246,10 @@ where // Evaluate L7 policy via Rego (using redacted target) let (allowed, reason) = evaluate_l7_request(engine, ctx, &request_info)?; + if close_if_stale(engine.generation_guard(), ctx) { + return Ok(()); + } + // Check if this is an upgrade request for logging purposes. let header_end = req .raw_header @@ -294,11 +310,12 @@ where if allowed || config.enforcement == EnforcementMode::Audit { // Forward request to upstream and relay response - let outcome = crate::l7::rest::relay_http_request_with_resolver( + let outcome = crate::l7::rest::relay_http_request_with_resolver_guarded( &req, client, upstream, ctx.secret_resolver.as_deref(), + Some(engine.generation_guard()), ) .await?; match outcome { @@ -331,6 +348,32 @@ where } } +fn close_if_stale(guard: &PolicyGenerationGuard, ctx: &L7EvalContext) -> bool { + if !guard.is_stale() { + return false; + } + + ocsf_emit!( + NetworkActivityBuilder::new(crate::ocsf_ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) + .firewall_rule(&ctx.policy_name, "l7") + .message(format!( + "L7 tunnel closed after policy reload [host:{} port:{} captured_generation:{} current_generation:{}]", + ctx.host, + ctx.port, + guard.captured_generation(), + guard.current_generation(), + )) + .build() + ); + true +} + /// Check if a miette error represents a benign connection close. /// /// TLS handshake EOF, missing `close_notify`, connection resets, and broken @@ -353,10 +396,18 @@ fn is_benign_connection_error(err: &miette::Report) -> bool { /// /// Returns `(allowed, deny_reason)`. pub fn evaluate_l7_request( - engine: &Mutex, + engine: &TunnelPolicyEngine, ctx: &L7EvalContext, request: &L7RequestInfo, ) -> Result<(bool, String)> { + if engine.is_stale() { + return Err(miette!( + "L7 tunnel policy generation is stale [captured_generation:{} current_generation:{}]", + engine.captured_generation(), + engine.current_generation(), + )); + } + let input_json = serde_json::json!({ "network": { "host": ctx.host, @@ -375,6 +426,7 @@ pub fn evaluate_l7_request( }); let mut engine = engine + .engine() .lock() .map_err(|_| miette!("OPA engine lock poisoned"))?; @@ -412,6 +464,7 @@ pub async fn relay_passthrough_with_credentials( client: &mut C, upstream: &mut U, ctx: &L7EvalContext, + generation_guard: &PolicyGenerationGuard, ) -> Result<()> where C: AsyncRead + AsyncWrite + Unpin + Send, @@ -426,6 +479,10 @@ where let resolver = ctx.secret_resolver.as_deref(); loop { + if close_if_stale(generation_guard, ctx) { + return Ok(()); + } + // Read next request from client. let req = match provider.parse_request(client).await { Ok(Some(req)) => req, @@ -441,6 +498,10 @@ where } }; + if close_if_stale(generation_guard, ctx) { + return Ok(()); + } + request_count += 1; // Resolve and redact the target for logging. @@ -489,9 +550,14 @@ where // Forward request with credential rewriting and relay the response. // relay_http_request_with_resolver handles both directions: it sends // the request upstream and reads the response back to the client. - let outcome = - crate::l7::rest::relay_http_request_with_resolver(&req, client, upstream, resolver) - .await?; + let outcome = crate::l7::rest::relay_http_request_with_resolver_guarded( + &req, + client, + upstream, + resolver, + Some(generation_guard), + ) + .await?; match outcome { RelayOutcome::Reusable => {} // continue loop @@ -515,6 +581,11 @@ where #[cfg(test)] mod tests { use super::*; + use crate::opa::{NetworkInput, OpaEngine}; + use std::path::PathBuf; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + const TEST_POLICY: &str = include_str!("../../data/sandbox-policy.rego"); #[test] fn parse_rejection_detail_adds_l7_hint_for_encoded_slash() { @@ -548,4 +619,221 @@ mod tests { error ); } + + #[tokio::test] + async fn l7_relay_closes_keep_alive_tunnel_after_policy_generation_change() { + let initial_data = r#" +network_policies: + rest_api: + name: rest_api + endpoints: + - host: api.example.test + port: 8080 + protocol: rest + enforcement: enforce + rules: + - allow: + method: POST + path: "/write" + binaries: + - { path: /usr/bin/curl } +"#; + let reloaded_data = r#" +network_policies: + rest_api: + name: rest_api + endpoints: + - host: api.example.test + port: 8080 + protocol: rest + enforcement: enforce + rules: + - allow: + method: GET + path: "/write" + binaries: + - { path: /usr/bin/curl } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, initial_data).unwrap(); + let input = NetworkInput { + host: "api.example.test".into(), + port: 8080, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .unwrap(); + let config = crate::l7::parse_l7_config(&endpoint_config.unwrap()).unwrap(); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 8080, + policy_name: "rest_api".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + }; + + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all( + b"POST /write HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n", + ) + .await + .unwrap(); + + let mut first_upstream = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut first_upstream), + ) + .await + .expect("first request should reach upstream") + .unwrap(); + let first_upstream = String::from_utf8_lossy(&first_upstream[..n]); + assert!(first_upstream.starts_with("POST /write HTTP/1.1")); + + upstream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: keep-alive\r\n\r\nOK") + .await + .unwrap(); + + let mut first_response = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read(&mut first_response), + ) + .await + .expect("first response should reach client") + .unwrap(); + let first_response = String::from_utf8_lossy(&first_response[..n]); + assert!(first_response.contains("200 OK")); + + engine.reload(TEST_POLICY, reloaded_data).unwrap(); + app.write_all( + b"POST /write HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n", + ) + .await + .unwrap(); + + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should close stale tunnel") + .unwrap() + .unwrap(); + + let mut second_upstream = [0u8; 128]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut second_upstream), + ) + .await + .expect("upstream side should close") + .unwrap(); + assert_eq!(n, 0, "stale request must not be forwarded upstream"); + } + + #[tokio::test] + async fn passthrough_relay_closes_keep_alive_tunnel_after_policy_generation_change() { + let policy_data = "network_policies: {}\n"; + let engine = OpaEngine::from_strings(TEST_POLICY, policy_data).unwrap(); + let generation_guard = engine + .generation_guard(engine.current_generation()) + .unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 8080, + policy_name: "rest_api".into(), + binary_path: "/usr/bin/curl".into(), + ancestors: vec![], + cmdline_paths: vec![], + secret_resolver: None, + }; + + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_passthrough_with_credentials( + &mut relay_client, + &mut relay_upstream, + &ctx, + &generation_guard, + ) + .await + }); + + app.write_all( + b"GET /first HTTP/1.1\r\nHost: api.example.test\r\nConnection: keep-alive\r\n\r\n", + ) + .await + .unwrap(); + + let mut first_upstream = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut first_upstream), + ) + .await + .expect("first passthrough request should reach upstream") + .unwrap(); + let first_upstream = String::from_utf8_lossy(&first_upstream[..n]); + assert!(first_upstream.starts_with("GET /first HTTP/1.1")); + + upstream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: keep-alive\r\n\r\nOK") + .await + .unwrap(); + + let mut first_response = [0u8; 512]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read(&mut first_response), + ) + .await + .expect("first passthrough response should reach client") + .unwrap(); + let first_response = String::from_utf8_lossy(&first_response[..n]); + assert!(first_response.contains("200 OK")); + + engine.reload(TEST_POLICY, policy_data).unwrap(); + app.write_all( + b"GET /second HTTP/1.1\r\nHost: api.example.test\r\nConnection: keep-alive\r\n\r\n", + ) + .await + .unwrap(); + + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("passthrough relay should close stale tunnel") + .unwrap() + .unwrap(); + + let mut second_upstream = [0u8; 128]; + let n = tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read(&mut second_upstream), + ) + .await + .expect("upstream side should close") + .unwrap(); + assert_eq!( + n, 0, + "stale passthrough request must not be forwarded upstream" + ); + } } diff --git a/crates/openshell-sandbox/src/l7/rest.rs b/crates/openshell-sandbox/src/l7/rest.rs index 737190e2c8..47588a4167 100644 --- a/crates/openshell-sandbox/src/l7/rest.rs +++ b/crates/openshell-sandbox/src/l7/rest.rs @@ -8,6 +8,7 @@ //! and chunked transfer encoding for body framing. use crate::l7::provider::{BodyLength, L7Provider, L7Request, RelayOutcome}; +use crate::opa::PolicyGenerationGuard; use crate::secrets::rewrite_http_header_block; use miette::{IntoDiagnostic, Result, miette}; use std::collections::HashMap; @@ -336,6 +337,20 @@ pub(crate) async fn relay_http_request_with_resolver( upstream: &mut U, resolver: Option<&crate::secrets::SecretResolver>, ) -> Result +where + C: AsyncRead + AsyncWrite + Unpin, + U: AsyncRead + AsyncWrite + Unpin, +{ + relay_http_request_with_resolver_guarded(req, client, upstream, resolver, None).await +} + +pub(crate) async fn relay_http_request_with_resolver_guarded( + req: &L7Request, + client: &mut C, + upstream: &mut U, + resolver: Option<&crate::secrets::SecretResolver>, + generation_guard: Option<&PolicyGenerationGuard>, +) -> Result where C: AsyncRead + AsyncWrite + Unpin, U: AsyncRead + AsyncWrite + Unpin, @@ -349,6 +364,10 @@ where let rewrite_result = rewrite_http_header_block(&req.raw_header[..header_end], resolver) .map_err(|e| miette!("credential injection failed: {e}"))?; + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } + upstream .write_all(&rewrite_result.rewritten) .await @@ -356,6 +375,9 @@ where let overflow = &req.raw_header[header_end..]; if !overflow.is_empty() { + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } upstream.write_all(overflow).await.into_diagnostic()?; } let overflow_len = overflow.len() as u64; @@ -364,11 +386,17 @@ where BodyLength::ContentLength(len) => { let remaining = len.saturating_sub(overflow_len); if remaining > 0 { - relay_fixed(client, upstream, remaining).await?; + relay_fixed(client, upstream, remaining, generation_guard).await?; } } BodyLength::Chunked => { - relay_chunked(client, upstream, &req.raw_header[header_end..]).await?; + relay_chunked( + client, + upstream, + &req.raw_header[header_end..], + generation_guard, + ) + .await?; } BodyLength::None => {} } @@ -460,7 +488,7 @@ async fn send_deny_response( /// Per RFC 7230 Section 3.3.3, rejects requests containing both /// `Content-Length` and `Transfer-Encoding` headers to prevent request /// smuggling via CL/TE ambiguity. -fn parse_body_length(headers: &str) -> Result { +pub(crate) fn parse_body_length(headers: &str) -> Result { let mut has_te_chunked = false; let mut cl_value: Option = None; @@ -504,7 +532,12 @@ fn parse_body_length(headers: &str) -> Result { } /// Relay exactly `len` bytes from reader to writer. -async fn relay_fixed(reader: &mut R, writer: &mut W, len: u64) -> Result<()> +async fn relay_fixed( + reader: &mut R, + writer: &mut W, + len: u64, + generation_guard: Option<&PolicyGenerationGuard>, +) -> Result<()> where R: AsyncRead + Unpin, W: AsyncWrite + Unpin, @@ -521,6 +554,9 @@ where "Connection closed with {remaining} bytes remaining" )); } + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } writer.write_all(&buf[..n]).await.into_diagnostic()?; remaining -= n as u64; } @@ -536,7 +572,12 @@ where /// `already_forwarded` are overflow bytes that were already written to the /// writer during header parsing. They are seeded into the parser buffer so /// termination can still be detected when boundaries span reads. -async fn relay_chunked(reader: &mut R, writer: &mut W, already_forwarded: &[u8]) -> Result<()> +async fn relay_chunked( + reader: &mut R, + writer: &mut W, + already_forwarded: &[u8], + generation_guard: Option<&PolicyGenerationGuard>, +) -> Result<()> where R: AsyncRead + Unpin, W: AsyncWrite + Unpin, @@ -560,6 +601,9 @@ where if n == 0 { return Err(miette!("Chunked body ended before chunk-size line")); } + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } writer.write_all(&read_buf[..n]).await.into_diagnostic()?; parse_buf.extend_from_slice(&read_buf[..n]); }; @@ -589,6 +633,9 @@ where if n == 0 { return Err(miette!("Chunked body ended before trailer terminator")); } + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } writer.write_all(&read_buf[..n]).await.into_diagnostic()?; parse_buf.extend_from_slice(&read_buf[..n]); }; @@ -622,6 +669,9 @@ where if n == 0 { return Err(miette!("Chunked body ended mid-chunk")); } + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } writer.write_all(&read_buf[..n]).await.into_diagnostic()?; parse_buf.extend_from_slice(&read_buf[..n]); } @@ -794,11 +844,11 @@ where BodyLength::ContentLength(len) => { let remaining = len.saturating_sub(overflow_len); if remaining > 0 { - relay_fixed(upstream, client, remaining).await?; + relay_fixed(upstream, client, remaining, None).await?; } } BodyLength::Chunked => { - relay_chunked(upstream, client, &buf[header_end..]).await?; + relay_chunked(upstream, client, &buf[header_end..], None).await?; } BodyLength::None => unreachable!(), } @@ -945,9 +995,12 @@ fn is_benign_close(err: &std::io::Error) -> bool { )] mod tests { use super::*; + use crate::opa::OpaEngine; use crate::secrets::SecretResolver; use base64::Engine as _; + const TEST_POLICY: &str = include_str!("../../data/sandbox-policy.rego"); + #[test] fn parse_content_length() { let headers = "POST /api HTTP/1.1\r\nHost: example.com\r\nContent-Length: 42\r\n\r\n"; @@ -1969,6 +2022,47 @@ mod tests { upstream_task.await.expect("upstream task should complete"); } + #[tokio::test] + async fn relay_request_guard_blocks_stale_generation_before_upstream_write() { + let policy_data = "network_policies: {}\n"; + let engine = OpaEngine::from_strings(TEST_POLICY, policy_data).unwrap(); + let guard = engine + .generation_guard(engine.current_generation()) + .unwrap(); + engine.reload(TEST_POLICY, policy_data).unwrap(); + + let req = L7Request { + action: "GET".to_string(), + target: "/api".to_string(), + query_params: HashMap::new(), + raw_header: b"GET /api HTTP/1.1\r\nHost: example.com\r\n\r\n".to_vec(), + body_length: BodyLength::None, + }; + let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); + let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); + + let result = relay_http_request_with_resolver_guarded( + &req, + &mut proxy_to_client, + &mut proxy_to_upstream, + None, + Some(&guard), + ) + .await; + assert!( + result.is_err(), + "stale generation must stop relay before upstream write" + ); + + drop(proxy_to_upstream); + let mut forwarded = Vec::new(); + upstream_side.read_to_end(&mut forwarded).await.unwrap(); + assert!( + forwarded.is_empty(), + "stale request bytes must not reach upstream" + ); + } + #[test] fn client_requested_upgrade_detects_websocket_headers() { let headers = "GET /ws HTTP/1.1\r\nHost: example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n"; diff --git a/crates/openshell-sandbox/src/opa.rs b/crates/openshell-sandbox/src/opa.rs index 7153be9cf3..ac9a09a8b2 100644 --- a/crates/openshell-sandbox/src/opa.rs +++ b/crates/openshell-sandbox/src/opa.rs @@ -11,7 +11,10 @@ use crate::policy::{FilesystemPolicy, LandlockCompatibility, LandlockPolicy, Pro use miette::Result; use openshell_core::proto::SandboxPolicy as ProtoSandboxPolicy; use std::path::{Path, PathBuf}; -use std::sync::Mutex; +use std::sync::{ + Arc, Mutex, + atomic::{AtomicU64, Ordering}, +}; /// Baked-in rego rules for OPA policy evaluation. /// These rules define the network access decision logic and static config @@ -64,6 +67,68 @@ pub struct SandboxConfig { /// (one eval per CONNECT request). pub struct OpaEngine { engine: Mutex, + generation: Arc, +} + +/// Generation guard captured when an HTTP tunnel or request path starts. +#[derive(Clone)] +pub struct PolicyGenerationGuard { + captured_generation: u64, + current_generation: Arc, +} + +impl PolicyGenerationGuard { + pub fn captured_generation(&self) -> u64 { + self.captured_generation + } + + pub fn current_generation(&self) -> u64 { + self.current_generation.load(Ordering::Acquire) + } + + pub fn is_stale(&self) -> bool { + self.current_generation() != self.captured_generation + } + + pub fn ensure_current(&self) -> Result<()> { + if self.is_stale() { + return Err(miette::miette!( + "policy generation is stale [captured_generation:{} current_generation:{}]", + self.captured_generation(), + self.current_generation(), + )); + } + Ok(()) + } +} + +/// Per-tunnel L7 policy evaluator bound to the engine generation captured when +/// the tunnel was established. +pub struct TunnelPolicyEngine { + engine: Mutex, + generation_guard: PolicyGenerationGuard, +} + +impl TunnelPolicyEngine { + pub fn captured_generation(&self) -> u64 { + self.generation_guard.captured_generation() + } + + pub fn current_generation(&self) -> u64 { + self.generation_guard.current_generation() + } + + pub fn is_stale(&self) -> bool { + self.generation_guard.is_stale() + } + + pub fn generation_guard(&self) -> &PolicyGenerationGuard { + &self.generation_guard + } + + pub(crate) fn engine(&self) -> &Mutex { + &self.engine + } } impl OpaEngine { @@ -84,6 +149,7 @@ impl OpaEngine { .map_err(|e| miette::miette!("{e}"))?; Ok(Self { engine: Mutex::new(engine), + generation: Arc::new(AtomicU64::new(0)), }) } @@ -101,6 +167,7 @@ impl OpaEngine { .map_err(|e| miette::miette!("{e}"))?; Ok(Self { engine: Mutex::new(engine), + generation: Arc::new(AtomicU64::new(0)), }) } @@ -162,6 +229,7 @@ impl OpaEngine { .map_err(|e| miette::miette!("{e}"))?; Ok(Self { engine: Mutex::new(engine), + generation: Arc::new(AtomicU64::new(0)), }) } @@ -233,6 +301,14 @@ impl OpaEngine { /// Uses the OPA `network_action` rule which returns one of: /// `"allow"` or `"deny"`. pub fn evaluate_network_action(&self, input: &NetworkInput) -> Result { + Ok(self.evaluate_network_action_with_generation(input)?.0) + } + + /// Evaluate network action and return the policy generation used for the evaluation. + pub fn evaluate_network_action_with_generation( + &self, + input: &NetworkInput, + ) -> Result<(NetworkAction, u64)> { let ancestor_strs: Vec = input .ancestors .iter() @@ -259,6 +335,7 @@ impl OpaEngine { .engine .lock() .map_err(|_| miette::miette!("OPA engine lock poisoned"))?; + let generation = self.current_generation(); engine .set_input_json(&input_json.to_string()) @@ -279,13 +356,13 @@ impl OpaEngine { }; if action_str == "allow" { - Ok(NetworkAction::Allow { matched_policy }) + Ok((NetworkAction::Allow { matched_policy }, generation)) } else { let reason_val = engine .eval_rule("data.openshell.sandbox.deny_reason".into()) .map_err(|e| miette::miette!("{e}"))?; let reason = value_to_string(&reason_val); - Ok(NetworkAction::Deny { reason }) + Ok((NetworkAction::Deny { reason }, generation)) } } @@ -306,6 +383,7 @@ impl OpaEngine { .lock() .map_err(|_| miette::miette!("OPA engine lock poisoned"))?; *engine = new_engine; + self.generation.fetch_add(1, Ordering::AcqRel); Ok(()) } @@ -340,9 +418,29 @@ impl OpaEngine { .lock() .map_err(|_| miette::miette!("OPA engine lock poisoned"))?; *engine = new_engine; + self.generation.fetch_add(1, Ordering::AcqRel); Ok(()) } + /// Current policy generation. Successful reloads increment this value. + pub fn current_generation(&self) -> u64 { + self.generation.load(Ordering::Acquire) + } + + /// Return a guard for a previously captured policy generation. + pub fn generation_guard(&self, expected_generation: u64) -> Result { + let generation = self.current_generation(); + if generation != expected_generation { + return Err(miette::miette!( + "policy changed before HTTP relay started [expected_generation:{expected_generation} current_generation:{generation}]" + )); + } + Ok(PolicyGenerationGuard { + captured_generation: generation, + current_generation: Arc::clone(&self.generation), + }) + } + /// Query static sandbox configuration from the OPA data module. /// /// Extracts `filesystem_policy`, `landlock`, and `process` from the Rego @@ -385,6 +483,14 @@ impl OpaEngine { /// to get the full endpoint object for the matched policy. Returns the raw /// `regorus::Value` which can be parsed by `l7::parse_l7_config()`. pub fn query_endpoint_config(&self, input: &NetworkInput) -> Result> { + Ok(self.query_endpoint_config_with_generation(input)?.0) + } + + /// Query L7 endpoint config and return the policy generation used for the query. + pub fn query_endpoint_config_with_generation( + &self, + input: &NetworkInput, + ) -> Result<(Option, u64)> { let ancestor_strs: Vec = input .ancestors .iter() @@ -411,6 +517,7 @@ impl OpaEngine { .engine .lock() .map_err(|_| miette::miette!("OPA engine lock poisoned"))?; + let generation = self.current_generation(); engine .set_input_json(&input_json.to_string()) @@ -421,9 +528,9 @@ impl OpaEngine { .map_err(|e| miette::miette!("{e}"))?; if val == regorus::Value::Undefined { - Ok(None) + Ok((None, generation)) } else { - Ok(Some(val)) + Ok((Some(val), generation)) } } @@ -445,12 +552,24 @@ impl OpaEngine { /// With the `arc` feature enabled, this shares compiled policy via Arc /// and only duplicates interpreter state (~microseconds). The cloned /// engine can be used without Mutex contention. - pub fn clone_engine_for_tunnel(&self) -> Result { + pub fn clone_engine_for_tunnel(&self, expected_generation: u64) -> Result { let engine = self .engine .lock() .map_err(|_| miette::miette!("OPA engine lock poisoned"))?; - Ok(engine.clone()) + let generation = self.current_generation(); + if generation != expected_generation { + return Err(miette::miette!( + "policy changed before L7 tunnel started [expected_generation:{expected_generation} current_generation:{generation}]" + )); + } + Ok(TunnelPolicyEngine { + engine: Mutex::new(engine.clone()), + generation_guard: PolicyGenerationGuard { + captured_generation: generation, + current_generation: Arc::clone(&self.generation), + }, + }) } } @@ -2027,10 +2146,12 @@ process: #[test] fn l7_clone_engine_for_tunnel() { let engine = l7_engine(); - let cloned = engine.clone_engine_for_tunnel().unwrap(); + let cloned = engine + .clone_engine_for_tunnel(engine.current_generation()) + .unwrap(); // Verify the cloned engine can evaluate let input_json = l7_input("api.example.com", 8080, "GET", "/repos/myorg/foo"); - let mut eng = cloned; + let mut eng = cloned.engine().lock().unwrap(); eng.set_input_json(&input_json.to_string()).unwrap(); let val = eng .eval_rule("data.openshell.sandbox.allow_request".into()) @@ -2038,6 +2159,85 @@ process: assert_eq!(val, regorus::Value::from(true)); } + #[test] + fn policy_generation_starts_at_zero_and_increments_on_successful_reload() { + let engine = l7_engine(); + assert_eq!(engine.current_generation(), 0); + + engine.reload(TEST_POLICY, L7_TEST_DATA).unwrap(); + + assert_eq!(engine.current_generation(), 1); + } + + #[test] + fn policy_generation_does_not_increment_on_failed_reload() { + let engine = l7_engine(); + engine.reload(TEST_POLICY, L7_TEST_DATA).unwrap(); + assert_eq!(engine.current_generation(), 1); + + let invalid_l7_data = r#" +network_policies: + bad_api: + name: bad_api + endpoints: + - host: api.example.com + port: 8080 + protocol: invalid-protocol + binaries: + - { path: /usr/bin/curl } +"#; + assert!(engine.reload(TEST_POLICY, invalid_l7_data).is_err()); + assert_eq!(engine.current_generation(), 1); + + let input_json = l7_input("api.example.com", 8080, "GET", "/repos/myorg/foo"); + let cloned = engine + .clone_engine_for_tunnel(engine.current_generation()) + .unwrap(); + let mut eng = cloned.engine().lock().unwrap(); + eng.set_input_json(&input_json.to_string()).unwrap(); + let val = eng + .eval_rule("data.openshell.sandbox.allow_request".into()) + .unwrap(); + assert_eq!(val, regorus::Value::from(true)); + } + + #[test] + fn endpoint_config_generation_matches_query_generation() { + let engine = l7_engine(); + let input = NetworkInput { + host: "api.example.com".into(), + port: 8080, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + + let (config, generation) = engine + .query_endpoint_config_with_generation(&input) + .unwrap(); + assert!(config.is_some()); + assert_eq!(generation, engine.current_generation()); + + engine.reload(TEST_POLICY, L7_TEST_DATA).unwrap(); + + let (config, generation) = engine + .query_endpoint_config_with_generation(&input) + .unwrap(); + assert!(config.is_some()); + assert_eq!(generation, engine.current_generation()); + assert_eq!(generation, 1); + } + + #[test] + fn tunnel_clone_rejects_stale_generation() { + let engine = l7_engine(); + let captured_generation = engine.current_generation(); + engine.reload(TEST_POLICY, L7_TEST_DATA).unwrap(); + + assert!(engine.clone_engine_for_tunnel(captured_generation).is_err()); + } + // ======================================================================== // Deny rules tests // ======================================================================== diff --git a/crates/openshell-sandbox/src/proxy.rs b/crates/openshell-sandbox/src/proxy.rs index a4ad694a9c..6614ace3a9 100644 --- a/crates/openshell-sandbox/src/proxy.rs +++ b/crates/openshell-sandbox/src/proxy.rs @@ -6,7 +6,7 @@ use crate::denial_aggregator::DenialEvent; use crate::identity::BinaryIdentityCache; use crate::l7::tls::ProxyTlsState; -use crate::opa::{NetworkAction, OpaEngine}; +use crate::opa::{NetworkAction, OpaEngine, PolicyGenerationGuard}; use crate::policy::ProxyPolicy; use crate::secrets::{SecretResolver, rewrite_header_line}; use miette::{IntoDiagnostic, Result}; @@ -19,7 +19,9 @@ use std::net::{IpAddr, SocketAddr}; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicU32, Ordering}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::{ + AsyncRead as TokioAsyncRead, AsyncReadExt, AsyncWrite as TokioAsyncWrite, AsyncWriteExt, +}; use tokio::net::{TcpListener, TcpStream}; use tokio::sync::mpsc; use tokio::task::JoinHandle; @@ -42,6 +44,8 @@ const CHUNK_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1 /// Result of a proxy CONNECT policy decision. struct ConnectDecision { action: NetworkAction, + /// Policy generation used for the L4 network decision. + generation: u64, /// Resolved binary path. binary: Option, /// PID owning the socket. @@ -668,12 +672,16 @@ async fn handle_tcp_connection( respond(&mut client, b"HTTP/1.1 200 Connection Established\r\n\r\n").await?; - // Check if endpoint has L7 config for protocol-aware inspection - let l7_config = query_l7_config(&opa_engine, &decision, &host_lc, port); + // Check if endpoint has L7 config for protocol-aware inspection, and + // retain the generation for HTTP passthrough keep-alive tunnels. + let l7_route = query_l7_route_snapshot(&opa_engine, &decision, &host_lc, port); // Log the allowed CONNECT — use CONNECT_L7 when L7 inspection follows, // so log consumers can distinguish L4-only decisions from tunnel lifecycle events. - let connect_msg = if l7_config.is_some() { + let connect_msg = if l7_route + .as_ref() + .is_some_and(|route| route.config.is_some()) + { "CONNECT_L7" } else { "CONNECT" @@ -758,24 +766,19 @@ async fn handle_tcp_connection( crate::l7::tls::tls_connect_upstream(upstream, &host_lc, tls.upstream_config()) .await?; - if let Some(ref l7_config) = l7_config { + if let Some(l7_config) = l7_route.as_ref().and_then(|route| route.config.as_ref()) { // L7 inspection on terminated TLS traffic. - let tunnel_engine = opa_engine.clone_engine_for_tunnel().unwrap_or_else(|e| { - let event = NetworkActivityBuilder::new(crate::ocsf_ctx()) - .activity(ActivityId::Fail) - .severity(SeverityId::Low) - .status(StatusId::Failure) - .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .message(format!( - "Failed to clone OPA engine for L7, falling back to relay-only: {e}" - )) - .build(); - ocsf_emit!(event); - regorus::Engine::new() - }); + let tunnel_engine = + match opa_engine.clone_engine_for_tunnel(l7_config.generation) { + Ok(engine) => engine, + Err(e) => { + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + return Ok(()); + } + }; crate::l7::relay::relay_with_inspection( - l7_config, - std::sync::Mutex::new(tunnel_engine), + &l7_config.config, + tunnel_engine, &mut tls_client, &mut tls_upstream, &ctx, @@ -783,10 +786,21 @@ async fn handle_tcp_connection( .await } else { // No L7 config — relay with credential injection only. + let generation = l7_route + .as_ref() + .map_or(decision.generation, |route| route.generation); + let generation_guard = match opa_engine.generation_guard(generation) { + Ok(guard) => guard, + Err(e) => { + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + return Ok(()); + } + }; crate::l7::relay::relay_passthrough_with_credentials( &mut tls_client, &mut tls_upstream, &ctx, + &generation_guard, ) .await } @@ -829,23 +843,17 @@ async fn handle_tcp_connection( } } else if is_http { // Plaintext HTTP detected. - if let Some(ref l7_config) = l7_config { - let tunnel_engine = opa_engine.clone_engine_for_tunnel().unwrap_or_else(|e| { - let event = NetworkActivityBuilder::new(crate::ocsf_ctx()) - .activity(ActivityId::Fail) - .severity(SeverityId::Low) - .status(StatusId::Failure) - .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .message(format!( - "Failed to clone OPA engine for L7, falling back to relay-only: {e}" - )) - .build(); - ocsf_emit!(event); - regorus::Engine::new() - }); + if let Some(l7_config) = l7_route.as_ref().and_then(|route| route.config.as_ref()) { + let tunnel_engine = match opa_engine.clone_engine_for_tunnel(l7_config.generation) { + Ok(engine) => engine, + Err(e) => { + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + return Ok(()); + } + }; if let Err(e) = crate::l7::relay::relay_with_inspection( - l7_config, - std::sync::Mutex::new(tunnel_engine), + &l7_config.config, + tunnel_engine, &mut client, &mut upstream, &ctx, @@ -867,10 +875,21 @@ async fn handle_tcp_connection( } } else { // Plaintext HTTP, no L7 config — relay with credential injection. + let generation = l7_route + .as_ref() + .map_or(decision.generation, |route| route.generation); + let generation_guard = match opa_engine.generation_guard(generation) { + Ok(guard) => guard, + Err(e) => { + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + return Ok(()); + } + }; if let Err(e) = crate::l7::relay::relay_passthrough_with_credentials( &mut client, &mut upstream, &ctx, + &generation_guard, ) .await { @@ -1103,6 +1122,7 @@ fn evaluate_opa_tcp( -> ConnectDecision { ConnectDecision { action: NetworkAction::Deny { reason }, + generation: engine.current_generation(), binary, binary_pid, ancestors, @@ -1154,9 +1174,10 @@ fn evaluate_opa_tcp( cmdline_paths: cmdline_paths.clone(), }; - let result = match engine.evaluate_network_action(&input) { - Ok(action) => ConnectDecision { + let result = match engine.evaluate_network_action_with_generation(&input) { + Ok((action, generation)) => ConnectDecision { action, + generation, binary: Some(bin_path), binary_pid: Some(binary_pid), ancestors, @@ -1191,6 +1212,7 @@ fn evaluate_opa_tcp( action: NetworkAction::Deny { reason: "identity binding unavailable on this platform".into(), }, + generation: _engine.current_generation(), binary: None, binary_pid: None, ancestors: vec![], @@ -1594,16 +1616,43 @@ async fn write_all(writer: &mut (impl tokio::io::AsyncWrite + Unpin), data: &[u8 Ok(()) } +#[derive(Debug, Clone)] +struct L7ConfigSnapshot { + config: crate::l7::L7EndpointConfig, + generation: u64, +} + +#[derive(Debug, Clone)] +struct L7RouteSnapshot { + config: Option, + generation: u64, +} + +fn emit_l7_tunnel_close_after_policy_change(host: &str, port: u16, error: miette::Report) { + let event = NetworkActivityBuilder::new(crate::ocsf_ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain(host, port)) + .message(format!( + "L7 tunnel closed before inspection because policy changed: {error}" + )) + .build(); + ocsf_emit!(event); +} + /// Query L7 endpoint config from the OPA engine for a matched CONNECT decision. /// /// Returns `Some(L7EndpointConfig)` if the matched endpoint has L7 config (protocol field), /// `None` for L4-only endpoints. -fn query_l7_config( +fn query_l7_route_snapshot( engine: &OpaEngine, decision: &ConnectDecision, host: &str, port: u16, -) -> Option { +) -> Option { // Only query if action is Allow (not Deny) let has_policy = match &decision.action { NetworkAction::Allow { matched_policy } => matched_policy.is_some(), @@ -1622,9 +1671,16 @@ fn query_l7_config( cmdline_paths: decision.cmdline_paths.clone(), }; - match engine.query_endpoint_config(&input) { - Ok(Some(val)) => crate::l7::parse_l7_config(&val), - Ok(None) => None, + match engine.query_endpoint_config_with_generation(&input) { + Ok((Some(val), generation)) => Some(L7RouteSnapshot { + config: crate::l7::parse_l7_config(&val) + .map(|config| L7ConfigSnapshot { config, generation }), + generation, + }), + Ok((None, generation)) => Some(L7RouteSnapshot { + config: None, + generation, + }), Err(e) => { let event = NetworkActivityBuilder::new(crate::ocsf_ctx()) .activity(ActivityId::Fail) @@ -2258,12 +2314,49 @@ fn rewrite_forward_request( Ok(output) } +async fn relay_rewritten_forward_request( + method: &str, + path: &str, + rewritten: Vec, + client: &mut C, + upstream: &mut U, + generation_guard: &PolicyGenerationGuard, +) -> Result +where + C: TokioAsyncRead + TokioAsyncWrite + Unpin, + U: TokioAsyncRead + TokioAsyncWrite + Unpin, +{ + let header_end = rewritten + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map_or(rewritten.len(), |p| p + 4); + let header_str = String::from_utf8_lossy(&rewritten[..header_end]); + let body_length = crate::l7::rest::parse_body_length(&header_str)?; + let (_, query_params) = crate::l7::rest::parse_target_query(path)?; + let req = crate::l7::provider::L7Request { + action: method.to_string(), + target: path.to_string(), + query_params, + raw_header: rewritten, + body_length, + }; + + crate::l7::rest::relay_http_request_with_resolver_guarded( + &req, + client, + upstream, + None, + Some(generation_guard), + ) + .await +} + /// Handle a plain HTTP forward proxy request (non-CONNECT). /// /// Public IPs are allowed through when the endpoint passes OPA evaluation. /// Private IPs require explicit `allowed_ips` on the endpoint config (SSRF /// override). Rewrites the absolute-form request to origin-form, connects -/// upstream, and relays the response using `copy_bidirectional` for streaming. +/// upstream, and relays the request/response using the guarded HTTP relay. // Many distinct, non-related context parameters are required for forward proxy // dispatch; bundling them into a struct would just shift the noise into call sites. #[allow(clippy::too_many_arguments)] @@ -2423,23 +2516,69 @@ async fn handle_forward_proxy( }; let policy_str = matched_policy.as_deref().unwrap_or("-"); let sandbox_entrypoint_pid = entrypoint_pid.load(Ordering::Acquire); + let forward_generation_guard = match opa_engine.generation_guard(decision.generation) { + Ok(guard) => guard, + Err(e) => { + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + respond( + client, + &build_json_error_response( + 403, + "Forbidden", + "policy_denied", + &format!("{method} {host_lc}:{port}{path} not permitted by policy"), + ), + ) + .await?; + return Ok(()); + } + }; // 4b. If the endpoint has L7 config, evaluate the request against // L7 policy. The forward proxy handles exactly one request per // connection (Connection: close), so a single evaluation suffices. - if let Some(l7_config) = query_l7_config(&opa_engine, &decision, &host_lc, port) { - let tunnel_engine = opa_engine.clone_engine_for_tunnel().unwrap_or_else(|e| { - let event = NetworkActivityBuilder::new(crate::ocsf_ctx()) - .activity(ActivityId::Fail) - .severity(SeverityId::Low) - .status(StatusId::Failure) - .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .message(format!("Failed to clone OPA engine for forward L7: {e}")) - .build(); - ocsf_emit!(event); - regorus::Engine::new() - }); - let engine_mutex = std::sync::Mutex::new(tunnel_engine); + if let Some(route) = query_l7_route_snapshot(&opa_engine, &decision, &host_lc, port) + && let Some(l7_config) = route.config + { + if l7_config.generation != forward_generation_guard.captured_generation() { + emit_l7_tunnel_close_after_policy_change( + &host_lc, + port, + miette::miette!( + "policy changed before forward L7 evaluation [expected_generation:{} current_generation:{}]", + forward_generation_guard.captured_generation(), + l7_config.generation, + ), + ); + respond( + client, + &build_json_error_response( + 403, + "Forbidden", + "policy_denied", + &format!("{method} {host_lc}:{port}{path} not permitted by policy"), + ), + ) + .await?; + return Ok(()); + } + let tunnel_engine = match opa_engine.clone_engine_for_tunnel(l7_config.generation) { + Ok(engine) => engine, + Err(e) => { + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + respond( + client, + &build_json_error_response( + 403, + "Forbidden", + "policy_denied", + &format!("{method} {host_lc}:{port}{path} not permitted by policy"), + ), + ) + .await?; + return Ok(()); + } + }; let l7_ctx = crate::l7::relay::L7EvalContext { host: host_lc.clone(), @@ -2471,7 +2610,7 @@ async fn handle_forward_proxy( // while the upstream re-normalizes the raw input and dispatches on a // potentially different path. let canonicalize_options = crate::l7::path::CanonicalizeOptions { - allow_encoded_slash: l7_config.allow_encoded_slash, + allow_encoded_slash: l7_config.config.allow_encoded_slash, ..Default::default() }; let query_params = @@ -2516,7 +2655,7 @@ async fn handle_forward_proxy( }; let (allowed, reason) = - crate::l7::relay::evaluate_l7_request(&engine_mutex, &l7_ctx, &request_info) + crate::l7::relay::evaluate_l7_request(&tunnel_engine, &l7_ctx, &request_info) .unwrap_or_else(|e| { let event = NetworkActivityBuilder::new(crate::ocsf_ctx()) .activity(ActivityId::Fail) @@ -2529,7 +2668,7 @@ async fn handle_forward_proxy( (false, format!("L7 evaluation error: {e}")) }); - let decision_str = match (allowed, l7_config.enforcement) { + let decision_str = match (allowed, l7_config.config.enforcement) { (true, _) => "allow", (false, crate::l7::EnforcementMode::Audit) => "audit", (false, crate::l7::EnforcementMode::Enforce) => "deny", @@ -2573,7 +2712,7 @@ async fn handle_forward_proxy( } let effectively_denied = - !allowed && l7_config.enforcement == crate::l7::EnforcementMode::Enforce; + !allowed && l7_config.config.enforcement == crate::l7::EnforcementMode::Enforce; if effectively_denied { emit_denial_simple( @@ -2775,6 +2914,21 @@ async fn handle_forward_proxy( } }; + if let Err(e) = forward_generation_guard.ensure_current() { + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + respond( + client, + &build_json_error_response( + 403, + "Forbidden", + "policy_denied", + &format!("{method} {host_lc}:{port}{path} not permitted by policy"), + ), + ) + .await?; + return Ok(()); + } + // 6. Connect upstream let mut upstream = match TcpStream::connect(addrs.as_slice()).await { Ok(s) => s, @@ -2859,12 +3013,32 @@ async fn handle_forward_proxy( return Ok(()); } }; - upstream.write_all(&rewritten).await.into_diagnostic()?; - - // 8. Relay remaining traffic bidirectionally (supports streaming) - let _ = tokio::io::copy_bidirectional(client, &mut upstream) - .await - .into_diagnostic()?; + if let Err(e) = forward_generation_guard.ensure_current() { + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + respond( + client, + &build_json_error_response( + 403, + "Forbidden", + "policy_denied", + &format!("{method} {host_lc}:{port}{path} not permitted by policy"), + ), + ) + .await?; + return Ok(()); + } + let outcome = relay_rewritten_forward_request( + method, + &path, + rewritten, + client, + &mut upstream, + &forward_generation_guard, + ) + .await?; + if let crate::l7::provider::RelayOutcome::Upgraded { overflow } = outcome { + crate::l7::relay::handle_upgrade(client, &mut upstream, overflow, &host_lc, port).await?; + } Ok(()) } @@ -3943,6 +4117,80 @@ mod tests { assert!(!result_str.contains("openshell:resolve:env:ANTHROPIC_API_KEY")); } + #[tokio::test] + async fn test_forward_relay_guard_blocks_stale_generation_before_upstream_write() { + let policy = include_str!("../data/sandbox-policy.rego"); + let policy_data = "network_policies: {}\n"; + let engine = OpaEngine::from_strings(policy, policy_data).unwrap(); + let guard = engine + .generation_guard(engine.current_generation()) + .unwrap(); + engine.reload(policy, policy_data).unwrap(); + + let raw = b"GET http://host/api HTTP/1.1\r\nHost: host\r\n\r\n"; + let rewritten = + rewrite_forward_request(raw, raw.len(), "/api", None).expect("rewrite should succeed"); + let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); + let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); + + let result = relay_rewritten_forward_request( + "GET", + "/api", + rewritten, + &mut proxy_to_client, + &mut proxy_to_upstream, + &guard, + ) + .await; + assert!( + result.is_err(), + "stale generation must stop forward relay before upstream write" + ); + + drop(proxy_to_upstream); + let mut forwarded = Vec::new(); + upstream_side.read_to_end(&mut forwarded).await.unwrap(); + assert!( + forwarded.is_empty(), + "stale forward request bytes must not reach upstream" + ); + } + + #[tokio::test] + async fn test_forward_relay_rejects_cl_te_smuggling_before_upstream_write() { + let policy = include_str!("../data/sandbox-policy.rego"); + let policy_data = "network_policies: {}\n"; + let engine = OpaEngine::from_strings(policy, policy_data).unwrap(); + let guard = engine + .generation_guard(engine.current_generation()) + .unwrap(); + + let raw = b"POST http://host/api HTTP/1.1\r\nHost: host\r\nContent-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n"; + let rewritten = + rewrite_forward_request(raw, raw.len(), "/api", None).expect("rewrite should succeed"); + let (mut proxy_to_upstream, mut upstream_side) = tokio::io::duplex(8192); + let (mut _app_side, mut proxy_to_client) = tokio::io::duplex(8192); + + let result = relay_rewritten_forward_request( + "POST", + "/api", + rewritten, + &mut proxy_to_client, + &mut proxy_to_upstream, + &guard, + ) + .await; + assert!(result.is_err(), "forward relay must reject CL/TE ambiguity"); + + drop(proxy_to_upstream); + let mut forwarded = Vec::new(); + upstream_side.read_to_end(&mut forwarded).await.unwrap(); + assert!( + forwarded.is_empty(), + "smuggled forward request bytes must not reach upstream" + ); + } + // --- Forward proxy SSRF defence tests --- // // The forward proxy handler uses the same SSRF logic as the CONNECT path: diff --git a/docs/sandboxes/policies.mdx b/docs/sandboxes/policies.mdx index 9e8d5fafe3..19502d71fb 100644 --- a/docs/sandboxes/policies.mdx +++ b/docs/sandboxes/policies.mdx @@ -48,6 +48,8 @@ network_policies: Static sections are locked at sandbox creation. Changing them requires destroying and recreating the sandbox. Dynamic sections can be updated on a running sandbox with `openshell policy update` for incremental merges or `openshell policy set` for full replacement, and take effect without restarting. +When a hot reload changes rules on an active HTTP L7 endpoint, existing keep-alive tunnels are closed before forwarding another parsed request. Credential-injection-only HTTP passthrough tunnels use the same reload boundary. Most HTTP clients reconnect automatically, and the next request is evaluated against the current policy. +Raw streams are connection-scoped and outside L7 live-reload guarantees. This includes `tls: skip`, non-HTTP TCP payloads, HTTP upgrades such as WebSocket, and long-lived response streams such as SSE. A reload applies to the next connection or next parsed HTTP request; it does not interrupt an already-forwarded raw stream. | Section | Type | Description | |---|---|---| @@ -445,7 +447,7 @@ Allow `pip install` and `uv pip install` to reach PyPI: - { path: /usr/local/bin/uv } ``` -Endpoints without `protocol` use TCP passthrough, where the proxy allows the stream without inspecting payloads. +Endpoints without `protocol` use TCP passthrough, where the proxy allows the stream without inspecting payloads. If the stream is HTTP and TLS is auto-terminated, the proxy can still rewrite configured credential placeholders and closes keep-alive passthrough tunnels on policy reload before forwarding another request.