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/issue-triage.yml b/.github/workflows/issue-triage.yml
index 10732b8c28..2549172596 100644
--- a/.github/workflows/issue-triage.yml
+++ b/.github/workflows/issue-triage.yml
@@ -8,40 +8,50 @@ permissions:
issues: write
jobs:
- check-agent-diagnostic:
+ label-non-maintainer-issues:
runs-on: ubuntu-latest
- # Only run on bug reports (title starts with "bug:")
- if: startsWith(github.event.issue.title, 'bug:')
+ if: github.repository_owner == 'NVIDIA'
steps:
- - name: Check for agent diagnostic section
+ - name: Check contributor permissions
+ id: contributor
uses: actions/github-script@v7
with:
+ result-encoding: string
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;
+ const author = context.payload.issue.user.login;
+ const maintainerPermissions = ['admin', 'maintain', 'write'];
+
+ try {
+ const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ username: author,
+ });
+
+ if (maintainerPermissions.includes(data.permission)) {
+ console.log(`${author} has maintainer permissions: ${data.permission}.`);
+ return 'false';
+ }
+
+ 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; labeling for triage.`);
+ return 'true';
+ }
+
+ throw e;
}
- console.log('Agent diagnostic section missing or placeholder. Flagging.');
-
- // Add state:triage-needed label
+ - name: Add triage label
+ if: steps.contributor.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']
+ labels: ['state:triage-needed'],
});
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/CONTRIBUTING.md b/CONTRIBUTING.md
index 3a01d75eb0..fc5ad6c803 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 users without `write`, `maintain`, or `admin` repository permission are automatically labeled `state:triage-needed` by the issue triage workflow.
## Prerequisites
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/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/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-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(())
}
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-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-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