diff --git a/.github/workflows/branch-checks.yml b/.github/workflows/branch-checks.yml index a65ea745d9..31b590e572 100644 --- a/.github/workflows/branch-checks.yml +++ b/.github/workflows/branch-checks.yml @@ -172,6 +172,26 @@ jobs: OPENSHELL_TELEMETRY_ENABLED: "false" run: | cargo nextest run --profile ci --workspace --features openshell-server/test-support + cargo nextest run --config-file .config/nextest.toml --profile ci --manifest-path examples/supervisor-middleware-content-guard/Cargo.toml + + - name: Verify standalone policy prover package + if: matrix.system == 'x86_64-linux' + env: + CARGO_NET_OFFLINE: "true" + run: | + cargo test --locked -p openshell-prover-cli + cargo build --locked --release -p openshell-prover-cli --bin openshell-prover + cargo tree --locked -p openshell-prover-cli --edges normal --prefix none > /tmp/openshell-prover-dependencies.txt + if grep -Eq '^(openshell-(cli|server|sdk|bootstrap|tui|providers|core|policy)) v' /tmp/openshell-prover-dependencies.txt; then + echo "ERROR: standalone prover includes an OpenShell control-plane dependency" >&2 + cat /tmp/openshell-prover-dependencies.txt >&2 + exit 1 + fi + target/release/openshell-prover check \ + crates/openshell-prover-cli/tests/fixtures/candidate-contained.yaml \ + --boundary crates/openshell-prover-cli/tests/fixtures/boundary.yaml \ + --output json > /tmp/openshell-prover-result.json + grep -q '"result"[[:space:]]*:[[:space:]]*"within_boundary"' /tmp/openshell-prover-result.json - name: Verify telemetry can be compiled out run: | diff --git a/.github/workflows/build-binaries.yml b/.github/workflows/build-binaries.yml index d9772a9d9e..ad34ee7926 100644 --- a/.github/workflows/build-binaries.yml +++ b/.github/workflows/build-binaries.yml @@ -77,6 +77,24 @@ jobs: timeout-minutes: 60 steps: *build_steps + prover: + name: openshell-prover (${{ matrix.triple }}) + env: + PACKAGE: openshell-prover-cli + BINARY: openshell-prover + strategy: + matrix: + include: + - triple: x86_64-unknown-linux-musl + runner: linux-amd64-cpu8 + - triple: aarch64-unknown-linux-musl + runner: linux-arm64-cpu8 + - triple: aarch64-apple-darwin + runner: macos-15-xlarge + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + steps: *build_steps + gateway: name: openshell-gateway (${{ matrix.triple }}) env: diff --git a/.github/workflows/build-rpm.yml b/.github/workflows/build-rpm.yml index 71aa04dddf..0b07af3160 100644 --- a/.github/workflows/build-rpm.yml +++ b/.github/workflows/build-rpm.yml @@ -21,6 +21,9 @@ on: gateway-target: required: true type: string + prover-target: + required: true + type: string rpm-version: required: false type: string @@ -81,10 +84,16 @@ jobs: name: openshell-gateway-${{ inputs.gateway-target }} path: package-binaries/ + - name: Download prover artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-prover-${{ inputs.prover-target }} + path: package-binaries/ + - name: Configure package inputs run: | set -euo pipefail - chmod +x package-binaries/openshell{,-gateway} + chmod +x package-binaries/openshell{,-gateway,-prover} ls -lah package-binaries - name: Mark workspace safe for git diff --git a/.github/workflows/conformance.yml b/.github/workflows/conformance.yml index a349d8bc23..c3e102cdef 100644 --- a/.github/workflows/conformance.yml +++ b/.github/workflows/conformance.yml @@ -4,150 +4,106 @@ name: Conformance on: - workflow_dispatch: {} - -permissions: {} + workflow_call: + inputs: + scenarios: + description: JSON array of tmachine scenarios to run + required: true + type: string + testsuites: + description: JSON array of tmachine test suites to run + required: true + type: string + +permissions: + actions: read + contents: read concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + group: ${{ github.workflow }}-conformance-${{ github.ref }} cancel-in-progress: true jobs: - pr_metadata: - name: Resolve PR metadata - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: read - outputs: - should_run: ${{ steps.gate.outputs.should_run }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - id: gate - uses: ./.github/actions/pr-gate - - version: - needs: pr_metadata - if: needs.pr_metadata.outputs.should_run == 'true' - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - contents: read - outputs: - cargo: ${{ steps.version.outputs.cargo }} - rpm_version: ${{ steps.version.outputs.rpm_version }} - rpm_release: ${{ steps.version.outputs.rpm_release }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Compute versions - id: version - run: | - cargo="$(python3 tasks/scripts/release.py get-version --cargo)" - rpm_version="$(python3 tasks/scripts/release.py get-version --rpm-version)" - rpm_release="$(python3 tasks/scripts/release.py get-version --rpm-release)" - { - echo "cargo=$cargo" - echo "rpm_version=$rpm_version" - echo "rpm_release=$rpm_release" - } >> "$GITHUB_OUTPUT" - - build-cli: - needs: version - runs-on: linux-amd64-cpu8 - timeout-minutes: 60 - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - ref: ${{ github.sha }} - - uses: ./.github/actions/setup-nix - with: - cachix-auth-token: ${{ secrets.CACHIX_AUTH_TOKEN }} - - uses: ./.github/actions/build-rust-binary - with: - package: openshell-cli - binary: openshell - triple: x86_64-unknown-linux-musl - cargo-version: ${{ needs.version.outputs.cargo }} - - build-conformance: - needs: version - runs-on: linux-amd64-cpu8 - timeout-minutes: 60 - permissions: - contents: read + prepare: + name: Prepare conformance inputs + runs-on: ubuntu-24.04 + timeout-minutes: 30 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false ref: ${{ github.sha }} + - uses: ./.github/actions/setup-nix + + - name: Download CLI artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - cachix-auth-token: ${{ secrets.CACHIX_AUTH_TOKEN }} - - uses: ./.github/actions/build-rust-binary + name: openshell-x86_64-unknown-linux-musl + path: artifacts/binaries/x86_64-unknown-linux-musl + + - name: Download gateway artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - package: openshell-conformance-cli - binary: openshell-conformance - triple: x86_64-unknown-linux-musl - cargo-version: ${{ needs.version.outputs.cargo }} - - build-gateway: - needs: version - runs-on: linux-amd64-cpu8 - timeout-minutes: 60 - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + name: openshell-gateway-x86_64-unknown-linux-gnu + path: artifacts/binaries/x86_64-unknown-linux-gnu + + - name: Download sandbox image artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - persist-credentials: false - ref: ${{ github.sha }} - - uses: ./.github/actions/setup-nix + name: image-sandbox + path: image-input/sandbox + + - name: Download supervisor image artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - cachix-auth-token: ${{ secrets.CACHIX_AUTH_TOKEN }} - - uses: ./.github/actions/build-rust-binary + name: image-supervisor + path: image-input/supervisor + + - name: Convert runtime images + shell: nix develop .#testing -c bash -euo pipefail {0} + run: | + mkdir -p artifacts/images + + skopeo copy \ + --override-os linux \ + --override-arch amd64 \ + oci-archive:image-input/sandbox/images/sandbox.tar \ + docker-archive:artifacts/images/openshell-sandbox-tmachine.tar:openshell/sandbox:tmachine + + skopeo copy \ + --override-os linux \ + --override-arch amd64 \ + oci-archive:image-input/supervisor/images/supervisor.tar \ + docker-archive:artifacts/images/openshell-supervisor-tmachine.tar:openshell/supervisor:tmachine + + - name: Build conformance test archive + run: nix run .#build-artifacts-test-archives + + - name: Upload conformance inputs + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - package: openshell-gateway - binary: openshell-gateway - triple: x86_64-unknown-linux-gnu - cargo-version: ${{ needs.version.outputs.cargo }} - supervisor-image-tag: dev - - build-rpm: - needs: [version, build-cli, build-gateway] - permissions: - contents: read - uses: ./.github/workflows/build-rpm.yml - with: - checkout-ref: ${{ github.sha }} - arch: x86_64 - runner: linux-amd64-cpu8 - cli-target: x86_64-unknown-linux-musl - gateway-target: x86_64-unknown-linux-gnu - cargo-version: ${{ needs.version.outputs.cargo }} - rpm-version: ${{ needs.version.outputs.rpm_version }} - rpm-release: ${{ needs.version.outputs.rpm_release }} - - fedora: - name: Fedora with Rootless Podman - needs: [build-conformance, build-rpm] + name: openshell-conformance-inputs + path: artifacts + compression-level: 0 + retention-days: 5 + if-no-files-found: error + + conformance: + name: Conformance (${{ matrix.scenario }}, ${{ matrix.testsuite }}) + needs: prepare + strategy: + fail-fast: false + matrix: + scenario: ${{ fromJSON(inputs.scenarios) }} + testsuite: ${{ fromJSON(inputs.testsuites) }} runs-on: ubuntu-24.04 - timeout-minutes: 45 - permissions: - actions: read - contents: read + timeout-minutes: 90 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + ref: ${{ github.sha }} - name: Enable KVM access run: | @@ -162,40 +118,20 @@ jobs: - uses: ./.github/actions/setup-nix - - name: Download RPM artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + - name: Cache tmachine disks + uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 with: - name: rpm-linux-x86_64 - path: rpm-input + path: ~/.cache/tmachine + key: tmachine-${{ runner.os }}-${{ runner.arch }} - - name: Download conformance CLI + - name: Download conformance inputs uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: openshell-conformance-x86_64-unknown-linux-musl - path: conformance-input - - - name: Run RPM smoke conformance - shell: bash - run: | - set -euo pipefail - chmod +x conformance-input/openshell-conformance - shopt -s nullglob - candidate_cli_package=(rpm-input/openshell-[0-9]*.rpm) - candidate_gateway_package=(rpm-input/openshell-gateway-[0-9]*.rpm) - if [[ ${#candidate_cli_package[@]} -ne 1 || ${#candidate_gateway_package[@]} -ne 1 ]]; then - echo "expected one candidate CLI and gateway RPM" >&2 - printf 'RPM artifacts:\n' >&2 - printf ' %s\n' rpm-input/* >&2 - exit 1 - fi - - OPENSHELL_TEST_GUEST_CACHE_DISABLE=1 nix run .#test-guest -- \ - --distro fedora \ - --with podman-rootless \ - --with selinux \ - --install "${candidate_cli_package[0]}" \ - --install "${candidate_gateway_package[0]}" \ - --copy conformance-input/openshell-conformance:/tmp/openshell-conformance \ - --provision openshell-rpm \ - --provision gateway-podman \ - -- /tmp/openshell-conformance run smoke + name: openshell-conformance-inputs + path: artifacts + + - name: Run conformance + env: + SCENARIO: ${{ matrix.scenario }} + TESTSUITE: ${{ matrix.testsuite }} + run: nix run .#tmachine -- test "${SCENARIO}" "${TESTSUITE}" diff --git a/.github/workflows/deb-package.yml b/.github/workflows/deb-package.yml index 7008acd4ed..1ec52dc3a1 100644 --- a/.github/workflows/deb-package.yml +++ b/.github/workflows/deb-package.yml @@ -58,6 +58,12 @@ jobs: name: openshell-gateway-${{ matrix.gnu_target }} path: package-binaries/ + - name: Download prover artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-prover-${{ matrix.cli_target }} + path: package-binaries/ + - name: Download VM driver artifact uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -67,7 +73,7 @@ jobs: - name: Configure package inputs run: | set -euo pipefail - chmod +x package-binaries/openshell{,-gateway,-driver-vm} + chmod +x package-binaries/openshell{,-gateway,-prover,-driver-vm} ls -lah package-binaries - name: Build Debian package @@ -75,6 +81,7 @@ jobs: set -euo pipefail OPENSHELL_CLI_BINARY="${PWD}/package-binaries/openshell" \ OPENSHELL_GATEWAY_BINARY="${PWD}/package-binaries/openshell-gateway" \ + OPENSHELL_PROVER_BINARY="${PWD}/package-binaries/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="${PWD}/package-binaries/openshell-driver-vm" \ OPENSHELL_DEB_VERSION="${INPUTS_DEB_VERSION}" \ OPENSHELL_DEB_ARCH="${{ matrix.deb_arch }}" \ diff --git a/.github/workflows/package-release-binaries.yml b/.github/workflows/package-release-binaries.yml index 2e05bc1876..fb8df4ada2 100644 --- a/.github/workflows/package-release-binaries.yml +++ b/.github/workflows/package-release-binaries.yml @@ -5,6 +5,11 @@ name: Package Release Binaries on: workflow_call: + inputs: + checkout-ref: + required: false + type: string + default: "" permissions: actions: read @@ -58,6 +63,15 @@ jobs: - artifact: openshell-driver-vm-aarch64-apple-darwin binary: openshell-driver-vm package: driver-vm-macos + - artifact: openshell-prover-x86_64-unknown-linux-musl + binary: openshell-prover + package: prover-binary-linux-amd64 + - artifact: openshell-prover-aarch64-unknown-linux-musl + binary: openshell-prover + package: prover-binary-linux-arm64 + - artifact: openshell-prover-aarch64-apple-darwin + binary: openshell-prover + package: prover-binary-macos steps: - name: Download ${{ matrix.artifact }} uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 @@ -81,3 +95,109 @@ jobs: path: ${{ matrix.artifact }}.tar.gz retention-days: 5 if-no-files-found: error + + smoke-prover: + name: Smoke packaged prover (${{ matrix.triple }}) + needs: package + runs-on: ${{ matrix.runner }} + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + include: + - triple: x86_64-unknown-linux-musl + runner: linux-amd64-cpu8 + package: prover-binary-linux-amd64 + - triple: aarch64-unknown-linux-musl + runner: linux-arm64-cpu8 + package: prover-binary-linux-arm64 + - triple: aarch64-apple-darwin + runner: macos-15-xlarge + package: prover-binary-macos + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs['checkout-ref'] || github.sha }} + + - name: Download packaged prover + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ matrix.package }} + path: package + + - name: Extract and run containment check + env: + TRIPLE: ${{ matrix.triple }} + run: | + set -euo pipefail + mkdir extracted + tar -xzf "package/openshell-prover-${TRIPLE}.tar.gz" -C extracted + test "$(find extracted -type f | wc -l | tr -d ' ')" = 1 + test -x extracted/openshell-prover + if [ "${RUNNER_OS}" = "Linux" ]; then + tasks/scripts/verify-static-binary.sh extracted/openshell-prover + else + otool -L extracted/openshell-prover | tee linkage.txt + if grep -Eiq 'libz3|/nix/store' linkage.txt; then + echo "ERROR: packaged prover has a non-portable native dependency" >&2 + exit 1 + fi + fi + extracted/openshell-prover check \ + crates/openshell-prover-cli/tests/fixtures/candidate-contained.yaml \ + --boundary crates/openshell-prover-cli/tests/fixtures/boundary.yaml \ + --output json > result.json + grep -q '"result"[[:space:]]*:[[:space:]]*"within_boundary"' result.json + + if extracted/openshell-prover check \ + crates/openshell-prover-cli/tests/fixtures/candidate-underscore-host.yaml \ + --boundary crates/openshell-prover-cli/tests/fixtures/boundary-empty.yaml \ + --output json > underscore.json; then + echo "ERROR: underscore host unexpectedly stayed within an empty boundary" >&2 + exit 1 + else + test "$?" = 1 + fi + grep -q '"result"[[:space:]]*:[[:space:]]*"exceeds_boundary"' underscore.json + grep -q '"host"[[:space:]]*:[[:space:]]*"api_internal.example.com"' underscore.json + + if extracted/openshell-prover check \ + crates/openshell-prover-cli/tests/fixtures/candidate-unicode-network-selector.yaml \ + --boundary crates/openshell-prover-cli/tests/fixtures/boundary-empty.yaml \ + --output json > unicode.json; then + echo "ERROR: non-ASCII network selector unexpectedly produced a definitive result" >&2 + exit 1 + else + test "$?" = 3 + fi + grep -q '"result"[[:space:]]*:[[:space:]]*"unsupported"' unicode.json + grep -q '"reason_code"[[:space:]]*:[[:space:]]*"unsupported_policy_shape"' unicode.json + + prover-checksums: + name: Package prover checksums + needs: smoke-prover + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Download packaged prover archives + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: prover-binary-* + path: release + merge-multiple: true + + - name: Generate prover checksums + run: | + set -euo pipefail + cd release + sha256sum openshell-prover-*.tar.gz > openshell-prover-checksums-sha256.txt + test "$(awk 'END { print NR }' openshell-prover-checksums-sha256.txt)" = 3 + sha256sum --check openshell-prover-checksums-sha256.txt + + - name: Upload prover checksums + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: prover-checksums + path: release/openshell-prover-checksums-sha256.txt + retention-days: 5 + if-no-files-found: error diff --git a/.github/workflows/release-dev.yml b/.github/workflows/release-dev.yml index 1af053d091..68c73a562e 100644 --- a/.github/workflows/release-dev.yml +++ b/.github/workflows/release-dev.yml @@ -89,6 +89,8 @@ jobs: actions: read contents: read uses: ./.github/workflows/package-release-binaries.yml + with: + checkout-ref: ${{ github.sha }} build-images: needs: build-binaries @@ -99,6 +101,16 @@ jobs: with: checkout-ref: ${{ github.sha }} + conformance: + needs: [build-binaries, build-images] + permissions: + actions: read + contents: read + uses: ./.github/workflows/conformance.yml + with: + scenarios: '["ubuntu-docker-rootful", "fedora-podman-rootful", "fedora-podman-rootless"]' + testsuites: '["smoke"]' + docker-e2e: needs: [build-binaries, build-images] permissions: @@ -232,7 +244,7 @@ jobs: # --------------------------------------------------------------------------- release-dev: name: Release Dev - needs: [compute-versions, package-binaries, build-python-wheel, docker-e2e, podman-e2e, vm-e2e, build-deb, build-rpm, build-snap] + needs: [compute-versions, package-binaries, build-python-wheel, conformance, docker-e2e, podman-e2e, vm-e2e, build-deb, build-rpm, build-snap] runs-on: linux-amd64-cpu8 timeout-minutes: 10 permissions: @@ -280,6 +292,19 @@ jobs: path: release/ merge-multiple: true + - name: Download prover binary artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: prover-binary-* + path: release/ + merge-multiple: true + + - name: Download prover checksums + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: prover-checksums + path: release/ + - name: Download wheel artifact uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -483,12 +508,16 @@ jobs: release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-prover-x86_64-unknown-linux-musl.tar.gz + release/openshell-prover-aarch64-unknown-linux-musl.tar.gz + release/openshell-prover-aarch64-apple-darwin.tar.gz release/*.whl release/openshell.rb release/openshell-checksums-sha256.txt release/openshell-gateway-checksums-sha256.txt release/openshell-sandbox-checksums-sha256.txt release/openshell-supervisor-checksums-sha256.txt + release/openshell-prover-checksums-sha256.txt release-helm: name: Release Helm Chart (OCI, dev) diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index 811e43e31f..09010d9031 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -111,11 +111,13 @@ jobs: CACHIX_AUTH_TOKEN: ${{ secrets.CACHIX_AUTH_TOKEN }} package-binaries: - needs: [build-binaries, build-vm-driver] + needs: [compute-versions, build-binaries, build-vm-driver] permissions: actions: read contents: read uses: ./.github/workflows/package-release-binaries.yml + with: + checkout-ref: ${{ needs.compute-versions.outputs.source_sha }} build-images: needs: [compute-versions, build-binaries] @@ -322,6 +324,19 @@ jobs: path: release/ merge-multiple: true + - name: Download prover binary artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: prover-binary-* + path: release/ + merge-multiple: true + + - name: Download prover checksums + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: prover-checksums + path: release/ + - name: Download wheel artifact uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -467,12 +482,16 @@ jobs: release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-prover-x86_64-unknown-linux-musl.tar.gz + release/openshell-prover-aarch64-unknown-linux-musl.tar.gz + release/openshell-prover-aarch64-apple-darwin.tar.gz release/*.whl release/openshell.rb release/openshell-checksums-sha256.txt release/openshell-gateway-checksums-sha256.txt release/openshell-sandbox-checksums-sha256.txt release/openshell-supervisor-checksums-sha256.txt + release/openshell-prover-checksums-sha256.txt - name: Upload pre-release artifacts if: needs.compute-versions.outputs.is_prerelease == 'true' diff --git a/.github/workflows/rpm-package.yml b/.github/workflows/rpm-package.yml index 5cda9a88c3..5e2e50ac59 100644 --- a/.github/workflows/rpm-package.yml +++ b/.github/workflows/rpm-package.yml @@ -40,10 +40,12 @@ jobs: runner: linux-amd64-cpu8 cli_target: x86_64-unknown-linux-musl gateway_target: x86_64-unknown-linux-gnu + prover_target: x86_64-unknown-linux-musl - arch: aarch64 runner: linux-arm64-cpu8 cli_target: aarch64-unknown-linux-musl gateway_target: aarch64-unknown-linux-gnu + prover_target: aarch64-unknown-linux-musl uses: ./.github/workflows/build-rpm.yml with: checkout-ref: ${{ inputs.checkout-ref }} @@ -51,6 +53,7 @@ jobs: runner: ${{ matrix.runner }} cli-target: ${{ matrix.cli_target }} gateway-target: ${{ matrix.gateway_target }} + prover-target: ${{ matrix.prover_target }} rpm-version: ${{ inputs.rpm-version }} rpm-release: ${{ inputs.rpm-release }} cargo-version: ${{ inputs.cargo-version }} diff --git a/AGENTS.md b/AGENTS.md index 3ac4eedf15..dab52c2f47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,6 +65,7 @@ These pipelines connect skills into end-to-end workflows. Individual skill files | `crates/openshell-driver-vm/` | VM compute driver | Standalone libkrun-backed `ComputeDriver` subprocess (embeds its own rootfs + runtime) | | `crates/openshell-driver-mxc/` | Microsoft MXC compute driver | In-process Windows AppContainer and isolation-session compute backend | | `crates/openshell-prover/` | Policy prover | Policy verification and proof generation | +| `crates/openshell-prover-cli/` | Policy prover CLI | Standalone local policy boundary checks | | `crates/openshell-server-macros/` | Server macros | Compile-time helpers for gateway RPC authorization | | `crates/openshell-supervisor-middleware/` | Middleware runtime | Generic middleware registry, remote service integration, and chain execution | | `crates/openshell-supervisor-middleware-builtins/` | Built-in middleware | First-party in-process middleware implementations | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 29e90769f8..3d97a6ce10 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -313,11 +313,12 @@ Project requirements: ### Z3 installation -The `openshell-prover` crate links directly against Z3. The `openshell-server` -crate depends on the prover, and the `openshell-gateway` binary crate depends -on `openshell-server` in turn; both forward a `bundled-z3` feature down to -`openshell-prover/bundled-z3`. The `openshell-cli` crate does not depend on -Z3. On macOS and Linux, install the system Z3 development package; `z3-sys` +The `openshell-prover` crate and standalone `openshell-prover-cli` binary link +directly against Z3. The `openshell-server` crate depends on the prover, and +the `openshell-gateway` binary crate depends on `openshell-server` in turn. +These packages forward a `bundled-z3` feature to +`openshell-prover/bundled-z3`. The `openshell-cli` crate does not depend on Z3. +On macOS and Linux, install the system Z3 development package; `z3-sys` discovers it through `pkg-config`. ```bash @@ -336,6 +337,7 @@ compiles Z3 from source during the Rust build and requires CMake 3.16+: ```bash cargo build -p openshell-prover --features bundled-z3 +cargo build -p openshell-prover-cli --features bundled-z3 ``` For x86-64 and ARM64 Windows MSVC builds, use one of these Z3 paths: @@ -459,6 +461,7 @@ These are the primary `mise` tasks for day-to-day development: | --------------- | --------------------------------------------- | | `crates/` | Rust crates | | `crates/openshell-policy-schema/` | Canonical authored policy DTOs and bounded YAML/JSON parser | +| `crates/openshell-prover-cli/` | Standalone local policy boundary checker | | `python/` | Python SDK and bindings | | `sdk/go/` | Go SDK (types, gRPC clients, converters) | | `sdk/typescript/` | TypeScript SDK (Connect client and generated protobuf bindings) | diff --git a/Cargo.lock b/Cargo.lock index 6d5c8afd55..109e6df8d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4472,12 +4472,27 @@ dependencies = [ "include_dir", "miette", "noyalib", + "openshell-core", "openshell-policy-schema", "owo-colors", + "regorus", "serde", + "serde_json", "z3", ] +[[package]] +name = "openshell-prover-cli" +version = "0.0.0" +dependencies = [ + "clap", + "nix 0.29.0", + "openshell-prover", + "serde", + "serde_json", + "signal-hook", +] + [[package]] name = "openshell-providers" version = "0.0.0" diff --git a/Cargo.toml b/Cargo.toml index ebc0485a97..f57b22c397 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -141,6 +141,7 @@ k8s-openapi = { version = "0.24", features = ["v1_29"] } # IDs uuid = { version = "1.10", features = ["v4"] } +signal-hook = "0.3" # SMT solver (uses system libz3; enable z3/bundled via the prover's bundled-z3 feature for local dev without system z3) z3 = "0.20" diff --git a/architecture/build.md b/architecture/build.md index cb60838630..e767f36f61 100644 --- a/architecture/build.md +++ b/architecture/build.md @@ -13,6 +13,7 @@ OpenShell builds these main artifacts: | Gateway binary | `crates/openshell-gateway` | | CLI binaries and system packages | `crates/openshell-cli` plus release packaging | | E2E conformance CLI | `crates/openshell-conformance-cli` | +| Standalone policy prover | `crates/openshell-prover-cli` | | Python SDK wheel | `python/openshell` | | TypeScript SDK package | `sdk/typescript` | | Gateway container image | `deploy/docker/Dockerfile.gateway` | @@ -75,6 +76,14 @@ HTTP/TLS support behind explicit build features, so default system-Z3 builds do not reintroduce bundled Mozilla roots. Release builds that need bundled Z3 continue to opt in with `bundled-z3`. +Release workflows build the standalone `openshell-prover` executable for Linux +musl x86_64 and aarch64 and macOS Apple Silicon. The standard Debian, RPM, and +Homebrew installations include it. Releases also publish one standalone archive +per target plus a dedicated SHA-256 manifest. Before publication, target-native +jobs extract each archive, reject host Z3 or Nix store linkage, and run a real +local containment check. The standalone artifact therefore requires neither an +OpenShell installation nor a separately installed Z3 runtime. + ## Linux Runtime Environments OpenShell uses different Linux libc environments for different host artifacts. @@ -135,6 +144,9 @@ is a different artifact from the source SBOM produced by `syft dir:.` in attestation below, which describes a published image. The shared binary build action compiles release artifacts with `cargo auditable`. +The standalone prover uses this same action, while its package workflow adds +target-native extracted-archive linkage and containment smoke checks before +producing its checksum manifest. Branch E2E, Release Dev, and Release Tag image jobs stage those same artifacts instead of rebuilding binaries in Docker. Each binary build scans its output with Syft and requires at least one decoded Cargo package before uploading the @@ -261,8 +273,10 @@ the required roles and their dependencies before running playbooks. The `tests/artifacts.nix` helpers build the CLI, conformance CLI, and sandbox with musl, and the gateway and supervisor with GNU. Image assembly stages the gateway, sandbox, and supervisor as separate binaries for their respective -Dockerfiles. The Ubuntu Docker and Fedora Podman scenarios import both local -runtime images and configure the gateway to use them. +Dockerfiles. The helpers stage binaries under `artifacts/binaries` so local and +CI builds expose the same inputs to tmachine and image assembly. The Ubuntu +Docker and Fedora Podman scenarios import both local runtime images and +configure the gateway to use them. ## Python Wheel Packaging diff --git a/architecture/compute-runtimes.md b/architecture/compute-runtimes.md index a2bb25c312..3999e32ebc 100644 --- a/architecture/compute-runtimes.md +++ b/architecture/compute-runtimes.md @@ -446,11 +446,14 @@ limit. RBAC promotes sandbox CRD permissions to a ClusterRole and adds namespace Secret copies use server-side apply. Kubernetes authorizes an apply to an existing Secret as `patch`, but also requires `create` authorization when the target does not exist. RBAC cannot constrain `create` by `resourceNames`, so -managed mode grants cluster-wide Secret `create` while keeping source reads and -subsequent patches restricted to the explicitly configured TLS and image-pull -Secret names. The driver exercises `create` only in gateway-owned managed -namespaces. This depends on the managed-mode ownership invariant described -below; the gateway ServiceAccount must not be shared with unrelated workloads. +managed mode grants cluster-wide Secret `create`, `list`, and `delete` for +generation-scoped bootstrap Secret creation and rollback recovery while keeping +source reads and subsequent patches restricted to the explicitly configured TLS +and image-pull Secret names. Recovery lists bootstrap Secrets by sandbox and +component labels, then deletes stale generations with UID preconditions. The +driver exercises these broad permissions only in gateway-owned managed +namespaces. This depends on the managed-mode ownership invariant described below; +the gateway ServiceAccount must not be shared with unrelated workloads. Operator mode does not create NetworkPolicies or copy image-pull Secrets. Platform teams must apply the gateway ingress boundary and provision configured diff --git a/architecture/gateway.md b/architecture/gateway.md index 5e04f377fa..f991e591bc 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -37,6 +37,10 @@ immediately without a grace period. Finalization is persisted separately from the exit result; the gateway deletes an ephemeral sandbox only after the finalized supervisor session disconnects. +Local Docker development builds the supervisor image separately from the +`openshell-sandbox` workload runtime. Cross-platform runtime extraction uses +the sandbox image, which exports `/openshell-sandbox`. + ## Configuration Boundary The gateway accepts exactly schema version 2. Missing, legacy, and future @@ -62,6 +66,37 @@ transport status, metadata, and unknown details alongside decoded fields. SDK deletion waits recognize missing-resource status through typed error wrappers without suppressing other failures. +Ordinary user-callable unary mutations explicitly opt into durable request +admission when the client supplies a UUID. Typed adapters +check current authorization before looking up a caller/method/workspace-scoped +key. The payload fingerprint excludes that UUID and canonicalizes protobuf maps. +An atomic, quota-checked insert chooses one executor; owned execution survives +client cancellation. Success is persisted before acknowledgment. Errors or +interruption leave permanent unresolved claims, never stealable leases. + +Admission rows live outside user workspace namespaces and are bounded per caller. +Successes expire after 24 hours; cleanup uses the unique admission incarnation +and version so an old cleaner cannot delete a new attempt. Replay stores only +resource references and reviewed public scalar/diagnostic receipts, never +credential-bearing response snapshots. It checks original identities and current +authorization and never substitutes a same-name resource. Sandbox responses are +live projections of the original UUID; normal status reconciliation does not +invalidate replay. Refresh status additionally requires the original grant epoch +and no deletion timestamp, including a timestamp at the Unix epoch. +Other resource projections retain exact-version guards. Terminal delete receipts +do not require the deleted target or parent to remain present. + +Sandbox, service, provider/profile, and policy/config adapters use keyed payload +fingerprints derived from existing gateway JWT or primary TLS private material. +Replicas must share that material; missing keys or key changes fail closed without +changing admission identity. Workspace/template adapters retain their original +format. Intercepted requests carry the original decoded payload only in a private +in-memory extension. Replay reauthorizes original and current effective scopes, +requires the same effective payload, and reruns current interceptor validation. +Interceptors cannot mutate the request UUID. Server-marked replay suppresses +post-commit observation, which remains best-effort rather than an outbox. +Credential capabilities and streaming execution require separate contracts. + The gateway listens on one service port and multiplexes gRPC and HTTP traffic. The default local single-user deployment mode is mTLS user authentication: clients present a certificate signed by the local deployment CA, and the @@ -352,6 +387,8 @@ Public RPC contracts and durable protobuf formats have separate ownership. The ` `ReportEndpointStatus` is a sandbox-authenticated public gateway RPC. Its request, response, and `EndpointObservation` messages belong only to the public closure. `EndpointStatus` and `EndpointResult` also belong to the durable closure because `Sandbox.status.endpoint_statuses` persists them. The repeated status field uses a new wire tag; stored sandboxes without it decode with an empty endpoint list and retain their lifecycle fields. A fixed payload encoded with the earlier sandbox schema verifies that no database rewrite is required. +`GetSandboxProviderStatus` and `ReportProviderReadiness` are unary public gateway RPCs. The first lets authorized users inspect a provider change; the second accepts installation reports only from the sandbox's current authenticated supervisor session. + The removed `NetworkBinary.harness` field remains reserved by number and name, so protobuf implementations cannot reuse its wire slot or source identifier. The durable-policy compatibility decoder reads the former boolean before Prost @@ -373,8 +410,10 @@ than extending the frozen message. | SQL materializations | `StoredPolicyRevision`, `StoredDraftChunk` | Server-only typed results assembled from indexed columns and decoded payloads; not public RPC messages. | | Public messages used directly as encoded storage roots | `Sandbox`, `SandboxWorkloadTemplate`, `Provider`, `Workspace`, `WorkspaceMember`, `SshSession`, `ServiceEndpoint` | The generated public type is also the persisted payload. `SshSession` is not in the current public RPC message closure. | | Embedded encoded root | `SandboxPolicy` | Stored in policy rows and inside the JSON settings envelope. | +| Configuration operation storage root | `StoredConfigUpdateOperation` | One common operation resource stores the exact provider target, receipt projection, snapshot failure reason, and historical outcome. | +| Public dependencies of an operation | `ConfigUpdateOperation`, `ProviderMutationReceipt`, `ProviderReadinessReason` | Their complete message and enum closures are durable contracts. | -The descriptor-derived test inventories the complete message and enum closure of the encoded durable roots and its intersection with the public RPC closure. The tables here record the reviewed roots and classifications. +The descriptor-derived test owns the complete public, durable, and intersecting inventories and their reviewed fingerprints. The tables here record their roots and classifications. A synthetic sandbox-spec byte fixture verifies that an absent server-owned attachment epoch decodes to the valid empty initial identity; direct and template creation tests separately require the gateway to replace any caller-supplied epoch. Public delete, membership-removal, and SSH-revocation responses use `DeletionOutcome`, not a transport-success boolean. `COMPLETED` establishes @@ -391,7 +430,8 @@ Missing targets return `NOT_FOUND` unless `allow_missing` explicitly requests failures remain errors. Already-revoked sessions complete without another write after current authorization. The removed response booleans are reserved by name and number; this coordinated pre-1.0 API change does not alter durable schemas. -It does not add request deduplication or identity preconditions for later retries. +The outcome alone does not provide request deduplication. Opted-in unary methods +require a request UUID for the admission contract. | Dual-purpose encoded root | Current decision | |---|---| @@ -403,6 +443,9 @@ It does not add request deduplication or identity preconditions for later retrie | `SshSession` | Defer a storage twin; govern its complete dependency closure as durable. | | `ServiceEndpoint` | Defer a storage twin; govern its complete dependency closure as durable. | | `SandboxPolicy` | Defer a storage twin; govern its complete dependency closure as durable. | +| `ConfigUpdateOperation` | Persist the common historical outcome within `StoredConfigUpdateOperation`; govern its complete dependency closure as durable. | +| `ProviderMutationReceipt` | Persist the immutable provider projection within `StoredConfigUpdateOperation`; govern its complete dependency closure as durable. | +| `ProviderReadinessReason` | Persist only the closed snapshot failure category within the operation; govern its enum values as durable. | The public/storage overlap is deliberate for the current format. Storage twins for the public roots are deferred: introducing them would require a broad @@ -442,6 +485,14 @@ populate `scope`, `version`, `status`, `dedup_key`, and `hit_count` so the gateway can efficiently fetch the latest policy, track load status, and manage advisor drafts without creating resource-specific tables. +Mutation admission uses a private, version-tagged JSON envelope in the same +object store. Its identity namespace stays stable across format changes, and an +unknown format fails closed. It contains explicit typed receipts, not arbitrary +public response payloads, and is not part of the protobuf storage closure. +Workspace create/delete admissions include the requested workspace name in the +key, but omit a workspace UUID guard. Different names have independent request-ID +namespaces; deletion receipts remain replayable after the target disappears. + Each sandbox policy revision stores the complete provenance annotation map supplied with that update. The revision payload is the authoritative immutable record; sandbox metadata receives the same annotations only as a convenience @@ -695,6 +746,28 @@ configuration, valid endpoint-bound static credentials from other attached providers, and the dynamic credential snapshot. Provider environment revisions include profile endpoint and binding changes. +The supervisor owns provider fetching, support negotiation, and credential resolution outside the workload. The authenticated sandbox boundary receives a revision and its prepared child environment from one snapshot; it preserves the issued placeholders without receiving the secret resolver or turning those placeholders into new references. + +Provider mutations return immutable per-sandbox receipts that separate saved desired state from observed runtime installation. A receipt pins sandbox and provider identity, the attachment epoch, and the exact provider/configuration/policy fingerprints. Attachment-set changes replace the epoch in the same sandbox CAS write; credential updates stage distinct backend objects before publishing their handles and provider revision. This prevents a published revision from referring to an unfinished in-place credential write. Update receipts retain the sandbox target set selected before publication. + +Each receipt projects a common configuration operation in the `config_update_operation` store; its receipt ID is the operation ID. The provider status path evaluates current installation evidence and records historical terminal outcomes through resource-version CAS. A previously applied operation does not bypass current session, freshness, or authority checks. The live provider projection can be pending after disconnection or superseded after another change even when historical operation state remains applied. Pending operations are evaluated through provider status queries; this path adds no background delivery engine or mutation replay contract. + +When a provider mutation opts into admission with `request_id`, its replay record retains references to the original configuration operations and the original mutation ID. Replay returns those immutable receipts even if sandbox attachments have since changed; it does not select new targets or create replacement receipts. Missing operation evidence makes replay unavailable without executing the mutation again. Provider resources still require their original recorded version, and sandbox resources retain the replay contract's current-state projection. + +Provider mutation and operation-result writes are separate. A result-storage failure can follow a saved mutation and returns structured uncertainty without a rollback or safe-retry claim. A failed initial snapshot remains failed rather than acquiring a different target during a later lookup. Operations contain only identities, revisions, timestamps, and closed reason categories. + +The CLI recognizes the gateway's `CONFIG_OPERATION_STORAGE_UNCERTAIN` error reason and domain for attach, detach, and update. It reports fixed guidance to inspect and reconcile the saved change before retrying, while withholding arbitrary server messages and error metadata. An uncertain mutation never starts a readiness wait or automatic replay. + +Provider receipts, installation status, and common operations represent absolute times with protobuf `Timestamp`; report intervals and evidence lifetimes use protobuf `Duration`. Receipt identity compares the full canonical timestamp without truncating nanoseconds. An absent observation or completion time represents missing evidence or an unfinished operation, independently of the Unix epoch. + +Provider installation reports belong to the existing `ConnectSupervisor` session. Each report names that session, has an increasing sequence, and expires unless the supervisor reports again. Reconnection or disconnect invalidates prior observations; stored change records survive a gateway restart, but runtime evidence does not. Replaying an identical report cannot extend its lifetime. + +Reports and status also compare the supervisor instance with the sandbox's persisted current instance. A different supervisor becoming current invalidates an older connection, including one retained by another gateway replica. Observations stay local to the gateway holding the supervisor session; a status request reaching a replica without that session returns pending. Multi-replica deployments therefore retain the existing supervisor-session routing requirement. + +The supervisor reports success only after it installs the matching credentials, activates the effective policy, and receives an acknowledgment from the authenticated workload boundary that it installed the environment for future processes. Environment synchronization shares the process-launch lock, and its acknowledgment identifies the exact publication, including retries at the same provider revision. Failed policy installation cannot reuse evidence for a different installed policy. Ready and revoked statuses also recheck the requested sandbox, provider, attachment and configuration identities; revision fingerprints are compared only for equality. Revocation applies to future credential resolution and future processes. Requests already forwarded upstream can still finish. + +Ordinary static credentials retain revision-scoped references. After update readiness, a newly launched process receives the updated reference; an existing process keeps its original revision. Installation completion does not retarget that reference or establish that an old upstream key can be retired. + ## Provider Environment Resolution The gateway resolves only the providers attached to a sandbox. It combines each diff --git a/architecture/sandbox.md b/architecture/sandbox.md index 6d828752f6..a9ba8ac3ef 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -39,6 +39,9 @@ credentials to claim the existing runtime generation. Confirmation resumes the workload; expiration terminates it. A credential replacement does not displace the active connection until the new connection is confirmed. Idle healthy connections remain usable. + +A renewed Sandbox Protocol bearer is authenticated even when its credential epoch is unchanged. The supervisor confirms that bearer on the active physical connection and records its fingerprint only after confirmation succeeds, preserving pending streams and the mediation session. Changing the credential epoch still requires an authenticated replacement connection. + Unauthenticated TLS handshakes have a separate bounded asynchronous pool and five-second deadline, never consuming authenticated control slots or threads. The socket broker reserves the TCP control-listener port against workload @@ -301,6 +304,23 @@ middleware registry validates implementation-owned config. The generic registry and chain runner live in `openshell-supervisor-middleware`; first-party implementations live in `openshell-supervisor-middleware-builtins`. +The selected middleware chain can also inspect the final HTTP response before +it returns to the workload. Stages select header-only, whole-body, or streaming +inspection independently. The relay owns response framing when body bytes can +change. Preflight exposes upstream `Content-Length`, `Content-Encoding`, and +`Content-Range` as read-only metadata, while the relay emits final framing +separately from middleware-visible headers. Stage failures follow policy-local +`on_error`; explicit denials always block delivery. Once delivery has started, +blocking aborts the response. + +The network supervisor represents the destination-selected request and response +pair as one `HttpMiddlewareExchange`. It retains the full chain, runner, request +identity, and policy generation while request and response bindings are selected +independently. The HTTP response adapter owns wire parsing, downstream commit +state, generation fences, framing, and transport error classification. The +generic middleware crate owns stage selection, remote stream lifecycle, ordered +body processing, limits, and result validation. + The supervisor installs policy and middleware registry changes as one runtime generation and preserves the last-known-good generation if preparation fails. Policy-only updates reuse the connected registry, so an external middleware diff --git a/architecture/security-policy.md b/architecture/security-policy.md index 4b9dd61334..eca641f4b5 100644 --- a/architecture/security-policy.md +++ b/architecture/security-policy.md @@ -33,8 +33,9 @@ path normalization. Consumers project that syntax into purpose-specific models. `openshell-policy` owns protobuf conversion, composition, merge behavior, raw-protobuf checks, and -validation that depends on runtime components. The existing prover retains its -risk model but uses the same fail-closed parser as the runtime. The parser +validation that depends on runtime components. Both the proposal-risk prover and +standalone containment checker project the shared schema into their own models +using the same fail-closed parser as the runtime. The parser requires `version: 1` and rejects managed annotations and every unknown field before any consumer-specific projection runs. There is no permissive parsing profile: unsupported policy fields always invalidate the document. Middleware `config`, query and persisted-query names, and recursive MCP @@ -368,7 +369,38 @@ may store such a draft, but existing merge validation rejects it when an approval attempts to add it to policy; runtime SSRF protections remain the final enforcement boundary. -## What the prover decides +## Standalone boundary checks + +The standalone `openshell-prover check` command compares a fully composed local +candidate policy with an operator-supplied local boundary. It establishes +`Allowed(candidate) ⊆ Allowed(boundary)` for the model scope reported in its +result. It does not fetch gateway state, compose provider rules, apply policy, +or decide whether an in-boundary change is eligible for automatic approval. + +The initial model covers filesystem paths, L4 network authority, and enforced +REST method and path authority. It returns explicit unsupported or inconclusive +results when a sound decision depends on authority or runtime context outside +the model. The result records the model version and covered domains so callers +can bind a successful check to those semantics. + +Before semantic validation, the checker observes cancellation and applies +aggregate limits across both inputs. Oversized checks therefore return +`resource_limit` without building validation indexes. Cross-protocol ambiguity +validation indexes host and port authority rather than comparing every endpoint +pair, and it checks cancellation while scanning admitted policies. + +The Rust containment API has an explicit extensibility contract: options and +modeled-domain evidence permit additive growth, while the four `CheckResult` +states remain exhaustive and authorization accepts only `Within`. This Rust +source-compatibility boundary is separate from the CLI JSON schema and the +reported containment model version. See the `openshell-prover` crate README for +the supported construction and matching patterns. + +This containment operation is separate from the proposal-risk queries below. +See the [standalone policy prover documentation](../docs/reference/policy-prover.mdx) +for installation, command behavior, model limitations, evidence, and exit codes. + +## What the proposal prover decides The prover answers four formal questions about each proposed policy change. Each "yes" answer becomes its own categorical finding — there is diff --git a/crates/openshell-cli/src/commands/mod.rs b/crates/openshell-cli/src/commands/mod.rs index 8d75cf5ae3..5158a4ac5d 100644 --- a/crates/openshell-cli/src/commands/mod.rs +++ b/crates/openshell-cli/src/commands/mod.rs @@ -4,3 +4,4 @@ pub mod common; pub mod gateway; pub mod provider; +pub mod provider_readiness; diff --git a/crates/openshell-cli/src/commands/provider.rs b/crates/openshell-cli/src/commands/provider.rs index 414b624c92..1c51b25bfc 100644 --- a/crates/openshell-cli/src/commands/provider.rs +++ b/crates/openshell-cli/src/commands/provider.rs @@ -1,6 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +use super::provider_readiness::{ + ProviderMutationExpectation, ProviderWaitOptions, finish_provider_mutation, +}; use crate::color::Colorize; use crate::commands::common::{ format_epoch_ms, format_optional_epoch_ms, parse_credential_expiry_pairs, @@ -19,10 +22,11 @@ use openshell_core::proto::{ LintProviderProfilesRequest, ListProviderProfilesRequest, ListProvidersRequest, ListSandboxProvidersRequest, Provider, ProviderCredentialRefreshRecoveryAction, ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, - ProviderCredentialTokenGrantType, ProviderProfile, ProviderProfileDiagnostic, - ProviderProfileImportItem, RotateProviderCredentialRequest, UpdateProviderProfilesRequest, - UpdateProviderRequest, + ProviderCredentialTokenGrantType, ProviderMutationKind, ProviderProfile, + ProviderProfileDiagnostic, ProviderProfileImportItem, RotateProviderCredentialRequest, + UpdateProviderProfilesRequest, UpdateProviderRequest, }; +use openshell_core::rpc_error::{ERROR_DOMAIN, decode_details}; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; use openshell_providers::{ ProviderTypeProfile, RealDiscoveryContext, detect_provider_from_command, discover_from_profile, @@ -34,6 +38,30 @@ use std::io::IsTerminal; use std::path::{Path, PathBuf}; use tonic::{Code, Status}; +fn provider_mutation_is_uncertain(status: &Status) -> bool { + // Only a validated gateway ErrorInfo identifies a possibly saved mutation. + // Message text, metadata, foreign domains, and malformed details are untrusted. + decode_details(status).is_some_and(|details| { + details.error_info().is_some_and(|info| { + info.domain == ERROR_DOMAIN && info.reason == "CONFIG_OPERATION_STORAGE_UNCERTAIN" + }) + }) +} + +fn provider_mutation_error(status: &Status, operation: &str) -> miette::Report { + if provider_mutation_is_uncertain(status) { + // Emit fixed guidance without chaining the server's potentially sensitive + // message or metadata. An error does not establish that the write rolled back. + miette!( + "provider change may already be saved (CONFIG_OPERATION_STORAGE_UNCERTAIN); \ + readiness receipt could not be recorded. Do not blindly retry the mutation; \ + check provider and sandbox status and reconcile the saved change first." + ) + } else { + miette!("provider {operation} failed ({})", status.code()) + } +} + fn proto_timestamp_ms(timestamp: Option<&prost_types::Timestamp>) -> i64 { timestamp .and_then(|value| openshell_core::time::timestamp_to_millis(value).ok()) @@ -84,13 +112,16 @@ pub async fn sandbox_provider_list( Ok(()) } +/// Save a provider attachment and optionally wait for its installed authority. pub async fn sandbox_provider_attach( server: &str, name: &str, provider: &str, workspace: &str, tls: &TlsOptions, + readiness: ProviderWaitOptions<'_>, ) -> Result<()> { + readiness.validate()?; let mut client = grpc_client(server, tls).await?; // Fetch current sandbox to get resource_version for CAS @@ -100,7 +131,7 @@ pub async fn sandbox_provider_attach( workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await - .into_diagnostic()? + .map_err(|status| miette!("provider attachment lookup failed ({})", status.code()))? .into_inner() .sandbox .ok_or_else(|| miette::miette!("sandbox not found"))?; @@ -109,6 +140,7 @@ pub async fn sandbox_provider_attach( let response = match client .attach_sandbox_provider(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: name.to_string(), provider_name: provider.to_string(), expected_resource_version: resource_version, @@ -117,36 +149,50 @@ pub async fn sandbox_provider_attach( .await { Ok(response) => response.into_inner(), - Err(status) if status.code() == Code::Aborted => { + // Explicit post-save uncertainty takes precedence over a generic retry hint. + Err(status) + if status.code() == Code::Aborted && !provider_mutation_is_uncertain(&status) => + { return Err(miette::miette!( "Failed to attach provider: sandbox was modified by another operation.\n\ Please retry the command." - ) - .with_source_code(status.message().to_string())); + )); } - Err(e) => return Err(e).into_diagnostic(), + Err(error) => return Err(provider_mutation_error(&error, "attachment")), }; - if response.attached { - println!( - "{} Attached provider {} to sandbox {}", - "✓".green().bold(), - provider, - name - ); - } else { - println!("Provider {provider} is already attached to sandbox {name}."); - } - Ok(()) + let receipt = response.receipt.ok_or_else(|| { + miette!( + "gateway did not return a provider receipt; saved attachment cannot establish readiness" + ) + })?; + let mutation_id = receipt.mutation_id.clone(); + finish_provider_mutation( + &client, + &mutation_id, + vec![receipt], + ProviderMutationExpectation { + workspace, + provider_name: provider, + kind: ProviderMutationKind::Attach, + sandbox: Some((name, sandbox.object_id())), + provider: None, + }, + readiness, + ) + .await } +/// Save a provider detachment and optionally wait for future authority revocation. pub async fn sandbox_provider_detach( server: &str, name: &str, provider: &str, workspace: &str, tls: &TlsOptions, + readiness: ProviderWaitOptions<'_>, ) -> Result<()> { + readiness.validate()?; let mut client = grpc_client(server, tls).await?; // Fetch current sandbox to get resource_version for CAS @@ -156,7 +202,7 @@ pub async fn sandbox_provider_detach( workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) .await - .into_diagnostic()? + .map_err(|status| miette!("provider detachment lookup failed ({})", status.code()))? .into_inner() .sandbox .ok_or_else(|| miette::miette!("sandbox not found"))?; @@ -165,6 +211,7 @@ pub async fn sandbox_provider_detach( let response = match client .detach_sandbox_provider(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: name.to_string(), provider_name: provider.to_string(), expected_resource_version: resource_version, @@ -173,27 +220,34 @@ pub async fn sandbox_provider_detach( .await { Ok(response) => response.into_inner(), - Err(status) if status.code() == Code::Aborted => { + // Explicit post-save uncertainty takes precedence over a generic retry hint. + Err(status) + if status.code() == Code::Aborted && !provider_mutation_is_uncertain(&status) => + { return Err(miette::miette!( "Failed to detach provider: sandbox was modified by another operation.\n\ Please retry the command." - ) - .with_source_code(status.message().to_string())); + )); } - Err(e) => return Err(e).into_diagnostic(), + Err(error) => return Err(provider_mutation_error(&error, "detachment")), }; - if response.detached { - println!( - "{} Detached provider {} from sandbox {}", - "✓".green().bold(), - provider, - name - ); - } else { - println!("Provider {provider} was not attached to sandbox {name}."); - } - Ok(()) + let receipt = response.receipt.ok_or_else(|| miette!("gateway did not return a provider receipt; saved detachment cannot establish revocation"))?; + let mutation_id = receipt.mutation_id.clone(); + finish_provider_mutation( + &client, + &mutation_id, + vec![receipt], + ProviderMutationExpectation { + workspace, + provider_name: provider, + kind: ProviderMutationKind::Detach, + sandbox: Some((name, sandbox.object_id())), + provider: None, + }, + readiness, + ) + .await } fn print_provider_attachment_table(providers: &[Provider]) { @@ -477,6 +531,7 @@ async fn auto_create_provider( if let Some(exact_name) = preferred_name { // Explicit name: create with exactly that name, no retries. let request = CreateProviderRequest { + request_id: String::new(), provider: Some(Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { id: String::new(), @@ -525,6 +580,7 @@ async fn auto_create_provider( }; let request = CreateProviderRequest { + request_id: String::new(), provider: Some(Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { id: String::new(), @@ -676,6 +732,7 @@ async fn rollback_provider_create_after_gcloud_adc_failure( ) -> Result<()> { match client .delete_provider(DeleteProviderRequest { + request_id: String::new(), allow_missing: true, name: provider_name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), @@ -705,6 +762,19 @@ async fn rollback_provider_create_after_gcloud_adc_failure( } } +fn provider_profile_lookup_error(status: &Status) -> miette::Report { + // A permission code supports recovery guidance, but cannot distinguish a + // missing membership from an insufficient role. Never expose backend text. + if status.code() == Code::PermissionDenied { + miette!( + "provider profile lookup denied (PERMISSION_DENIED): \ + verify workspace membership and required permissions" + ) + } else { + miette!("provider profile lookup failed ({})", status.code()) + } +} + async fn fetch_provider_profile( client: &mut crate::tls::GrpcClient, provider_type: &str, @@ -729,11 +799,11 @@ async fn fetch_provider_profile( "provider profile '{requested}' not found; import a matching profile before using this provider type" ) } else { - miette::miette!(fallback_status.to_string()) + provider_profile_lookup_error(&fallback_status) } })? } - Err(status) => return Err(miette::miette!(status.to_string())), + Err(status) => return Err(provider_profile_lookup_error(&status)), }; Ok(response) @@ -1020,11 +1090,10 @@ pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> if profile_id.is_empty() { return Err(miette::miette!("provider type is required")); } - let provider_profile = fetch_provider_profile(&mut client, profile_id, profile_workspace) - .await - .map_err(|err| { - miette::miette!("unsupported provider type or profile: {profile_id} ({err})") - })?; + // Lookup already distinguishes absent profiles from permission and transport + // failures; those failures do not establish that the profile is unsupported. + let provider_profile = + fetch_provider_profile(&mut client, profile_id, profile_workspace).await?; let provider_type = provider_profile.id.clone(); let adc_credential_key = if from_gcloud_adc { @@ -1107,6 +1176,7 @@ pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> let response = client .create_provider(CreateProviderRequest { + request_id: String::new(), provider: Some(Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { id: String::new(), @@ -1153,6 +1223,7 @@ pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> if let Err(configure_err) = client .configure_provider_refresh(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: provider_name.clone(), credential_key: adc_credential_key.clone(), strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32, @@ -1178,6 +1249,7 @@ pub async fn provider_create_with_options(options: ProviderCreateOptions<'_>) -> if let Err(rotate_err) = client .rotate_provider_credential(RotateProviderCredentialRequest { + request_id: String::new(), provider: provider_name.clone(), credential_key: adc_credential_key, workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), @@ -1601,6 +1673,7 @@ pub async fn provider_profile_import( if !items.is_empty() { let response = client .import_provider_profiles(ImportProviderProfilesRequest { + request_id: String::new(), profiles: items, workspace: workspace.to_string(), }) @@ -1650,6 +1723,7 @@ pub async fn provider_profile_update( .map_or(0, |profile| profile.resource_version); let response = client .update_provider_profiles(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(item), expected_resource_version, id: id.to_string(), @@ -1714,6 +1788,7 @@ pub async fn provider_profile_delete( for id in ids { let response = match client .delete_provider_profile(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: true, id: id.clone(), workspace: workspace.to_string(), @@ -1826,6 +1901,7 @@ pub async fn provider_refresh_config( let mut client = grpc_client(server, tls).await?; let status = client .configure_provider_refresh(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: input.name.to_string(), credential_key: input.credential_key.to_string(), strategy: strategy as i32, @@ -1863,6 +1939,7 @@ pub async fn provider_rotate( let mut client = grpc_client(server, tls).await?; let status = client .rotate_provider_credential(RotateProviderCredentialRequest { + request_id: String::new(), provider: name.to_string(), credential_key: credential_key.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), @@ -1900,6 +1977,7 @@ pub async fn provider_refresh_delete( let mut client = grpc_client(server, tls).await?; let response = client .delete_provider_refresh(DeleteProviderRefreshRequest { + request_id: String::new(), allow_missing: true, provider: name.to_string(), credential_key: credential_key.to_string(), @@ -2223,6 +2301,7 @@ fn print_provider_type_row( ); } +/// Credential update inputs and observation choices for all attached sandboxes. pub struct ProviderUpdateOptions<'a> { pub server: &'a str, pub name: &'a str, @@ -2233,8 +2312,11 @@ pub struct ProviderUpdateOptions<'a> { pub credential_expires_at: &'a [String], pub workspace: &'a str, pub tls: &'a TlsOptions, + /// Bound observation of the sandbox target set selected by the update. + pub readiness: ProviderWaitOptions<'a>, } +/// Update provider credentials and report each selected sandbox independently. pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { let ProviderUpdateOptions { server, @@ -2246,7 +2328,9 @@ pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { credential_expires_at, workspace, tls, + readiness, } = options; + readiness.validate()?; if from_existing && !credentials.is_empty() { return Err(miette::miette!( @@ -2284,7 +2368,7 @@ pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { { None } - Err(status) => return Err(status).into_diagnostic(), + Err(status) => return Err(miette!("provider update lookup failed ({})", status.code())), }; if existing.is_none() && (from_existing || from_oidc_token) { @@ -2337,6 +2421,7 @@ pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { let response = client .update_provider(UpdateProviderRequest { + request_id: String::new(), provider: Some(Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { id: String::new(), @@ -2373,19 +2458,28 @@ pub async fn provider_update(options: ProviderUpdateOptions<'_>) -> Result<()> { clear_credential_expiration_keys, }) .await - .into_diagnostic()?; - - let provider = response - .into_inner() - .provider - .ok_or_else(|| miette::miette!("provider missing from response"))?; + .map_err(|error| provider_mutation_error(&error, "update"))?; - println!( - "{} Updated provider {}", - "✓".green().bold(), - provider.object_name() - ); - Ok(()) + let response = response.into_inner(); + if response.mutation_id.is_empty() { + return Err(miette!( + "gateway did not return a provider mutation receipt; saved credentials cannot establish readiness" + )); + } + finish_provider_mutation( + &client, + &response.mutation_id, + response.target_receipts, + ProviderMutationExpectation { + workspace, + provider_name: name, + kind: ProviderMutationKind::Update, + sandbox: None, + provider: response.provider.as_ref(), + }, + readiness, + ) + .await } pub async fn provider_delete( @@ -2399,6 +2493,7 @@ pub async fn provider_delete( for name in names { let response = match client .delete_provider(DeleteProviderRequest { + request_id: String::new(), allow_missing: true, name: name.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), diff --git a/crates/openshell-cli/src/commands/provider_readiness.rs b/crates/openshell-cli/src/commands/provider_readiness.rs new file mode 100644 index 0000000000..c0472853b1 --- /dev/null +++ b/crates/openshell-cli/src/commands/provider_readiness.rs @@ -0,0 +1,584 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Secret-free provider receipts, status rendering, and bounded CLI waits. + +use crate::tls::{GrpcClient, TlsOptions, grpc_client}; +use futures::{StreamExt, stream}; +use miette::{IntoDiagnostic, Result, miette}; +use openshell_core::proto::{ + GetSandboxProviderStatusRequest, Provider, ProviderMutationKind, ProviderMutationReceipt, + ProviderReadinessReason, ProviderReadinessState, ProviderReadinessStatus, +}; +use openshell_sdk::provider_readiness::{ + ProviderWaitOutcome, persisted_status, provider_status, provider_wait_deadline, + validate_provider_receipt, wait_for_provider_status_until, +}; +use std::collections::HashSet; +use std::time::Duration; +use tokio::time::Instant; + +const PROVIDER_WAIT_CONCURRENCY: usize = 16; + +/// Output and deadline choices shared by provider mutation and status commands. +#[derive(Clone, Copy)] +pub struct ProviderWaitOptions<'a> { + /// Wait for current runtime installation after saving the desired mutation. + pub wait: bool, + /// One total deadline for all selected sandbox observations. + pub timeout: Duration, + /// CLI output format: table, JSON, or YAML. + pub output: &'a str, +} + +impl Default for ProviderWaitOptions<'_> { + fn default() -> Self { + Self { + wait: false, + timeout: Duration::from_secs(30), + output: "table", + } + } +} + +impl ProviderWaitOptions<'_> { + /// Reject invalid wait settings before performing a provider mutation. + pub fn validate(self) -> Result<()> { + provider_wait_deadline(self.timeout).into_diagnostic()?; + if !matches!(self.output, "table" | "json" | "yaml") { + return Err(miette!("unsupported provider status output format")); + } + Ok(()) + } +} + +struct DisplayStatus { + status: ProviderReadinessStatus, + outcome: &'static str, + complete: bool, +} + +/// Caller-selected authority that every returned mutation receipt must retain. +#[derive(Clone, Copy)] +pub(super) struct ProviderMutationExpectation<'a> { + /// Workspace explicitly selected by the command. + pub workspace: &'a str, + /// Provider name explicitly selected by the command. + pub provider_name: &'a str, + /// Operation submitted to the gateway. + pub kind: ProviderMutationKind, + /// Requested sandbox name and previously fetched object ID for attach/detach. + pub sandbox: Option<(&'a str, &'a str)>, + /// Published provider object returned by an update, including its revision. + pub provider: Option<&'a Provider>, +} + +fn validate_mutation_receipts( + mutation_id: &str, + receipts: &[ProviderMutationReceipt], + expected: &ProviderMutationExpectation<'_>, +) -> Result<()> { + let invalid = || miette!("gateway returned an invalid provider mutation receipt"); + if mutation_id.is_empty() || expected.workspace.is_empty() || expected.provider_name.is_empty() + { + return Err(invalid()); + } + let provider = match expected.kind { + ProviderMutationKind::Attach | ProviderMutationKind::Detach => { + if receipts.len() != 1 + || expected + .sandbox + .is_none_or(|(name, id)| name.is_empty() || id.is_empty()) + { + return Err(invalid()); + } + None + } + ProviderMutationKind::Update => { + let metadata = expected + .provider + .and_then(|provider| provider.metadata.as_ref()) + .ok_or_else(invalid)?; + if metadata.id.is_empty() + || metadata.name != expected.provider_name + || metadata.workspace != expected.workspace + { + return Err(invalid()); + } + Some(metadata) + } + ProviderMutationKind::Unspecified | ProviderMutationKind::Observe => return Err(invalid()), + }; + let mut receipt_ids = HashSet::new(); + let mut sandbox_ids = HashSet::new(); + for receipt in receipts { + validate_provider_receipt(receipt).into_diagnostic()?; + let desired = receipt.desired.as_ref().ok_or_else(invalid)?; + // Validate the complete batch before polling or printing saved intent. + // Otherwise a substituted receipt can redirect a wait to another scope. + if receipt.mutation_id != mutation_id + || receipt.workspace != expected.workspace + || receipt.provider_name != expected.provider_name + || receipt.kind != i32::from(expected.kind) + || !receipt_ids.insert(receipt.receipt_id.as_str()) + || !sandbox_ids.insert(desired.sandbox_id.as_str()) + || expected + .sandbox + .is_some_and(|(name, id)| desired.sandbox_name != name || desired.sandbox_id != id) + || provider.is_some_and(|provider| { + desired.provider_id != provider.id + || desired.provider_resource_version != provider.resource_version + }) + { + return Err(invalid()); + } + } + Ok(()) +} + +/// Display persisted targets and optionally wait for each original receipt. +/// +/// Every target is reported even when another target fails. Concurrency is +/// bounded and all requests share one deadline, including queued targets. +pub(super) async fn finish_provider_mutation( + client: &GrpcClient, + mutation_id: &str, + receipts: Vec, + expected: ProviderMutationExpectation<'_>, + options: ProviderWaitOptions<'_>, +) -> Result<()> { + options.validate()?; + validate_mutation_receipts(mutation_id, &receipts, &expected)?; + let deadline = provider_wait_deadline(options.timeout).into_diagnostic()?; + let statuses = receipts.into_iter().map(persisted_status).collect(); + let results = if options.wait { + wait_for_mutation_statuses(client, statuses, deadline).await + } else { + statuses + .into_iter() + .map(|status| DisplayStatus { + status, + outcome: "not_requested", + complete: false, + }) + .collect() + }; + print_statuses(mutation_id, &results, options.output)?; + if options.wait && results.iter().any(|result| !result.complete) { + return Err(miette!( + "provider readiness wait did not complete for every selected sandbox; inspect the reported outcomes" + )); + } + Ok(()) +} + +async fn wait_for_mutation_statuses( + client: &GrpcClient, + statuses: Vec, + deadline: Instant, +) -> Vec { + let mut pending = statuses.into_iter().enumerate().collect::>(); + let mut results = Vec::with_capacity(pending.len()); + while !pending.is_empty() && Instant::now() < deadline { + // Divide the remaining time among actual queued batches. When every + // target fits in one batch, healthy but slow RPCs get the full deadline; + // queued targets still get a turn if the preceding batch stalls. + let batches = + u32::try_from(pending.len().div_ceil(PROVIDER_WAIT_CONCURRENCY)).unwrap_or(u32::MAX); + let slice = deadline.saturating_duration_since(Instant::now()) / batches; + if slice.is_zero() { + break; + } + let round = stream::iter(pending.into_iter().map(|(index, status)| { + let mut client = client.clone(); + async move { + let slice_deadline = (Instant::now() + slice).min(deadline); + let result = + wait_for_provider_status_until(&mut client, &status, slice_deadline).await; + (index, status, result) + } + })) + .buffer_unordered(PROVIDER_WAIT_CONCURRENCY) + .collect::>() + .await; + pending = Vec::new(); + for (index, previous, result) in round { + match result { + // The SDK pins the receipt in this status and retains its last + // observation. Only unfinished targets enter the next round. + Ok(result) + if result.outcome == ProviderWaitOutcome::TimedOut + && Instant::now() < deadline => + { + pending.push((index, result.status)); + } + Ok(result) => { + results.push(( + index, + DisplayStatus { + status: result.status, + outcome: match result.outcome { + ProviderWaitOutcome::Complete => "complete", + ProviderWaitOutcome::TimedOut => "timed_out", + ProviderWaitOutcome::Terminal => "terminal", + }, + complete: result.outcome == ProviderWaitOutcome::Complete, + }, + )); + } + // A transport error cannot prove installation failure. Preserve + // the last observation and expose only the safe error category. + Err(_) => { + results.push(( + index, + DisplayStatus { + status: previous, + outcome: "observation_error", + complete: false, + }, + )); + } + } + } + } + results.extend(pending.into_iter().map(|(index, status)| { + ( + index, + DisplayStatus { + status, + outcome: "timed_out", + complete: false, + }, + ) + })); + // Fair polling must not change the command's stable target output order. + results.sort_unstable_by_key(|(index, _)| *index); + results.into_iter().map(|(_, result)| result).collect() +} + +/// Show desired/observed provider state, optionally waiting for that exact state. +pub async fn sandbox_provider_status( + server: &str, + name: &str, + provider: &str, + receipt_id: &str, + workspace: &str, + tls: &TlsOptions, + options: ProviderWaitOptions<'_>, +) -> Result<()> { + options.validate()?; + let mut client = grpc_client(server, tls).await?; + let deadline = provider_wait_deadline(options.timeout).into_diagnostic()?; + let status = tokio::time::timeout_at( + deadline, + provider_status( + &mut client, + GetSandboxProviderStatusRequest { + sandbox_name: name.to_string(), + provider_name: provider.to_string(), + receipt_id: receipt_id.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), + }, + ), + ) + .await + .map_err(|_| miette!("provider status request timed out"))? + .into_diagnostic()?; + let receipt = status + .receipt + .as_ref() + .ok_or_else(|| miette!("gateway returned no provider receipt"))?; + let mutation_id = receipt.mutation_id.clone(); + let result = if options.wait { + let result = wait_for_provider_status_until(&mut client, &status, deadline) + .await + .into_diagnostic()?; + DisplayStatus { + status: result.status, + outcome: match result.outcome { + ProviderWaitOutcome::Complete => "complete", + ProviderWaitOutcome::TimedOut => "timed_out", + ProviderWaitOutcome::Terminal => "terminal", + }, + complete: result.outcome == ProviderWaitOutcome::Complete, + } + } else { + DisplayStatus { + status, + outcome: "not_requested", + complete: false, + } + }; + let complete = result.complete; + print_statuses(&mutation_id, &[result], options.output)?; + if options.wait && !complete { + return Err(miette!( + "provider readiness wait did not complete; inspect the reported outcome" + )); + } + Ok(()) +} + +fn state_label(state: i32) -> &'static str { + match ProviderReadinessState::try_from(state) { + Ok(ProviderReadinessState::Persisted) => "persisted", + Ok(ProviderReadinessState::Pending) => "pending", + Ok(ProviderReadinessState::Ready) => "ready", + Ok(ProviderReadinessState::Withheld) => "withheld", + Ok(ProviderReadinessState::Revoked) => "revoked", + Ok(ProviderReadinessState::Failed) => "failed", + Ok(ProviderReadinessState::Superseded) => "superseded", + _ => "unknown", + } +} + +fn reason_label(reason: i32) -> String { + ProviderReadinessReason::try_from(reason).map_or_else( + |_| "unknown".to_string(), + |reason| { + reason + .as_str_name() + .trim_start_matches("PROVIDER_READINESS_REASON_") + .to_ascii_lowercase() + }, + ) +} + +fn receipt_json(receipt: &ProviderMutationReceipt) -> serde_json::Value { + let desired = receipt.desired.as_ref().map(|desired| { + serde_json::json!({ + "sandbox_id": desired.sandbox_id, + "sandbox_name": desired.sandbox_name, + "attachment_epoch": desired.attachment_epoch, + "provider_id": desired.provider_id, + "provider_resource_version": desired.provider_resource_version.to_string(), + "provider_env_revision": desired.provider_env_revision.to_string(), + "config_revision": desired.config_revision.to_string(), + "policy_hash": desired.policy_hash, + }) + }); + serde_json::json!({ + "receipt_id": receipt.receipt_id, + "mutation_id": receipt.mutation_id, + "provider_name": receipt.provider_name, + "workspace": receipt.workspace, + "kind": receipt.kind().as_str_name().trim_start_matches("PROVIDER_MUTATION_KIND_").to_ascii_lowercase(), + "desired": desired, + "persisted_time": receipt.persisted_time.as_ref().map(ToString::to_string), + }) +} + +fn status_json(result: &DisplayStatus) -> serde_json::Value { + let observed = result.status.observed.as_ref().map(|observed| { + serde_json::json!({ + "session_id": observed.session_id, + "sequence": observed.sequence.to_string(), + "attachment_epoch": observed.attachment_epoch, + "provider_env_revision": observed.provider_env_revision.to_string(), + "config_revision": observed.config_revision.to_string(), + "policy_hash": observed.policy_hash, + "credentials_installed": observed.credentials_installed, + "policy_active": observed.policy_active, + "launch_environment_installed": observed.launch_environment_installed, + "process_instance_id": observed.process_instance_id, + "reason": reason_label(observed.reason), + }) + }); + serde_json::json!({ + "receipt": result.status.receipt.as_ref().map(receipt_json), + "state": state_label(result.status.state), + "reason": reason_label(result.status.reason), + "observed": observed, + "network_instance_id": result.status.network_instance_id, + "observed_time": result.status.observed_time.as_ref().map(ToString::to_string), + "evaluated_time": result.status.evaluated_time.as_ref().map(ToString::to_string), + "wait_outcome": result.outcome, + }) +} + +fn print_statuses(mutation_id: &str, results: &[DisplayStatus], output: &str) -> Result<()> { + let value = serde_json::json!({ + "mutation_id": mutation_id, + "targets": results.iter().map(status_json).collect::>(), + }); + if crate::output::print_output_single(output, &value, Clone::clone)? { + return Ok(()); + } + if results.is_empty() { + println!("Provider mutation {mutation_id} persisted; no attached sandboxes were selected."); + return Ok(()); + } + for result in results { + let Some(receipt) = result.status.receipt.as_ref() else { + continue; + }; + let sandbox = receipt + .desired + .as_ref() + .map_or("unknown", |desired| desired.sandbox_name.as_str()); + println!( + "{} / {}: {} ({})", + sandbox, + receipt.provider_name, + state_label(result.status.state), + reason_label(result.status.reason) + ); + println!( + " Receipt: {}", + if receipt.receipt_id.is_empty() { + "current state" + } else { + &receipt.receipt_id + } + ); + println!( + " Persisted: {}", + receipt + .persisted_time + .as_ref() + .map_or_else(|| "-".to_string(), ToString::to_string) + ); + if let Some(observed) = result.status.observed.as_ref() { + println!( + " Installed: credentials={}, policy={}, future process environment={}", + observed.credentials_installed, + observed.policy_active, + observed.launch_environment_installed + ); + } + if result.outcome != "not_requested" { + println!(" Wait: {}", result.outcome); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::ProviderDesiredIdentity; + + #[test] + fn mutation_receipts_reject_duplicate_targets_and_allow_initial_fingerprints() { + let provider = Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: "provider-id".to_string(), + name: "provider".to_string(), + workspace: "default".to_string(), + resource_version: 0, + ..Default::default() + }), + ..Default::default() + }; + let expected = ProviderMutationExpectation { + workspace: "default", + provider_name: "provider", + kind: ProviderMutationKind::Update, + sandbox: None, + provider: Some(&provider), + }; + let receipt = ProviderMutationReceipt { + receipt_id: "receipt".to_string(), + mutation_id: "mutation".to_string(), + provider_name: "provider".to_string(), + workspace: "default".to_string(), + kind: ProviderMutationKind::Update.into(), + persisted_time: Some(openshell_core::time::timestamp_from_millis(1).unwrap()), + desired: Some(ProviderDesiredIdentity { + sandbox_id: "sandbox-id".to_string(), + sandbox_name: "sandbox".to_string(), + provider_id: "provider-id".to_string(), + ..Default::default() + }), + }; + assert!( + validate_mutation_receipts("mutation", std::slice::from_ref(&receipt), &expected) + .is_ok() + ); + assert!(validate_mutation_receipts("mutation", &[], &expected).is_ok()); + let mut duplicate = receipt.clone(); + duplicate.receipt_id = "other-receipt".to_string(); + assert!( + validate_mutation_receipts("mutation", &[receipt.clone(), duplicate], &expected) + .is_err() + ); + let mut duplicate = receipt.clone(); + duplicate + .desired + .as_mut() + .expect("desired identity") + .sandbox_id = "other-sandbox".to_string(); + assert!(validate_mutation_receipts("mutation", &[receipt, duplicate], &expected).is_err()); + assert!( + validate_mutation_receipts( + "mutation", + &[], + &ProviderMutationExpectation { + provider: None, + ..expected + } + ) + .is_err() + ); + } + + #[test] + fn structured_status_renders_rfc3339_timestamps_without_losing_nanos() { + let timestamp = prost_types::Timestamp { + seconds: 1_000, + nanos: 123_456_789, + }; + let receipt = ProviderMutationReceipt { + persisted_time: Some(timestamp), + ..Default::default() + }; + let mut status = persisted_status(receipt); + status.observed_time = Some(timestamp); + status.evaluated_time = Some(timestamp); + let value = status_json(&DisplayStatus { + status, + outcome: "not_requested", + complete: false, + }); + let expected = "1970-01-01T00:16:40.123456789Z"; + assert_eq!(value["receipt"]["persisted_time"], expected); + assert_eq!(value["observed_time"], expected); + assert_eq!(value["evaluated_time"], expected); + assert!(value["receipt"].get("persisted_at_ms").is_none()); + assert!(value.get("observed_at_ms").is_none()); + assert!(value.get("evaluated_at_ms").is_none()); + + let value = status_json(&DisplayStatus { + status: persisted_status(ProviderMutationReceipt::default()), + outcome: "not_requested", + complete: false, + }); + assert!(value["receipt"]["persisted_time"].is_null()); + assert!(value["observed_time"].is_null()); + assert!(value["evaluated_time"].is_null()); + } + + #[test] + fn structured_status_preserves_opaque_revisions_and_separates_timeout() { + let receipt = ProviderMutationReceipt { + desired: Some(ProviderDesiredIdentity { + provider_env_revision: u64::MAX, + ..Default::default() + }), + ..Default::default() + }; + let value = status_json(&DisplayStatus { + status: persisted_status(receipt), + outcome: "timed_out", + complete: false, + }); + assert_eq!(value["state"], "persisted"); + assert_eq!(value["wait_outcome"], "timed_out"); + assert_eq!( + value["receipt"]["desired"]["provider_env_revision"], + u64::MAX.to_string() + ); + assert!(value.get("environment").is_none()); + assert!(value.get("load_error").is_none()); + } +} diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index fdec4ce7e5..a17d4c2e92 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -944,6 +944,9 @@ enum ProviderCommands { /// Credential expiry (`KEY=TIMESTAMP`). Accepts epoch milliseconds or RFC3339. A zero timestamp clears expiry. #[arg(long = "credential-expires-at", value_name = "KEY=TIMESTAMP")] credential_expires_at: Vec, + + #[command(flatten)] + readiness: ProviderReadinessArgs, }, /// Delete providers by name. @@ -1624,6 +1627,32 @@ enum SandboxCommands { Template(SandboxTemplateCommands), } +/// Common observation flags; the deadline starts after the mutation is saved. +#[derive(clap::Args, Debug)] +struct ProviderReadinessArgs { + /// Wait until the sandbox applies the credentials, policy, and environment for new processes. + #[arg(long)] + wait: bool, + + /// Maximum wait in seconds after saving the change, shared by all selected sandboxes. + #[arg(long, default_value_t = 30, value_parser = clap::value_parser!(u64).range(1..=3600))] + timeout: u64, + + /// Output format; JSON and YAML include change IDs and results for each sandbox. + #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)] + output: OutputFormat, +} + +impl ProviderReadinessArgs { + fn options(&self) -> run::ProviderWaitOptions<'_> { + run::ProviderWaitOptions { + wait: self.wait, + timeout: std::time::Duration::from_secs(self.timeout), + output: self.output.as_str(), + } + } +} + #[derive(Subcommand, Debug)] enum SandboxProviderCommands { /// List providers attached to a sandbox. @@ -1648,6 +1677,9 @@ enum SandboxProviderCommands { /// Provider name to attach. #[arg(add = ArgValueCompleter::new(completers::complete_provider_names))] provider: String, + + #[command(flatten)] + readiness: ProviderReadinessArgs, }, /// Detach a provider from a sandbox. @@ -1660,6 +1692,28 @@ enum SandboxProviderCommands { /// Provider name to detach. #[arg(add = ArgValueCompleter::new(completers::complete_provider_names))] provider: String, + + #[command(flatten)] + readiness: ProviderReadinessArgs, + }, + + /// Check whether a sandbox has applied a provider change. + #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] + Status { + /// Sandbox name. + #[arg(add = ArgValueCompleter::new(completers::complete_sandbox_names))] + name: String, + + /// Provider whose attachment or revocation is being inspected. + #[arg(add = ArgValueCompleter::new(completers::complete_provider_names))] + provider: String, + + /// Change ID returned by attach, detach, or update; omitted means the latest saved state. + #[arg(long = "receipt")] + receipt: Option, + + #[command(flatten)] + readiness: ProviderReadinessArgs, }, } @@ -3356,23 +3410,50 @@ async fn run_async() -> Result<()> { ) .await?; } - SandboxProviderCommands::Attach { name, provider } => { + SandboxProviderCommands::Attach { + name, + provider, + readiness, + } => { run::sandbox_provider_attach( endpoint, &name, &provider, &cli.workspace, &tls, + readiness.options(), ) .await?; } - SandboxProviderCommands::Detach { name, provider } => { + SandboxProviderCommands::Detach { + name, + provider, + readiness, + } => { run::sandbox_provider_detach( endpoint, &name, &provider, &cli.workspace, &tls, + readiness.options(), + ) + .await?; + } + SandboxProviderCommands::Status { + name, + provider, + receipt, + readiness, + } => { + run::sandbox_provider_status( + endpoint, + &name, + &provider, + receipt.as_deref().unwrap_or_default(), + &cli.workspace, + &tls, + readiness.options(), ) .await?; } @@ -3733,6 +3814,7 @@ async fn run_async() -> Result<()> { credentials, config, credential_expires_at, + readiness, } => { run::provider_update(run::ProviderUpdateOptions { server: endpoint, @@ -3744,6 +3826,7 @@ async fn run_async() -> Result<()> { credential_expires_at: &credential_expires_at, workspace: &cli.workspace, tls: &tls, + readiness: readiness.options(), }) .await?; } @@ -4030,7 +4113,9 @@ mod tests { let Some(Commands::Sandbox { command: - Some(SandboxCommands::Provider(SandboxProviderCommands::Attach { name, provider })), + Some(SandboxCommands::Provider(SandboxProviderCommands::Attach { + name, provider, .. + })), }) = cli.command else { panic!("expected sandbox provider attach command"); @@ -4040,6 +4125,68 @@ mod tests { assert_eq!(provider, "work-github"); } + #[test] + fn provider_readiness_commands_have_bounded_waits_and_structured_output() { + for action in ["attach", "detach", "status"] { + let cli = Cli::try_parse_from([ + "openshell", + "sandbox", + "provider", + action, + "sandbox", + "provider", + "--wait", + "--timeout", + "45", + "--output", + "json", + ]) + .expect("readiness flags should parse"); + let Some(Commands::Sandbox { + command: Some(SandboxCommands::Provider(command)), + }) = cli.command + else { + panic!("expected provider command") + }; + let (SandboxProviderCommands::Attach { readiness, .. } + | SandboxProviderCommands::Detach { readiness, .. } + | SandboxProviderCommands::Status { readiness, .. }) = command + else { + panic!("expected readiness command"); + }; + assert!(readiness.wait); + assert_eq!(readiness.timeout, 45); + assert_eq!(readiness.output.as_str(), "json"); + } + for timeout in ["0", "3601"] { + assert!( + Cli::try_parse_from([ + "openshell", + "provider", + "update", + "provider", + "--wait", + "--timeout", + timeout, + ]) + .is_err() + ); + } + assert!( + Cli::try_parse_from([ + "openshell", + "sandbox", + "provider", + "status", + "sandbox", + "provider", + "--receipt", + "receipt-id", + ]) + .is_ok() + ); + } + #[test] fn completions_policy_flag_falls_back_to_file_paths() { let temp = tempfile::tempdir().expect("failed to create tempdir"); diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 9dbbe763b5..817b7e7eaf 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -32,6 +32,7 @@ pub use crate::commands::provider::{ provider_refresh_status, provider_rotate, provider_update, sandbox_provider_attach, sandbox_provider_detach, sandbox_provider_list, }; +pub use crate::commands::provider_readiness::{ProviderWaitOptions, sandbox_provider_status}; use crate::color::Colorize; use crate::policy_update::build_policy_update_plan; @@ -642,6 +643,7 @@ pub async fn sandbox_create( )]) }; let request = CreateSandboxRequest { + request_id: String::new(), spec: Some(SandboxSpec { resource_requirements, environment: if template.is_none() { @@ -2685,6 +2687,7 @@ pub async fn sandbox_template_create( let mut client = grpc_client(server, tls).await?; let response = client .create_sandbox_template(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(SandboxWorkloadTemplate { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { id: String::new(), @@ -2872,6 +2875,7 @@ pub async fn sandbox_template_delete( for name in names { let response = client .delete_sandbox_template(DeleteSandboxTemplateRequest { + request_id: String::new(), allow_missing: true, name: name.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), @@ -3300,6 +3304,7 @@ pub async fn sandbox_delete( let response = match client .delete_sandbox(DeleteSandboxRequest { + request_id: String::new(), allow_missing: true, name: name.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), @@ -3360,6 +3365,7 @@ pub async fn sandbox_stop( let mut client = grpc_client(server, tls).await?; let sandbox = client .stop_sandbox(StopSandboxRequest { + request_id: String::new(), name: name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) @@ -3383,6 +3389,7 @@ pub async fn sandbox_start( let mut client = grpc_client(server, tls).await?; let sandbox = client .start_sandbox(StartSandboxRequest { + request_id: String::new(), name: name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) @@ -3481,6 +3488,7 @@ pub async fn service_expose( let mut client = grpc_client(server, tls).await?; let response = client .expose_service(ExposeServiceRequest { + request_id: String::new(), sandbox: sandbox.to_string(), service: service.to_string(), target_port: u32::from(target_port), @@ -3607,6 +3615,7 @@ pub async fn service_delete( let mut client = grpc_client(server, tls).await?; let response = client .delete_service(DeleteServiceRequest { + request_id: String::new(), allow_missing: false, sandbox: sandbox.to_string(), service: service.to_string(), @@ -3827,6 +3836,7 @@ pub async fn workspace_create( let mut client = grpc_client(server, tls).await?; let response = client .create_workspace(CreateWorkspaceRequest { + request_id: String::new(), name: name.to_string(), labels, }) @@ -3981,6 +3991,7 @@ pub async fn workspace_delete(server: &str, names: &[String], tls: &TlsOptions) for name in names { let response = client .delete_workspace(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: name.clone(), }) @@ -4018,6 +4029,7 @@ pub async fn workspace_member_add( let mut client = grpc_client(server, tls).await?; let response = client .add_workspace_member(AddWorkspaceMemberRequest { + request_id: String::new(), workspace: workspace.to_string(), principal_subject: subject.to_string(), role: role_val.into(), @@ -4052,6 +4064,7 @@ pub async fn workspace_member_remove( let mut client = grpc_client(server, tls).await?; let response = client .remove_workspace_member(RemoveWorkspaceMemberRequest { + request_id: String::new(), allow_missing: true, workspace: workspace.to_string(), principal_subject: subject.to_string(), @@ -5876,6 +5889,7 @@ pub async fn sandbox_draft_approve( let response = client .approve_draft_chunk(ApproveDraftChunkRequest { + request_id: String::new(), name: name.to_string(), chunk_id: chunk_id.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), @@ -5908,6 +5922,7 @@ pub async fn sandbox_draft_reject( client .reject_draft_chunk(RejectDraftChunkRequest { + request_id: String::new(), name: name.to_string(), chunk_id: chunk_id.to_string(), reason: reason.to_string(), @@ -5949,6 +5964,7 @@ pub async fn sandbox_draft_approve_all( let response = client .approve_all_draft_chunks(ApproveAllDraftChunksRequest { + request_id: String::new(), name: name.to_string(), include_security_flagged, workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), @@ -5980,6 +5996,7 @@ pub async fn sandbox_draft_clear( let response = client .clear_draft_chunks(ClearDraftChunksRequest { + request_id: String::new(), name: name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector(workspace)), }) diff --git a/crates/openshell-cli/tests/ensure_providers_integration.rs b/crates/openshell-cli/tests/ensure_providers_integration.rs index 017a165ff3..f1a41fe227 100644 --- a/crates/openshell-cli/tests/ensure_providers_integration.rs +++ b/crates/openshell-cli/tests/ensure_providers_integration.rs @@ -215,6 +215,24 @@ impl OpenShell for TestOpenShell { Ok(Response::new(GetGatewayConfigResponse::default())) } + async fn get_sandbox_provider_status( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider readiness is not exercised by this mock", + )) + } + + async fn report_provider_readiness( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider installation reports are not exercised by this mock", + )) + } + async fn get_sandbox_provider_environment( &self, _request: tonic::Request, @@ -296,6 +314,7 @@ impl OpenShell for TestOpenShell { providers.insert(provider_name, provider.clone()); Ok(Response::new(ProviderResponse { provider: Some(provider), + ..Default::default() })) } @@ -311,6 +330,7 @@ impl OpenShell for TestOpenShell { .ok_or_else(|| Status::not_found("provider not found"))?; Ok(Response::new(ProviderResponse { provider: Some(provider), + ..Default::default() })) } @@ -463,6 +483,7 @@ impl OpenShell for TestOpenShell { providers.insert(updated_name, updated.clone()); Ok(Response::new(ProviderResponse { provider: Some(updated), + ..Default::default() })) } async fn get_provider_refresh_status( diff --git a/crates/openshell-cli/tests/mtls_integration.rs b/crates/openshell-cli/tests/mtls_integration.rs index fa732c3a03..e188d541f1 100644 --- a/crates/openshell-cli/tests/mtls_integration.rs +++ b/crates/openshell-cli/tests/mtls_integration.rs @@ -186,6 +186,24 @@ impl OpenShell for TestOpenShell { )) } + async fn get_sandbox_provider_status( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider readiness is not exercised by this mock", + )) + } + + async fn report_provider_readiness( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider installation reports are not exercised by this mock", + )) + } + async fn get_sandbox_provider_environment( &self, _request: tonic::Request, diff --git a/crates/openshell-cli/tests/provider_commands_integration.rs b/crates/openshell-cli/tests/provider_commands_integration.rs index 2c9b9ba005..182c46d3e6 100644 --- a/crates/openshell-cli/tests/provider_commands_integration.rs +++ b/crates/openshell-cli/tests/provider_commands_integration.rs @@ -17,27 +17,63 @@ use openshell_core::proto::{ ExecSandboxInput, ExecSandboxRequest, GatewayMessage, GetGatewayConfigRequest, GetGatewayConfigResponse, GetProviderRefreshStatusRequest, GetProviderRefreshStatusResponse, GetProviderRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, - GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, GetSandboxRequest, + GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, + GetSandboxProviderStatusRequest, GetSandboxProviderStatusResponse, GetSandboxRequest, HealthRequest, HealthResponse, ListProvidersRequest, ListProvidersResponse, ListSandboxProvidersRequest, ListSandboxProvidersResponse, ListSandboxesRequest, ListSandboxesResponse, Provider, ProviderCredentialRefresh, ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrant, - ProviderCredentialTokenGrantSubjectToken, ProviderCredentialTokenGrantType, ProviderProfile, - ProviderProfileCredential, ProviderProfileDiscovery, ProviderResponse, RevokeSshSessionRequest, - RevokeSshSessionResponse, RotateProviderCredentialRequest, RotateProviderCredentialResponse, - Sandbox, SandboxResponse, SandboxStreamEvent, ServiceStatus, SettingValue, SupervisorMessage, - UpdateProviderRequest, WatchSandboxRequest, + ProviderCredentialTokenGrantSubjectToken, ProviderCredentialTokenGrantType, + ProviderDesiredIdentity, ProviderMutationKind, ProviderMutationReceipt, ProviderProfile, + ProviderProfileCredential, ProviderProfileDiscovery, ProviderReadinessObservation, + ProviderReadinessReason, ProviderReadinessState, ProviderReadinessStatus, ProviderResponse, + RevokeSshSessionRequest, RevokeSshSessionResponse, RotateProviderCredentialRequest, + RotateProviderCredentialResponse, Sandbox, SandboxResponse, SandboxStreamEvent, ServiceStatus, + SettingValue, SupervisorMessage, UpdateProviderRequest, WatchSandboxRequest, }; +use openshell_core::rpc_error::{ERROR_DOMAIN, ErrorDetails, StatusExt}; use openshell_core::{ObjectId, ObjectName}; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Duration; use tempfile::TempDir; use tokio::net::TcpListener; use tokio::sync::{Mutex, mpsc}; use tokio_stream::wrappers::TcpListenerStream; use tonic::transport::{Certificate as TlsCertificate, Identity, Server, ServerTlsConfig}; -use tonic::{Response, Status}; +use tonic::{Code, Response, Status}; + +type ReadinessScript = HashMap>; +type ReceiptCorruption = fn(&mut ProviderMutationReceipt); + +#[derive(Clone)] +enum ReadinessReply { + Status(Box), + DelayedStatus(Duration, Box), + Error(Code), + Hung, +} + +const READINESS_PROVIDER: &str = "readiness-provider"; +const SYNTHETIC_READINESS_CREDENTIAL: &str = "fixture-provider-credential"; +const SYNTHETIC_READINESS_BACKEND_ERROR: &str = "fixture-backend-authorization-details"; +const SYNTHETIC_PROFILE_BACKEND_ERROR: &str = "TESTLEAK"; +const SYNTHETIC_MUTATION_ERROR_METADATA: &str = "fixture-mutation-error-metadata"; +const STORAGE_UNCERTAIN_REASON: &str = "CONFIG_OPERATION_STORAGE_UNCERTAIN"; + +fn selected_workspace( + scope: &Option, +) -> Option<&str> { + match scope.as_ref()?.selection.as_ref()? { + openshell_core::proto::datamodel::v1::workspace_selector::Selection::Workspace( + workspace, + ) => Some(workspace), + openshell_core::proto::datamodel::v1::workspace_selector::Selection::AllWorkspaces(_) => { + None + } + } +} #[derive(Clone, Default)] struct ProviderState { @@ -46,8 +82,13 @@ struct ProviderState { scoped_profiles: Arc>>, refresh_statuses: Arc>>, refresh_requests: Arc>>, + provider_create_requests: Arc, provider_update_requests: Arc>>, deny_provider_reads: Arc, + fail_provider_reads: Arc, + fail_sandbox_reads: Arc, + profile_read_errors: Arc>>, + profile_read_requests: Arc>>, delete_provider_requests: Arc>>, delete_provider_profile_requests: Arc>>, fail_configure_refresh_message: Arc>>, @@ -56,6 +97,12 @@ struct ProviderState { fail_delete_provider_profile_message: Arc>>, sandbox_providers: Arc>>>, sandbox_provider_requests: Arc>>, + readiness_receipts: Arc>>, + readiness_scripts: Arc>, + readiness_requests: Arc>>, + readiness_sequence: Arc, + corrupt_mutation_receipt: Arc>>, + fail_mutation_after_save: Arc>>, global_settings: Arc>>, } @@ -102,6 +149,78 @@ struct TestOpenShell { state: ProviderState, } +impl TestOpenShell { + // A durable mutation can fail before its receipt is stored. Keep the failure + // active for every call so a client replay remains visible in request logs. + async fn check_mutation_receipt_storage(&self) -> Result<(), Status> { + let failure = self.state.fail_mutation_after_save.lock().await.clone(); + failure.map_or(Ok(()), Err) + } + + async fn provider_receipt( + &self, + sandbox_name: &str, + provider_name: &str, + workspace: &str, + kind: ProviderMutationKind, + mutation_id: Option<&str>, + ) -> ProviderMutationReceipt { + let sequence = self.state.readiness_sequence.fetch_add(1, Ordering::SeqCst) + 1; + let provider = self + .state + .providers + .lock() + .await + .get(provider_name) + .cloned(); + let detached = kind == ProviderMutationKind::Detach; + let mut receipt = ProviderMutationReceipt { + receipt_id: format!("receipt-{sequence}"), + mutation_id: mutation_id.map_or_else(|| format!("mutation-{sequence}"), str::to_string), + provider_name: provider_name.to_string(), + workspace: workspace.to_string(), + kind: kind.into(), + desired: Some(ProviderDesiredIdentity { + sandbox_id: format!("sb-{sandbox_name}"), + sandbox_name: sandbox_name.to_string(), + attachment_epoch: format!("attachment-{sandbox_name}"), + provider_id: if detached { + String::new() + } else { + provider + .as_ref() + .map_or_else(String::new, |provider| provider.object_id().to_string()) + }, + provider_resource_version: if detached { + 0 + } else { + provider + .as_ref() + .and_then(|provider| provider.metadata.as_ref()) + .map_or(0, |metadata| metadata.resource_version) + }, + provider_env_revision: sequence, + config_revision: 17, + policy_hash: "effective-policy".to_string(), + }), + persisted_time: Some( + openshell_core::time::timestamp_from_millis(i64::try_from(sequence).unwrap()) + .unwrap(), + ), + }; + let corrupt = *self.state.corrupt_mutation_receipt.lock().await; + if let Some(corrupt) = corrupt { + corrupt(&mut receipt); + } + self.state + .readiness_receipts + .lock() + .await + .insert(receipt.receipt_id.clone(), receipt.clone()); + receipt + } +} + #[tonic::async_trait] impl OpenShell for TestOpenShell { async fn report_endpoint_status( @@ -183,6 +302,9 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result, Status> { + if self.state.fail_sandbox_reads.load(Ordering::SeqCst) { + return Err(Status::internal(SYNTHETIC_READINESS_BACKEND_ERROR)); + } let name = request.into_inner().name; // Return a minimal sandbox with metadata for CAS operations Ok(Response::new(SandboxResponse { @@ -246,6 +368,9 @@ impl OpenShell for TestOpenShell { request: tonic::Request, ) -> Result, Status> { let request = request.into_inner(); + let workspace = selected_workspace(&request.workspace_scope) + .filter(|workspace| !workspace.is_empty()) + .ok_or_else(|| Status::invalid_argument("one explicit workspace is required"))?; self.state .sandbox_provider_requests .lock() @@ -273,13 +398,25 @@ impl OpenShell for TestOpenShell { providers.push(request.provider_name.clone()); true }; + let provider_names = providers.clone(); + drop(sandbox_providers); + self.check_mutation_receipt_storage().await?; + let receipt = self + .provider_receipt( + &request.sandbox_name, + &request.provider_name, + workspace, + ProviderMutationKind::Attach, + None, + ) + .await; let sandbox = Sandbox { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { name: request.sandbox_name, ..Default::default() }), spec: Some(openshell_core::proto::SandboxSpec { - providers: providers.clone(), + providers: provider_names, ..Default::default() }), ..Default::default() @@ -287,6 +424,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(AttachSandboxProviderResponse { sandbox: Some(sandbox), attached, + receipt: Some(receipt), })) } @@ -295,6 +433,9 @@ impl OpenShell for TestOpenShell { request: tonic::Request, ) -> Result, Status> { let request = request.into_inner(); + let workspace = selected_workspace(&request.workspace_scope) + .filter(|workspace| !workspace.is_empty()) + .ok_or_else(|| Status::invalid_argument("one explicit workspace is required"))?; self.state .sandbox_provider_requests .lock() @@ -310,13 +451,25 @@ impl OpenShell for TestOpenShell { let before_len = providers.len(); providers.retain(|name| name != &request.provider_name); let detached = providers.len() != before_len; + let provider_names = providers.clone(); + drop(sandbox_providers); + self.check_mutation_receipt_storage().await?; + let receipt = self + .provider_receipt( + &request.sandbox_name, + &request.provider_name, + workspace, + ProviderMutationKind::Detach, + None, + ) + .await; let sandbox = Sandbox { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { name: request.sandbox_name, ..Default::default() }), spec: Some(openshell_core::proto::SandboxSpec { - providers: providers.clone(), + providers: provider_names, ..Default::default() }), ..Default::default() @@ -324,6 +477,7 @@ impl OpenShell for TestOpenShell { Ok(Response::new(DetachSandboxProviderResponse { sandbox: Some(sandbox), detached, + receipt: Some(receipt), })) } @@ -363,6 +517,102 @@ impl OpenShell for TestOpenShell { )) } + async fn get_sandbox_provider_status( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + let workspace = selected_workspace(&request.workspace_scope) + .filter(|workspace| !workspace.is_empty()) + .ok_or_else(|| Status::invalid_argument("one explicit workspace is required"))?; + self.state + .readiness_requests + .lock() + .await + .push(request.clone()); + let receipts = self.state.readiness_receipts.lock().await; + let receipt = if request.receipt_id.is_empty() { + receipts + .values() + .filter(|receipt| { + receipt.workspace == workspace + && receipt.provider_name == request.provider_name + && receipt + .desired + .as_ref() + .is_some_and(|desired| desired.sandbox_name == request.sandbox_name) + }) + .max_by_key(|receipt| { + receipt + .persisted_time + .as_ref() + .map(|time| (time.seconds, time.nanos)) + }) + } else { + receipts + .get(&request.receipt_id) + .filter(|receipt| receipt.workspace == workspace) + } + .cloned() + .ok_or_else(|| Status::not_found("provider receipt not found"))?; + drop(receipts); + let scripted = self + .state + .readiness_scripts + .lock() + .await + .get_mut(&request.sandbox_name) + .and_then(|script| { + if script.len() > 1 { + script.pop_front() + } else { + script.front().cloned() + } + }); + let mut status = match scripted { + Some(ReadinessReply::Status(status)) => *status, + // The last scripted reply repeats its delay after cancellation, + // matching a gateway whose status calls are consistently slow. + Some(ReadinessReply::DelayedStatus(delay, status)) => { + tokio::time::sleep(delay).await; + *status + } + Some(ReadinessReply::Error(code)) => { + return Err(Status::new(code, SYNTHETIC_READINESS_BACKEND_ERROR)); + } + // No mock lock survives this await; the client deadline must cancel + // the request while retaining its previously observed status. + Some(ReadinessReply::Hung) => std::future::pending().await, + None => ProviderReadinessStatus { + state: ProviderReadinessState::Persisted.into(), + reason: ProviderReadinessReason::WaitingForSupervisor.into(), + ..Default::default() + }, + }; + let response_receipt = status.receipt.get_or_insert(receipt); + if let Some(observed) = status.observed.as_mut() { + let desired = response_receipt.desired.as_ref().unwrap(); + observed + .attachment_epoch + .clone_from(&desired.attachment_epoch); + observed.provider_env_revision = desired.provider_env_revision; + observed.config_revision = desired.config_revision; + observed.policy_hash.clone_from(&desired.policy_hash); + } + Ok(Response::new(GetSandboxProviderStatusResponse { + status: Some(status), + })) + } + + async fn report_provider_readiness( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider installation reports are not exercised by this mock", + )) + } + async fn create_ssh_session( &self, _request: tonic::Request, @@ -418,6 +668,9 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result, Status> { + self.state + .provider_create_requests + .fetch_add(1, Ordering::SeqCst); let mut provider = request .into_inner() .provider @@ -459,6 +712,7 @@ impl OpenShell for TestOpenShell { providers.insert(provider_name, provider.clone()); Ok(Response::new(ProviderResponse { provider: Some(provider), + ..Default::default() })) } @@ -466,6 +720,9 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result, Status> { + if self.state.fail_provider_reads.load(Ordering::SeqCst) { + return Err(Status::internal(SYNTHETIC_READINESS_BACKEND_ERROR)); + } if self.state.deny_provider_reads.load(Ordering::SeqCst) { return Err(Status::permission_denied("scope 'provider:read' required")); } @@ -477,6 +734,7 @@ impl OpenShell for TestOpenShell { .ok_or_else(|| Status::not_found("provider not found"))?; Ok(Response::new(ProviderResponse { provider: Some(provider), + ..Default::default() })) } @@ -521,6 +779,21 @@ impl OpenShell for TestOpenShell { ) -> Result, Status> { let request = request.into_inner(); let id = request.id; + self.state + .profile_read_requests + .lock() + .await + .push(id.clone()); + let error_code = self + .state + .profile_read_errors + .lock() + .await + .get(&id) + .copied(); + if let Some(code) = error_code { + return Err(Status::new(code, SYNTHETIC_PROFILE_BACKEND_ERROR)); + } let scoped_profile = self .state .scoped_profiles @@ -660,8 +933,11 @@ impl OpenShell for TestOpenShell { &self, request: tonic::Request, ) -> Result, Status> { + let request = request.into_inner(); + let workspace = selected_workspace(&request.workspace_scope) + .filter(|workspace| !workspace.is_empty()) + .ok_or_else(|| Status::invalid_argument("one explicit workspace is required"))?; let provider = request - .into_inner() .provider .ok_or_else(|| Status::invalid_argument("provider is required"))?; self.state @@ -670,6 +946,16 @@ impl OpenShell for TestOpenShell { .await .push(provider.clone()); + let mut targets = self + .state + .sandbox_providers + .lock() + .await + .iter() + .filter(|(_, attached)| attached.iter().any(|name| name == provider.object_name())) + .map(|(sandbox_name, _)| sandbox_name.clone()) + .collect::>(); + targets.sort(); let mut providers = self.state.providers.lock().await; let existing = providers .get(provider.object_name()) @@ -708,9 +994,9 @@ impl OpenShell for TestOpenShell { name: provider_metadata.name, created_time: existing_metadata.created_time, labels: existing_metadata.labels, - resource_version: 0, + resource_version: existing_metadata.resource_version + 1, annotations: HashMap::new(), - workspace: String::new(), + workspace: workspace.to_string(), deletion_time: None, }), r#type: existing.r#type, @@ -728,9 +1014,30 @@ impl OpenShell for TestOpenShell { }, }; let updated_name = updated.object_name().to_string(); - providers.insert(updated_name, updated.clone()); + providers.insert(updated_name.clone(), updated.clone()); + drop(providers); + self.check_mutation_receipt_storage().await?; + let mutation_id = format!( + "update-{}", + self.state.readiness_sequence.fetch_add(1, Ordering::SeqCst) + 1 + ); + let mut target_receipts = Vec::with_capacity(targets.len()); + for sandbox_name in targets { + target_receipts.push( + self.provider_receipt( + &sandbox_name, + &updated_name, + workspace, + ProviderMutationKind::Update, + Some(&mutation_id), + ) + .await, + ); + } Ok(Response::new(ProviderResponse { provider: Some(updated), + target_receipts, + mutation_id, })) } async fn get_provider_refresh_status( @@ -1192,7 +1499,7 @@ struct TestServer { endpoint: String, tls: TlsOptions, state: ProviderState, - _dir: TempDir, + tls_materials_dir: TempDir, } async fn run_server() -> TestServer { @@ -1239,10 +1546,1619 @@ async fn run_server() -> TestServer { endpoint, tls, state, - _dir: dir, + tls_materials_dir: dir, + } +} + +async fn seed_readiness_provider(server: &TestServer) { + server.state.providers.lock().await.insert( + READINESS_PROVIDER.to_string(), + Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: format!("id-{READINESS_PROVIDER}"), + name: READINESS_PROVIDER.to_string(), + workspace: "default".to_string(), + resource_version: 1, + ..Default::default() + }), + r#type: "openai".to_string(), + credentials: HashMap::from([( + "OPENAI_API_KEY".to_string(), + SYNTHETIC_READINESS_CREDENTIAL.to_string(), + )]), + ..Default::default() + }, + ); +} + +fn readiness_status( + state: ProviderReadinessState, + reason: ProviderReadinessReason, + process_installed: bool, +) -> ProviderReadinessStatus { + ProviderReadinessStatus { + state: state.into(), + reason: reason.into(), + observed: Some(ProviderReadinessObservation { + session_id: "network-session".to_string(), + sequence: 1, + credentials_installed: true, + policy_active: true, + launch_environment_installed: process_installed, + process_instance_id: if process_installed { + "process-instance".to_string() + } else { + String::new() + }, + reason: reason.into(), + ..Default::default() + }), + network_instance_id: "network-instance".to_string(), + observed_time: Some(openshell_core::time::timestamp_from_millis(1000).unwrap()), + evaluated_time: Some(openshell_core::time::timestamp_from_millis(1000).unwrap()), + ..Default::default() + } +} + +async fn script_readiness( + server: &TestServer, + sandbox_name: &str, + responses: Vec>, +) { + server.state.readiness_scripts.lock().await.insert( + sandbox_name.to_string(), + responses + .into_iter() + .map(|response| match response { + Ok(status) => ReadinessReply::Status(Box::new(status)), + Err(code) => ReadinessReply::Error(code), + }) + .collect(), + ); +} + +async fn script_readiness_then_hang( + server: &TestServer, + sandbox_name: &str, + first_status: ProviderReadinessStatus, +) { + server.state.readiness_scripts.lock().await.insert( + sandbox_name.to_string(), + VecDeque::from([ + ReadinessReply::Status(Box::new(first_status)), + ReadinessReply::Hung, + ]), + ); +} + +async fn seed_readiness_receipt( + server: &TestServer, + sandbox_name: &str, + kind: ProviderMutationKind, +) -> ProviderMutationReceipt { + seed_readiness_provider(server).await; + TestOpenShell { + state: server.state.clone(), + } + .provider_receipt(sandbox_name, READINESS_PROVIDER, "default", kind, None) + .await +} + +async fn latest_readiness_receipt( + server: &TestServer, + sandbox_name: &str, +) -> ProviderMutationReceipt { + server + .state + .readiness_receipts + .lock() + .await + .values() + .filter(|receipt| { + receipt + .desired + .as_ref() + .is_some_and(|desired| desired.sandbox_name == sandbox_name) + }) + .max_by_key(|receipt| { + receipt + .persisted_time + .as_ref() + .map(|time| (time.seconds, time.nanos)) + }) + .cloned() + .expect("sandbox mutation receipt") +} + +fn provider_wait_options() -> run::ProviderWaitOptions<'static> { + run::ProviderWaitOptions { + wait: true, + timeout: Duration::from_secs(2), + output: "json", + } +} + +// A separate CLI process provides isolated stdout/stderr without redirecting +// the test runner's descriptors or sharing the user's gateway configuration. +async fn run_readiness_cli(server: &TestServer, args: &[&str]) -> std::process::Output { + let config_dir = tempfile::tempdir().unwrap(); + let tls_dir = config_dir + .path() + .join("openshell/gateways/provider-readiness/mtls"); + std::fs::create_dir_all(&tls_dir).unwrap(); + for filename in ["ca.crt", "tls.crt", "tls.key"] { + std::fs::copy( + server.tls_materials_dir.path().join(filename), + tls_dir.join(filename), + ) + .unwrap(); + } + let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell")); + for (key, _) in std::env::vars().filter(|(key, _)| key.starts_with("OPENSHELL_")) { + command.env_remove(key); + } + command + .args([ + "--gateway", + "provider-readiness", + "--gateway-endpoint", + &server.endpoint, + "--color", + "never", + ]) + .args(args) + .env("XDG_CONFIG_HOME", config_dir.path()) + .kill_on_drop(true); + tokio::time::timeout(Duration::from_secs(8), command.output()) + .await + .expect("bounded readiness CLI process") + .expect("readiness CLI output") +} + +fn assert_readiness_output_redacted(output: &std::process::Output) { + for bytes in [&output.stdout, &output.stderr] { + let text = String::from_utf8_lossy(bytes); + assert!(!text.contains(SYNTHETIC_READINESS_CREDENTIAL)); + assert!(!text.contains(SYNTHETIC_READINESS_BACKEND_ERROR)); + assert!(!text.contains(SYNTHETIC_PROFILE_BACKEND_ERROR)); + assert!(!text.contains(SYNTHETIC_MUTATION_ERROR_METADATA)); + } +} + +fn mutation_error_status(code: Code, reason: &str, domain: &str) -> Status { + Status::with_error_details( + code, + SYNTHETIC_READINESS_BACKEND_ERROR, + ErrorDetails::with_error_info( + reason, + domain, + HashMap::from([( + "backend".to_string(), + SYNTHETIC_MUTATION_ERROR_METADATA.to_string(), + )]), + ), + ) +} + +// Exercise the actual CLI process and establish that the mock saved exactly one +// mutation before returning the error, without producing or polling a receipt. +async fn run_saved_provider_mutation_error( + server: &TestServer, + action: &str, + status: Status, + wait: bool, +) -> String { + let sandbox_name = "storage-uncertain"; + seed_readiness_provider(server).await; + server.state.sandbox_providers.lock().await.insert( + sandbox_name.to_string(), + if action == "attach" { + Vec::new() + } else { + vec![READINESS_PROVIDER.to_string()] + }, + ); + server.state.sandbox_provider_requests.lock().await.clear(); + server.state.provider_update_requests.lock().await.clear(); + *server.state.fail_mutation_after_save.lock().await = Some(status); + let mut args = if action == "update" { + vec![ + "provider", + "update", + READINESS_PROVIDER, + "--config", + "region=changed", + ] + } else { + vec![ + "sandbox", + "provider", + action, + sandbox_name, + READINESS_PROVIDER, + ] + }; + args.extend(["--output", "json"]); + if wait { + args.extend(["--wait", "--timeout", "1"]); + } + let output = run_readiness_cli(server, &args).await; + assert!(!output.status.success(), "{action}, wait={wait}"); + assert!(output.stdout.is_empty(), "failed mutation printed a result"); + assert_readiness_output_redacted(&output); + assert!(server.state.readiness_receipts.lock().await.is_empty()); + assert!(server.state.readiness_requests.lock().await.is_empty()); + + let attachment_requests = server.state.sandbox_provider_requests.lock().await; + let update_requests = server.state.provider_update_requests.lock().await; + if action == "update" { + assert!(attachment_requests.is_empty()); + assert_eq!(update_requests.len(), 1, "update was replayed"); + let providers = server.state.providers.lock().await; + let provider = providers.get(READINESS_PROVIDER).unwrap(); + assert_eq!( + provider.config.get("region").map(String::as_str), + Some("changed") + ); + assert_eq!(provider.metadata.as_ref().unwrap().resource_version, 2); + } else { + assert!(update_requests.is_empty()); + let expected_request = if action == "attach" { + SandboxProviderRequestLog::Attach { + sandbox_name: sandbox_name.to_string(), + provider_name: READINESS_PROVIDER.to_string(), + } + } else { + SandboxProviderRequestLog::Detach { + sandbox_name: sandbox_name.to_string(), + provider_name: READINESS_PROVIDER.to_string(), + } + }; + assert_eq!( + *attachment_requests, + vec![expected_request], + "mutation was replayed" + ); + let attachments = server.state.sandbox_providers.lock().await; + assert_eq!( + attachments + .get(sandbox_name) + .unwrap() + .contains(&READINESS_PROVIDER.to_string()), + action == "attach", + "attachment mutation was not saved" + ); + } + String::from_utf8(output.stderr).unwrap() +} + +#[tokio::test] +async fn provider_readiness_storage_uncertainty_preserves_safe_recovery_guidance() { + let server = run_server().await; + for action in ["attach", "detach", "update"] { + for wait in [false, true] { + // Structured uncertainty takes precedence over the ordinary Aborted + // conflict hint: this saved mutation must not invite a blind retry. + for code in [Code::Unavailable, Code::Aborted] { + let stderr = run_saved_provider_mutation_error( + &server, + action, + mutation_error_status(code, STORAGE_UNCERTAIN_REASON, ERROR_DOMAIN), + wait, + ) + .await; + for expected in [ + STORAGE_UNCERTAIN_REASON, + "may already be saved", + "Do not blindly retry", + "reconcile", + ] { + assert!( + stderr.contains(expected), + "{action}, wait={wait}, {code:?}: {stderr}" + ); + } + assert!(!stderr.contains("Please retry the command")); + } + } + } +} + +#[tokio::test] +async fn provider_readiness_storage_uncertainty_requires_trusted_error_info() { + let server = run_server().await; + let valid = mutation_error_status(Code::Unavailable, STORAGE_UNCERTAIN_REASON, ERROR_DOMAIN); + let mut malformed_error_info = valid.details().to_vec(); + let reason_offset = malformed_error_info + .windows(STORAGE_UNCERTAIN_REASON.len()) + .position(|bytes| bytes == STORAGE_UNCERTAIN_REASON.as_bytes()) + .unwrap(); + // Invalid UTF-8 breaks only the nested ErrorInfo reason; its outer status + // envelope remains valid and cannot authorize the special recovery hint. + malformed_error_info[reason_offset] = 0xff; + let cases = [ + ( + "unrelated", + mutation_error_status(Code::Unavailable, "OTHER_REASON", ERROR_DOMAIN), + ), + ( + "wrong domain", + mutation_error_status(Code::Unavailable, STORAGE_UNCERTAIN_REASON, "other.example"), + ), + ( + "reason case", + mutation_error_status( + Code::Unavailable, + "config_operation_storage_uncertain", + ERROR_DOMAIN, + ), + ), + ( + "domain case", + mutation_error_status( + Code::Unavailable, + STORAGE_UNCERTAIN_REASON, + "OPENSHELL.NVIDIA.COM", + ), + ), + ( + "missing ErrorInfo", + Status::with_error_details( + Code::Unavailable, + SYNTHETIC_READINESS_BACKEND_ERROR, + ErrorDetails::new(), + ), + ), + ( + "message only", + Status::unavailable(format!( + "{STORAGE_UNCERTAIN_REASON}: {SYNTHETIC_READINESS_BACKEND_ERROR}" + )), + ), + ( + "malformed ErrorInfo", + Status::with_details( + Code::Unavailable, + SYNTHETIC_READINESS_BACKEND_ERROR, + malformed_error_info.into(), + ), + ), + ( + "malformed envelope", + Status::with_details( + Code::Unavailable, + SYNTHETIC_READINESS_BACKEND_ERROR, + vec![0xff].into(), + ), + ), + ( + "mismatched envelope message", + Status::with_details( + Code::Unavailable, + "different message", + valid.details().to_vec().into(), + ), + ), + ]; + for action in ["attach", "detach", "update"] { + let error_prefix = match action { + "attach" => "provider attachment failed", + "detach" => "provider detachment failed", + _ => "provider update failed", + }; + for (case, status) in &cases { + let stderr = + run_saved_provider_mutation_error(&server, action, status.clone(), true).await; + assert!(stderr.contains(error_prefix), "{action}, {case}: {stderr}"); + assert!( + stderr.contains(&Code::Unavailable.to_string()), + "{action}, {case}: {stderr}" + ); + assert!( + !stderr.contains(STORAGE_UNCERTAIN_REASON), + "{action}, {case}: {stderr}" + ); + assert!( + !stderr.contains("may already be saved"), + "{action}, {case}: {stderr}" + ); + } + } +} + +#[tokio::test] +async fn provider_readiness_mutations_reject_unbound_receipts_before_output_or_polling() { + let server = run_server().await; + seed_readiness_provider(&server).await; + let corruptions: &[(&str, ReceiptCorruption)] = &[ + ("empty", |receipt| { + *receipt = ProviderMutationReceipt::default(); + }), + ("receipt_id", |receipt| receipt.receipt_id.clear()), + ("mutation_id", |receipt| receipt.mutation_id.clear()), + ("workspace", |receipt| { + receipt.workspace = "other".to_string(); + }), + ("provider", |receipt| { + receipt.provider_name = "other".to_string(); + }), + ("kind", |receipt| { + receipt.kind = ProviderMutationKind::Observe.into(); + }), + ("sandbox_name", |receipt| { + receipt + .desired + .as_mut() + .expect("desired identity") + .sandbox_name = "other".to_string(); + }), + ("sandbox_id", |receipt| { + receipt + .desired + .as_mut() + .expect("desired identity") + .sandbox_id = "other-id".to_string(); + }), + ("desired", |receipt| receipt.desired = None), + ("timestamp", |receipt| receipt.persisted_time = None), + ("provider_presence", |receipt| { + let detached = receipt.kind == i32::from(ProviderMutationKind::Detach); + receipt + .desired + .as_mut() + .expect("desired identity") + .provider_id = if detached { + "unexpected-provider".to_string() + } else { + String::new() + }; + }), + ]; + for action in ["attach", "detach"] { + let state = if action == "attach" { + ProviderReadinessState::Ready + } else { + ProviderReadinessState::Revoked + }; + script_readiness( + &server, + "receipt-target", + vec![Ok(readiness_status( + state, + ProviderReadinessReason::Unspecified, + true, + ))], + ) + .await; + for wait in [false, true] { + for (field, corrupt) in corruptions { + *server.state.corrupt_mutation_receipt.lock().await = Some(*corrupt); + let mut args = vec![ + "sandbox", + "provider", + action, + "receipt-target", + READINESS_PROVIDER, + "--timeout", + "1", + "--output", + "json", + ]; + if wait { + args.push("--wait"); + } + let output = run_readiness_cli(&server, &args).await; + assert!(!output.status.success(), "{action}: {field}, wait={wait}"); + assert!( + output.stdout.is_empty(), + "invalid receipt was printed: {field}" + ); + assert_readiness_output_redacted(&output); + assert!(server.state.readiness_requests.lock().await.is_empty()); + } + } + } +} + +#[tokio::test] +async fn provider_readiness_update_rejects_unbound_batch_identity() { + let server = run_server().await; + seed_readiness_provider(&server).await; + server.state.sandbox_providers.lock().await.insert( + "update-target".to_string(), + vec![READINESS_PROVIDER.to_string()], + ); + script_readiness( + &server, + "update-target", + vec![Ok(readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + ))], + ) + .await; + let corruptions: &[(&str, ReceiptCorruption)] = &[ + ("mutation_id", |receipt| { + receipt.mutation_id = "another-update".to_string(); + }), + ("workspace", |receipt| { + receipt.workspace = "other".to_string(); + }), + ("provider_name", |receipt| { + receipt.provider_name = "other".to_string(); + }), + ("kind", |receipt| { + receipt.kind = ProviderMutationKind::Observe.into(); + }), + ("provider_id", |receipt| { + receipt + .desired + .as_mut() + .expect("desired identity") + .provider_id = "other-id".to_string(); + }), + ("provider_revision", |receipt| { + receipt + .desired + .as_mut() + .expect("desired identity") + .provider_resource_version = u64::MAX; + }), + ]; + for wait in [false, true] { + for (field, corrupt) in corruptions { + *server.state.corrupt_mutation_receipt.lock().await = Some(*corrupt); + let mut args = vec![ + "provider", + "update", + READINESS_PROVIDER, + "--credential", + "OPENAI_API_KEY=updated-fixture", + "--timeout", + "1", + "--output", + "json", + ]; + if wait { + args.push("--wait"); + } + let output = run_readiness_cli(&server, &args).await; + assert!(!output.status.success(), "{field}, wait={wait}"); + assert!( + output.stdout.is_empty(), + "invalid batch was printed: {field}" + ); + assert_readiness_output_redacted(&output); + assert!(server.state.readiness_requests.lock().await.is_empty()); + } + } +} + +#[tokio::test] +async fn provider_readiness_update_with_no_targets_preserves_saved_success() { + let server = run_server().await; + seed_readiness_provider(&server).await; + for wait in [false, true] { + let mut args = vec![ + "provider", + "update", + READINESS_PROVIDER, + "--credential", + "OPENAI_API_KEY=updated-fixture", + "--output", + "json", + ]; + if wait { + args.push("--wait"); + } + let output = run_readiness_cli(&server, &args).await; + assert!(output.status.success()); + let value: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("saved update JSON"); + assert_eq!(value["targets"], serde_json::json!([])); + assert!( + !value["mutation_id"] + .as_str() + .expect("mutation ID") + .is_empty() + ); + assert!(server.state.readiness_requests.lock().await.is_empty()); + } +} + +#[tokio::test] +async fn provider_profile_permission_denial_preserves_safe_workspace_guidance() { + let server = run_server().await; + seed_readiness_provider(&server).await; + for (profile, failed_lookup, expected_lookups) in [ + ("openai", "openai", vec!["openai"]), + ("gh", "github", vec!["gh", "github"]), + ] { + server + .state + .providers + .lock() + .await + .get_mut(READINESS_PROVIDER) + .expect("seeded provider") + .r#type = profile.to_string(); + let mut errors = server.state.profile_read_errors.lock().await; + errors.clear(); + errors.insert(failed_lookup.to_string(), Code::PermissionDenied); + drop(errors); + for args in [ + vec![ + "provider", + "create", + "--name", + "denied-new-provider", + "--type", + profile, + "--credential", + "OPENAI_API_KEY=fixture-provider-credential", + ], + vec![ + "provider", + "update", + READINESS_PROVIDER, + "--from-existing", + "--wait", + "--output", + "json", + ], + ] { + server.state.profile_read_requests.lock().await.clear(); + let output = run_readiness_cli(&server, &args).await; + assert!(!output.status.success(), "{args:?}"); + assert!(output.stdout.is_empty()); + assert_readiness_output_redacted(&output); + let diagnostic = String::from_utf8_lossy(&output.stderr); + let compact: String = diagnostic + .chars() + .filter(|character| !character.is_whitespace() && *character != '│') + .collect(); + assert!( + compact.contains("providerprofilelookupdenied"), + "{diagnostic}" + ); + // The permission code supports recovery guidance without revealing + // backend text or inferring which membership or role check failed. + assert!(compact.contains("PERMISSION_DENIED"), "{diagnostic}"); + assert!( + compact.contains("verifyworkspacemembershipandrequiredpermissions"), + "{diagnostic}" + ); + assert!(!diagnostic.contains("unsupported provider type or profile")); + assert_eq!( + *server.state.profile_read_requests.lock().await, + expected_lookups + ); + assert!( + !server + .state + .providers + .lock() + .await + .contains_key("denied-new-provider") + ); + assert_eq!( + server.state.provider_create_requests.load(Ordering::SeqCst), + 0 + ); + assert!( + server + .state + .provider_update_requests + .lock() + .await + .is_empty() + ); + assert!(server.state.readiness_requests.lock().await.is_empty()); + } + } +} + +#[tokio::test] +async fn provider_readiness_update_redacts_exact_and_alias_profile_lookup_errors() { + let server = run_server().await; + seed_readiness_provider(&server).await; + for (profile, failed_lookup, expected_lookups) in [ + ("openai", "openai", vec!["openai"]), + ("gh", "github", vec!["gh", "github"]), + ] { + server + .state + .providers + .lock() + .await + .get_mut(READINESS_PROVIDER) + .expect("seeded provider") + .r#type = profile.to_string(); + let mut errors = server.state.profile_read_errors.lock().await; + errors.clear(); + errors.insert(failed_lookup.to_string(), Code::Internal); + drop(errors); + for source in ["--from-existing", "--from-oidc-token"] { + server.state.profile_read_requests.lock().await.clear(); + let output = run_readiness_cli( + &server, + &[ + "provider", + "update", + READINESS_PROVIDER, + source, + "--wait", + "--output", + "json", + ], + ) + .await; + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + assert!( + String::from_utf8_lossy(&output.stderr).contains("provider profile lookup failed") + ); + assert_eq!( + *server.state.profile_read_requests.lock().await, + expected_lookups + ); + assert!( + server + .state + .provider_update_requests + .lock() + .await + .is_empty() + ); + } } } +async fn assert_later_readiness_targets_are_polled( + blocked_targets: usize, + blocked_reply: ReadinessReply, + expected_state: &str, +) { + let server = run_server().await; + seed_readiness_provider(&server).await; + for index in 0..17 { + let sandbox = format!("sandbox-{index:02}"); + server + .state + .sandbox_providers + .lock() + .await + .insert(sandbox.clone(), vec![READINESS_PROVIDER.to_string()]); + script_readiness( + &server, + &sandbox, + vec![Ok(readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + ))], + ) + .await; + } + for index in 0..blocked_targets { + server.state.readiness_scripts.lock().await.insert( + format!("sandbox-{index:02}"), + VecDeque::from([blocked_reply.clone()]), + ); + } + let started = std::time::Instant::now(); + let output = run_readiness_cli( + &server, + &[ + "provider", + "update", + READINESS_PROVIDER, + "--credential", + "OPENAI_API_KEY=updated-fixture", + "--wait", + "--timeout", + "1", + "--output", + "json", + ], + ) + .await; + assert!(!output.status.success()); + assert!(started.elapsed() < Duration::from_secs(4)); + assert_readiness_output_redacted(&output); + let value: serde_json::Value = serde_json::from_slice(&output.stdout).expect("target outcomes"); + let targets = value["targets"].as_array().expect("target array"); + assert_eq!(targets.len(), 17); + let requests = server.state.readiness_requests.lock().await; + for (index, target) in targets.iter().enumerate() { + let sandbox = format!("sandbox-{index:02}"); + assert_eq!(target["receipt"]["desired"]["sandbox_name"], sandbox); + if index < blocked_targets { + assert_eq!(target["wait_outcome"], "timed_out"); + assert_eq!(target["state"], expected_state); + } else { + assert_eq!(target["wait_outcome"], "complete"); + } + let target_requests = requests + .iter() + .filter(|request| request.sandbox_name == sandbox) + .collect::>(); + assert!(!target_requests.is_empty(), "{sandbox} was never queried"); + if index >= blocked_targets { + assert_eq!( + target_requests.len(), + 1, + "completed targets leave the queue" + ); + } + for request in target_requests { + assert_eq!( + request.receipt_id, + target["receipt"]["receipt_id"] + .as_str() + .expect("receipt ID") + ); + assert_eq!(request.provider_name, READINESS_PROVIDER); + assert_eq!( + selected_workspace(&request.workspace_scope), + Some("default") + ); + } + } +} + +#[tokio::test] +async fn provider_readiness_update_polls_later_targets_while_first_is_hung() { + assert_later_readiness_targets_are_polled(1, ReadinessReply::Hung, "persisted").await; +} + +#[tokio::test] +async fn provider_readiness_update_polls_later_targets_while_first_batch_is_pending() { + assert_later_readiness_targets_are_polled( + 16, + ReadinessReply::Status(Box::new(readiness_status( + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForProcess, + false, + ))), + "pending", + ) + .await; +} + +#[tokio::test] +async fn provider_readiness_update_polls_later_targets_while_first_batch_is_hung() { + assert_later_readiness_targets_are_polled(16, ReadinessReply::Hung, "persisted").await; +} + +async fn assert_slow_readiness_targets_complete(target_count: usize, delay: Duration) { + let server = run_server().await; + seed_readiness_provider(&server).await; + for index in 0..target_count { + let sandbox = format!("slow-sandbox-{index:02}"); + server + .state + .sandbox_providers + .lock() + .await + .insert(sandbox.clone(), vec![READINESS_PROVIDER.to_string()]); + server.state.readiness_scripts.lock().await.insert( + sandbox, + VecDeque::from([ReadinessReply::DelayedStatus( + delay, + Box::new(readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + )), + )]), + ); + } + let started = std::time::Instant::now(); + let output = run_readiness_cli( + &server, + &[ + "provider", + "update", + READINESS_PROVIDER, + "--credential", + "OPENAI_API_KEY=updated-fixture", + "--wait", + "--timeout", + "2", + "--output", + "json", + ], + ) + .await; + assert!( + output.status.success(), + "healthy status replies that fit the shared deadline must complete: {}", + String::from_utf8_lossy(&output.stdout) + ); + assert!(started.elapsed() < Duration::from_secs(4)); + assert_readiness_output_redacted(&output); + let value: serde_json::Value = serde_json::from_slice(&output.stdout).expect("target outcomes"); + let targets = value["targets"].as_array().expect("target array"); + assert_eq!(targets.len(), target_count); + let requests = server.state.readiness_requests.lock().await; + for (index, target) in targets.iter().enumerate() { + let sandbox = format!("slow-sandbox-{index:02}"); + assert_eq!(target["receipt"]["desired"]["sandbox_name"], sandbox); + assert_eq!(target["wait_outcome"], "complete"); + assert_eq!( + requests + .iter() + .filter(|request| request.sandbox_name == sandbox) + .count(), + 1, + "a healthy response must not be discarded and retried" + ); + } +} + +#[tokio::test] +async fn provider_readiness_update_wait_allows_slow_single_target() { + assert_slow_readiness_targets_complete(1, Duration::from_millis(1200)).await; +} + +#[tokio::test] +async fn provider_readiness_update_wait_allows_slow_queued_targets() { + assert_slow_readiness_targets_complete(17, Duration::from_millis(700)).await; +} + +#[tokio::test] +async fn provider_readiness_attach_wait_observes_pending_then_ready() { + let server = run_server().await; + seed_readiness_provider(&server).await; + script_readiness( + &server, + "pending-sandbox", + vec![ + Ok(readiness_status( + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForProcess, + false, + )), + Ok(readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + )), + ], + ) + .await; + + run::sandbox_provider_attach( + &server.endpoint, + "pending-sandbox", + READINESS_PROVIDER, + "default", + &server.tls, + provider_wait_options(), + ) + .await + .expect("attachment waits through pending state"); + + let requests = server.state.readiness_requests.lock().await; + assert_eq!(requests.len(), 2); + assert!(!requests[0].receipt_id.is_empty()); + assert!( + requests + .iter() + .all(|request| request.receipt_id == requests[0].receipt_id) + ); + assert!( + requests + .iter() + .all(|request| selected_workspace(&request.workspace_scope) == Some("default")) + ); +} + +#[tokio::test] +async fn provider_readiness_attach_wait_times_out_without_process_ack() { + let server = run_server().await; + seed_readiness_provider(&server).await; + script_readiness( + &server, + "missing-process", + vec![Ok(readiness_status( + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForProcess, + false, + ))], + ) + .await; + + let output = run_readiness_cli( + &server, + &[ + "sandbox", + "provider", + "attach", + "missing-process", + READINESS_PROVIDER, + "--wait", + "--timeout", + "1", + "--output", + "json", + ], + ) + .await; + + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + let value: serde_json::Value = serde_json::from_slice(&output.stdout).expect("readiness JSON"); + let target = &value["targets"][0]; + assert_eq!(target["state"], "pending"); + assert_eq!(target["reason"], "waiting_for_process"); + assert_eq!(target["wait_outcome"], "timed_out"); + assert_eq!(target["observed"]["launch_environment_installed"], false); + assert!(!server.state.readiness_requests.lock().await.is_empty()); +} + +#[tokio::test] +async fn provider_readiness_status_wait_supersedes_changed_desired_authority() { + let server = run_server().await; + seed_readiness_provider(&server).await; + run::sandbox_provider_attach( + &server.endpoint, + "changed-authority", + READINESS_PROVIDER, + "default", + &server.tls, + run::ProviderWaitOptions::default(), + ) + .await + .unwrap(); + let original = latest_readiness_receipt(&server, "changed-authority").await; + let mut newer = original.clone(); + newer.desired.as_mut().unwrap().provider_env_revision += 1; + let mut newer_status = readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + ); + newer_status.receipt = Some(newer); + script_readiness( + &server, + "changed-authority", + vec![ + Ok(readiness_status( + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForProcess, + false, + )), + Ok(newer_status), + ], + ) + .await; + + let output = run_readiness_cli( + &server, + &[ + "sandbox", + "provider", + "status", + "changed-authority", + READINESS_PROVIDER, + "--receipt", + &original.receipt_id, + "--wait", + "--output", + "json", + ], + ) + .await; + + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + let value: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("superseded readiness JSON"); + let target = &value["targets"][0]; + assert_eq!(target["state"], "superseded"); + assert_eq!(target["reason"], "desired_state_changed"); + assert_eq!(target["wait_outcome"], "terminal"); + assert_eq!(target["receipt"]["receipt_id"], original.receipt_id); + assert_eq!( + target["receipt"]["desired"]["provider_env_revision"], + original + .desired + .as_ref() + .unwrap() + .provider_env_revision + .to_string() + ); + let requests = server.state.readiness_requests.lock().await; + assert_eq!(requests.len(), 2); + assert!( + requests + .iter() + .all(|request| request.receipt_id == original.receipt_id) + ); +} + +#[tokio::test] +async fn provider_readiness_status_without_wait_rejects_missing_process_ack() { + let server = run_server().await; + let receipt = + seed_readiness_receipt(&server, "unproved-ready", ProviderMutationKind::Attach).await; + script_readiness( + &server, + "unproved-ready", + vec![Ok(readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + false, + ))], + ) + .await; + + let output = run_readiness_cli( + &server, + &[ + "sandbox", + "provider", + "status", + "unproved-ready", + READINESS_PROVIDER, + "--receipt", + &receipt.receipt_id, + "--output", + "json", + ], + ) + .await; + + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).contains("invalid provider readiness status")); + assert_eq!(server.state.readiness_requests.lock().await.len(), 1); +} + +#[tokio::test] +async fn provider_readiness_status_without_wait_rejects_ready_for_detach() { + let server = run_server().await; + let receipt = + seed_readiness_receipt(&server, "unrevoked-detach", ProviderMutationKind::Detach).await; + script_readiness( + &server, + "unrevoked-detach", + vec![Ok(readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + ))], + ) + .await; + + let output = run_readiness_cli( + &server, + &[ + "sandbox", + "provider", + "status", + "unrevoked-detach", + READINESS_PROVIDER, + "--receipt", + &receipt.receipt_id, + "--output", + "json", + ], + ) + .await; + + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).contains("invalid provider readiness status")); + assert_eq!(server.state.readiness_requests.lock().await.len(), 1); +} + +#[tokio::test] +async fn provider_readiness_status_wait_completes_from_first_ready_response() { + let server = run_server().await; + let receipt = + seed_readiness_receipt(&server, "first-ready", ProviderMutationKind::Attach).await; + script_readiness_then_hang( + &server, + "first-ready", + readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + ), + ) + .await; + + let output = run_readiness_cli( + &server, + &[ + "sandbox", + "provider", + "status", + "first-ready", + READINESS_PROVIDER, + "--receipt", + &receipt.receipt_id, + "--wait", + "--timeout", + "1", + "--output", + "json", + ], + ) + .await; + + assert!(output.status.success()); + assert_readiness_output_redacted(&output); + let value: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("completed readiness JSON"); + let target = &value["targets"][0]; + assert_eq!(target["state"], "ready"); + assert_eq!(target["wait_outcome"], "complete"); + assert_eq!(target["receipt"]["receipt_id"], receipt.receipt_id); + assert_eq!(target["observed"]["launch_environment_installed"], true); + assert_eq!(server.state.readiness_requests.lock().await.len(), 1); +} + +#[tokio::test] +async fn provider_readiness_status_wait_timeout_preserves_first_pending_response() { + let server = run_server().await; + let receipt = + seed_readiness_receipt(&server, "first-pending", ProviderMutationKind::Attach).await; + script_readiness_then_hang( + &server, + "first-pending", + readiness_status( + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForProcess, + false, + ), + ) + .await; + + let output = run_readiness_cli( + &server, + &[ + "sandbox", + "provider", + "status", + "first-pending", + READINESS_PROVIDER, + "--receipt", + &receipt.receipt_id, + "--wait", + "--timeout", + "1", + "--output", + "json", + ], + ) + .await; + + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + let value: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("timed-out readiness JSON"); + let target = &value["targets"][0]; + assert_eq!(target["state"], "pending"); + assert_eq!(target["reason"], "waiting_for_process"); + assert_eq!(target["wait_outcome"], "timed_out"); + assert_eq!(target["receipt"]["receipt_id"], receipt.receipt_id); + assert_eq!(target["observed"]["session_id"], "network-session"); + assert_eq!(target["observed"]["launch_environment_installed"], false); + let requests = server.state.readiness_requests.lock().await; + assert_eq!(requests.len(), 2); + assert!( + requests + .iter() + .all(|request| request.receipt_id == receipt.receipt_id) + ); +} + +#[tokio::test] +async fn provider_readiness_mutations_redact_sandbox_lookup_errors() { + let server = run_server().await; + seed_readiness_provider(&server).await; + server + .state + .fail_sandbox_reads + .store(true, Ordering::SeqCst); + + for operation in ["attach", "detach"] { + let output = run_readiness_cli( + &server, + &[ + "sandbox", + "provider", + operation, + "read-failed", + READINESS_PROVIDER, + "--wait", + "--output", + "json", + ], + ) + .await; + + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + assert!( + String::from_utf8_lossy(&output.stderr) + .to_ascii_lowercase() + .contains("internal") + ); + } + assert!( + server + .state + .sandbox_provider_requests + .lock() + .await + .is_empty() + ); + assert!(server.state.readiness_requests.lock().await.is_empty()); +} + +#[tokio::test] +async fn provider_readiness_update_redacts_provider_lookup_errors() { + let server = run_server().await; + seed_readiness_provider(&server).await; + server + .state + .fail_provider_reads + .store(true, Ordering::SeqCst); + + let output = run_readiness_cli( + &server, + &[ + "provider", + "update", + READINESS_PROVIDER, + "--config", + "region=test", + "--wait", + "--output", + "json", + ], + ) + .await; + + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + assert!( + String::from_utf8_lossy(&output.stderr) + .to_ascii_lowercase() + .contains("internal") + ); + assert!( + server + .state + .provider_update_requests + .lock() + .await + .is_empty() + ); + assert!(server.state.readiness_requests.lock().await.is_empty()); +} + +#[tokio::test] +async fn provider_readiness_status_rejects_wrong_first_receipt() { + let server = run_server().await; + seed_readiness_provider(&server).await; + run::sandbox_provider_attach( + &server.endpoint, + "wrong-receipt", + READINESS_PROVIDER, + "default", + &server.tls, + run::ProviderWaitOptions::default(), + ) + .await + .unwrap(); + let original = latest_readiness_receipt(&server, "wrong-receipt").await; + let mut replacement = original.clone(); + replacement.receipt_id = "another-mutation-receipt".to_string(); + replacement.mutation_id = "another-mutation".to_string(); + let mut status = readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + ); + status.receipt = Some(replacement); + script_readiness(&server, "wrong-receipt", vec![Ok(status)]).await; + + let error = run::sandbox_provider_status( + &server.endpoint, + "wrong-receipt", + READINESS_PROVIDER, + &original.receipt_id, + "default", + &server.tls, + provider_wait_options(), + ) + .await + .expect_err("a replacement receipt cannot satisfy the requested receipt"); + + assert!( + error + .to_string() + .contains("invalid provider readiness status") + ); + assert_eq!(server.state.readiness_requests.lock().await.len(), 1); +} + +#[tokio::test] +async fn provider_readiness_detach_wait_requires_revoked() { + let server = run_server().await; + seed_readiness_provider(&server).await; + server.state.sandbox_providers.lock().await.insert( + "detach-sandbox".to_string(), + vec![READINESS_PROVIDER.to_string()], + ); + script_readiness( + &server, + "detach-sandbox", + vec![Ok(readiness_status( + ProviderReadinessState::Ready, + ProviderReadinessReason::Unspecified, + true, + ))], + ) + .await; + + let error = run::sandbox_provider_detach( + &server.endpoint, + "detach-sandbox", + READINESS_PROVIDER, + "default", + &server.tls, + provider_wait_options(), + ) + .await + .expect_err("READY cannot establish detachment completion"); + assert!( + error + .to_string() + .contains("readiness wait did not complete") + ); + script_readiness( + &server, + "detach-sandbox", + vec![ + Ok(readiness_status( + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForProcess, + false, + )), + Ok(readiness_status( + ProviderReadinessState::Revoked, + ProviderReadinessReason::Unspecified, + true, + )), + ], + ) + .await; + + // A repeated detach still returns a receipt and waits for revoked authority. + run::sandbox_provider_detach( + &server.endpoint, + "detach-sandbox", + READINESS_PROVIDER, + "default", + &server.tls, + provider_wait_options(), + ) + .await + .expect("revoked receipt completes detachment"); + let requests = server.state.readiness_requests.lock().await; + assert_eq!(requests.len(), 3); + assert!( + requests + .iter() + .all(|request| selected_workspace(&request.workspace_scope) == Some("default")) + ); +} + +#[tokio::test] +async fn provider_readiness_update_reports_every_target_failure() { + let server = run_server().await; + seed_readiness_provider(&server).await; + for sandbox in ["network-failed", "unsupported", "transport-failed"] { + server + .state + .sandbox_providers + .lock() + .await + .insert(sandbox.to_string(), vec![READINESS_PROVIDER.to_string()]); + } + script_readiness( + &server, + "network-failed", + vec![Ok(readiness_status( + ProviderReadinessState::Failed, + ProviderReadinessReason::CredentialInstallFailed, + false, + ))], + ) + .await; + script_readiness( + &server, + "unsupported", + vec![Ok(readiness_status( + ProviderReadinessState::Withheld, + ProviderReadinessReason::UnsupportedSupervisor, + false, + ))], + ) + .await; + script_readiness(&server, "transport-failed", vec![Err(Code::Internal)]).await; + + let output = run_readiness_cli( + &server, + &[ + "provider", + "update", + READINESS_PROVIDER, + "--config", + "region=test", + "--wait", + "--timeout", + "1", + "--output", + "json", + ], + ) + .await; + + assert!(!output.status.success()); + assert_readiness_output_redacted(&output); + let value: serde_json::Value = + serde_json::from_slice(&output.stdout).expect("multi-target readiness JSON"); + let targets: HashMap<_, _> = value["targets"] + .as_array() + .unwrap() + .iter() + .map(|target| { + ( + target["receipt"]["desired"]["sandbox_name"] + .as_str() + .unwrap(), + target, + ) + }) + .collect(); + assert_eq!(targets.len(), 3); + assert_eq!(targets["network-failed"]["state"], "failed"); + assert_eq!( + targets["network-failed"]["reason"], + "credential_install_failed" + ); + assert_eq!(targets["unsupported"]["state"], "withheld"); + assert_eq!(targets["unsupported"]["reason"], "unsupported_supervisor"); + assert_eq!( + targets["transport-failed"]["wait_outcome"], + "observation_error" + ); + assert!(!value["mutation_id"].as_str().unwrap().is_empty()); + assert!( + targets + .values() + .all(|target| target["receipt"]["mutation_id"] == value["mutation_id"]) + ); + let requests = server.state.readiness_requests.lock().await; + assert_eq!(requests.len(), 3); + assert!( + requests + .iter() + .all(|request| selected_workspace(&request.workspace_scope) == Some("default")) + ); +} + async fn install_test_profile(ts: &TestServer, id: &str, credential_key: &str) { ts.state.profiles.lock().await.insert( id.to_string(), @@ -1296,6 +3212,7 @@ async fn provider_update_preserves_stored_type_and_profile_workspace_when_readab credential_expires_at: &[], workspace: "default", tls: &ts.tls, + readiness: run::ProviderWaitOptions::default(), }) .await .expect("provider update"); @@ -1417,6 +3334,7 @@ async fn provider_cli_run_functions_support_full_crud_flow() { credential_expires_at: &[], workspace: "default", tls: &ts.tls, + readiness: run::ProviderWaitOptions::default(), }) .await .expect("provider update"); @@ -1892,6 +3810,7 @@ async fn sandbox_provider_cli_run_functions_wire_requests_and_idempotent_results "work-github", "default", &ts.tls, + run::ProviderWaitOptions::default(), ) .await .expect("sandbox provider attach"); @@ -1901,6 +3820,7 @@ async fn sandbox_provider_cli_run_functions_wire_requests_and_idempotent_results "work-github", "default", &ts.tls, + run::ProviderWaitOptions::default(), ) .await .expect("sandbox provider attach is idempotent"); @@ -1913,6 +3833,7 @@ async fn sandbox_provider_cli_run_functions_wire_requests_and_idempotent_results "work-github", "default", &ts.tls, + run::ProviderWaitOptions::default(), ) .await .expect("sandbox provider detach"); @@ -1922,6 +3843,7 @@ async fn sandbox_provider_cli_run_functions_wire_requests_and_idempotent_results "work-github", "default", &ts.tls, + run::ProviderWaitOptions::default(), ) .await .expect("sandbox provider detach is idempotent"); @@ -1966,14 +3888,12 @@ async fn sandbox_provider_attach_cli_surfaces_server_errors() { "missing-provider", "default", &ts.tls, + run::ProviderWaitOptions::default(), ) .await .expect_err("missing provider should fail"); - assert!( - err.to_string().contains("provider not found"), - "unexpected error: {err}" - ); + assert!(err.to_string().contains("provider attachment failed")); assert_eq!( ts.state.sandbox_provider_requests.lock().await.as_slice(), [SandboxProviderRequestLog::Attach { @@ -2385,6 +4305,7 @@ async fn provider_update_from_existing_uses_profile_discovery() { credential_expires_at: &[], workspace: "default", tls: &ts.tls, + readiness: run::ProviderWaitOptions::default(), }) .await .expect("profile-backed provider update --from-existing"); @@ -2457,6 +4378,7 @@ async fn provider_update_from_existing_preserves_global_profile_scope() { credential_expires_at: &[], workspace: "default", tls: &ts.tls, + readiness: run::ProviderWaitOptions::default(), }) .await .expect("global profile-backed provider update --from-existing"); @@ -2534,6 +4456,7 @@ async fn provider_update_from_oidc_token_preserves_global_profile_scope() { credential_expires_at: &[], workspace: "default", tls: &ts.tls, + readiness: run::ProviderWaitOptions::default(), }) .await .expect_err("unnamed test gateway should stop after profile validation"); diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index 5bf1e0e1c5..1739c3a4c2 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -367,6 +367,24 @@ impl OpenShell for TestOpenShell { })) } + async fn get_sandbox_provider_status( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider readiness is not exercised by this mock", + )) + } + + async fn report_provider_readiness( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider installation reports are not exercised by this mock", + )) + } + async fn get_sandbox_provider_environment( &self, _request: tonic::Request, diff --git a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs index 50214b083f..316cd3d1d0 100644 --- a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs +++ b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs @@ -248,6 +248,24 @@ impl OpenShell for TestOpenShell { Ok(Response::new(GetGatewayConfigResponse::default())) } + async fn get_sandbox_provider_status( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider readiness is not exercised by this mock", + )) + } + + async fn report_provider_readiness( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider installation reports are not exercised by this mock", + )) + } + async fn get_sandbox_provider_environment( &self, _request: tonic::Request, diff --git a/crates/openshell-conformance/src/lib.rs b/crates/openshell-conformance/src/lib.rs index 6a424664a2..a9689be119 100644 --- a/crates/openshell-conformance/src/lib.rs +++ b/crates/openshell-conformance/src/lib.rs @@ -23,7 +23,7 @@ use tokio::time::sleep; use self::executor::{CliExecutionError, CliExecutor, ProcessCli}; -pub use scenarios::SMOKE_SCENARIO; +pub use scenarios::{SANDBOX_LIFECYCLE_SCENARIO, SMOKE_SCENARIO}; /// An installed conformance scenario. #[derive(Debug)] @@ -41,7 +41,7 @@ impl Scenario { } } -const SCENARIOS: &[Scenario] = &[SMOKE_SCENARIO]; +const SCENARIOS: &[Scenario] = &[SMOKE_SCENARIO, SANDBOX_LIFECYCLE_SCENARIO]; /// Returns every scenario compiled into this distribution. pub fn scenarios() -> &'static [Scenario] { diff --git a/crates/openshell-conformance/src/scenarios/mod.rs b/crates/openshell-conformance/src/scenarios/mod.rs index bd6abdc7af..a7bf2781f1 100644 --- a/crates/openshell-conformance/src/scenarios/mod.rs +++ b/crates/openshell-conformance/src/scenarios/mod.rs @@ -3,6 +3,8 @@ //! Registered, portable conformance scenarios. +mod sandbox_lifecycle; mod smoke; +pub use sandbox_lifecycle::SANDBOX_LIFECYCLE_SCENARIO; pub use smoke::SMOKE_SCENARIO; diff --git a/crates/openshell-conformance/src/scenarios/sandbox_lifecycle.rs b/crates/openshell-conformance/src/scenarios/sandbox_lifecycle.rs new file mode 100644 index 0000000000..a06de97a43 --- /dev/null +++ b/crates/openshell-conformance/src/scenarios/sandbox_lifecycle.rs @@ -0,0 +1,280 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Portable sandbox lifecycle conformance scenarios. + +use std::time::Duration; + +use serde::Deserialize; + +use crate::{OpenShellRunner, Poll, Scenario, ScenarioFuture}; + +const CREATE_TIMEOUT: Duration = Duration::from_mins(10); +const COMMAND_TIMEOUT: Duration = Duration::from_mins(2); +const TRANSITION_TIMEOUT: Duration = Duration::from_mins(4); +const TRANSITION_INTERVAL: Duration = Duration::from_secs(2); + +#[derive(Debug, Deserialize)] +struct SandboxState { + name: String, + phase: String, +} + +/// Certify sandbox stop, start, and deletion lifecycle behavior. +pub const SANDBOX_LIFECYCLE_SCENARIO: Scenario = Scenario { + name: "sandbox-lifecycle", + description: "Verify sandbox stop, start, and deletion lifecycle behavior.", + run: run_sandbox_lifecycle, +}; + +fn run_sandbox_lifecycle(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> { + Box::pin(async move { + stop_start_preserves_workspace(runner).await?; + stopped_can_be_deleted(runner).await + }) +} + +async fn stop_start_preserves_workspace(runner: &mut OpenShellRunner) -> Result<(), String> { + let sandbox_name = format!("ct-{}-ss", runner.id()); + let sentinel = format!("openshell-stop-start-{}", runner.id()); + let sentinel_path = "/sandbox/.openshell-stop-start-sentinel"; + let run_count_path = "/sandbox/.openshell-main-run-count"; + let main = format!( + "count=0; test ! -f '{run_count_path}' || count=$(cat '{run_count_path}'); \ + count=$((count + 1)); printf '%s\\n' \"$count\" > '{run_count_path}'; \ + exec sleep infinity" + ); + + create_running_sandbox(runner, &sandbox_name, &main, "stop-start").await?; + exec_expect_exact( + runner, + &sandbox_name, + "write-sentinel", + &[ + "sh", + "-lc", + &format!("printf '%s\\n' '{sentinel}' > '{sentinel_path}' && sync"), + ], + "", + ) + .await?; + + run_lifecycle_command(runner, "stop", &sandbox_name, "stop-start/stop").await?; + wait_for_phase(runner, &sandbox_name, "Stopped", "stop-start/stopped").await?; + + let stopped_exec = runner + .step("stop-start/exec-while-stopped") + .description(format!( + "sandbox '{sandbox_name}' rejects exec while stopped" + )) + .with_timeout(COMMAND_TIMEOUT) + .run(&[ + "sandbox", + "exec", + "--name", + &sandbox_name, + "--no-tty", + "--", + "cat", + sentinel_path, + ]) + .await + .map_err(|error| error.to_string())?; + if stopped_exec.success() { + return Err( + stopped_exec.failure_diagnostic("sandbox exec fails while the sandbox is stopped") + ); + } + + run_lifecycle_command(runner, "start", &sandbox_name, "stop-start/start").await?; + wait_for_phase(runner, &sandbox_name, "Ready", "stop-start/restarted").await?; + + exec_expect_exact( + runner, + &sandbox_name, + "read-sentinel", + &["cat", sentinel_path], + &format!("{sentinel}\n"), + ) + .await?; + exec_expect_exact( + runner, + &sandbox_name, + "read-main-run-count", + &["cat", run_count_path], + "2\n", + ) + .await +} + +async fn stopped_can_be_deleted(runner: &mut OpenShellRunner) -> Result<(), String> { + let sandbox_name = format!("ct-{}-sd", runner.id()); + create_running_sandbox( + runner, + &sandbox_name, + "exec sleep infinity", + "stopped-delete", + ) + .await?; + + run_lifecycle_command(runner, "stop", &sandbox_name, "stopped-delete/stop").await?; + wait_for_phase(runner, &sandbox_name, "Stopped", "stopped-delete/stopped").await?; + run_lifecycle_command(runner, "delete", &sandbox_name, "stopped-delete/delete").await?; + wait_for_absence(runner, &sandbox_name, "stopped-delete/deleted").await?; + runner.forget_sandbox(&sandbox_name); + Ok(()) +} + +async fn create_running_sandbox( + runner: &mut OpenShellRunner, + sandbox_name: &str, + main: &str, + step: &str, +) -> Result<(), String> { + runner.track_sandbox(sandbox_name); + let create = runner + .step(format!("{step}/create")) + .description(format!("sandbox '{sandbox_name}' is created")) + .with_timeout(CREATE_TIMEOUT) + .run(&[ + "sandbox", + "create", + "--name", + sandbox_name, + "--from", + "base", + "--detach", + "--no-tty", + "--", + "sh", + "-lc", + main, + ]) + .await + .map_err(|error| error.to_string())?; + create.require_success()?; + wait_for_phase(runner, sandbox_name, "Ready", &format!("{step}/ready")).await +} + +async fn run_lifecycle_command( + runner: &OpenShellRunner, + operation: &str, + sandbox_name: &str, + step: &str, +) -> Result<(), String> { + let result = runner + .step(step) + .description(format!("sandbox '{sandbox_name}' {operation} succeeds")) + .with_timeout(COMMAND_TIMEOUT) + .run(&["sandbox", operation, sandbox_name]) + .await + .map_err(|error| error.to_string())?; + result.require_success() +} + +async fn exec_expect_exact( + runner: &OpenShellRunner, + sandbox_name: &str, + step: &str, + command: &[&str], + expected_stdout: &str, +) -> Result<(), String> { + let mut args = vec!["sandbox", "exec", "--name", sandbox_name, "--no-tty", "--"]; + args.extend_from_slice(command); + let result = runner + .step(format!("stop-start/{step}")) + .description(format!("sandbox '{sandbox_name}' exec {step} succeeds")) + .with_timeout(COMMAND_TIMEOUT) + .run(&args) + .await + .map_err(|error| error.to_string())?; + result.require_success()?; + if result.stdout() == expected_stdout { + Ok(()) + } else { + Err(result.failure_diagnostic(&format!("stdout is exactly {expected_stdout:?}"))) + } +} + +async fn wait_for_phase( + runner: &mut OpenShellRunner, + sandbox_name: &str, + expected_phase: &str, + step: &str, +) -> Result<(), String> { + let sandbox_name = sandbox_name.to_string(); + let expected_phase = expected_phase.to_string(); + let step = step.to_string(); + let poll_step = step.clone(); + runner + .poll_until( + &poll_step, + TRANSITION_TIMEOUT, + TRANSITION_INTERVAL, + async move |runner| { + let result = runner + .step(format!("{step}/get")) + .description(format!( + "sandbox '{sandbox_name}' reaches phase {expected_phase}" + )) + .with_timeout(COMMAND_TIMEOUT) + .run(&["sandbox", "get", &sandbox_name, "--output", "json"]) + .await; + match result { + Ok(result) if !result.success() => { + Poll::Pending(result.failure_diagnostic(&format!( + "sandbox '{sandbox_name}' can be retrieved" + ))) + } + Ok(result) => match result.json::() { + Ok(state) if state.name != sandbox_name => Poll::Failed(format!( + "sandbox get returned {:?}; expected '{sandbox_name}'", + state.name + )), + Ok(state) if state.phase == expected_phase => Poll::Ready(()), + Ok(state) => Poll::Pending(format!( + "sandbox '{sandbox_name}' phase is {:?}; expected {expected_phase:?}", + state.phase + )), + Err(error) => Poll::Failed(error.to_string()), + }, + Err(error) => Poll::Pending(error.to_string()), + } + }, + ) + .await + .map_err(|error| error.to_string()) +} + +async fn wait_for_absence( + runner: &mut OpenShellRunner, + sandbox_name: &str, + step: &str, +) -> Result<(), String> { + let sandbox_name = sandbox_name.to_string(); + let step = step.to_string(); + let poll_step = step.clone(); + runner + .poll_until( + &poll_step, + TRANSITION_TIMEOUT, + TRANSITION_INTERVAL, + async move |runner| { + let result = runner + .step(format!("{step}/get")) + .description(format!("sandbox '{sandbox_name}' is no longer retrievable")) + .with_timeout(COMMAND_TIMEOUT) + .run(&["sandbox", "get", &sandbox_name, "--output", "json"]) + .await; + match result { + Ok(result) if !result.success() => Poll::Ready(()), + Ok(_) => { + Poll::Pending(format!("sandbox '{sandbox_name}' is still retrievable")) + } + Err(error) => Poll::Pending(error.to_string()), + } + }, + ) + .await + .map_err(|error| error.to_string()) +} diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index f9274701bd..fcdbe907e3 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -27,10 +27,11 @@ use crate::proto::{ DenialSummary, EndpointObservation as ProtoEndpointObservation, EndpointResult as ProtoEndpointResult, ExchangeProviderSubjectTokenRequest, GetDraftPolicyRequest, GetSandboxConfigRequest, GetSandboxProviderEnvironmentRequest, - IssueSandboxTokenRequest, NetworkActivitySummary, PolicyChunk, PolicySource, PolicyStatus, - RefreshSandboxTokenRequest, ReportEndpointStatusRequest, ReportPolicyStatusRequest, - SandboxPolicy as ProtoSandboxPolicy, SubmitPolicyAnalysisRequest, SubmitPolicyAnalysisResponse, - UpdateConfigRequest, open_shell_client::OpenShellClient, workspace_selector, + GetSandboxProviderEnvironmentResponse, IssueSandboxTokenRequest, NetworkActivitySummary, + PolicyChunk, PolicySource, PolicyStatus, RefreshSandboxTokenRequest, + ReportEndpointStatusRequest, ReportPolicyStatusRequest, SandboxPolicy as ProtoSandboxPolicy, + SubmitPolicyAnalysisRequest, SubmitPolicyAnalysisResponse, UpdateConfigRequest, + open_shell_client::OpenShellClient, workspace_selector, }; use crate::sandbox_env; use crate::time::{duration_to_std, timestamp_to_millis}; @@ -397,6 +398,26 @@ pub async fn connect_channel_pub(endpoint: &str) -> Result { connect_channel(endpoint).await } +/// Report installed provider state for the current authenticated supervisor session. +/// +/// The observation must carry the session ID returned by `ConnectSupervisor`. +/// Reconnects start a new report sequence; retries preserve the complete report. +pub async fn report_provider_readiness( + endpoint: &str, + sandbox_id: &str, + observation: crate::proto::ProviderReadinessObservation, +) -> Result { + let mut client = connect(endpoint).await?; + client + .report_provider_readiness(crate::proto::ReportProviderReadinessRequest { + sandbox_id: sandbox_id.to_string(), + observation: Some(observation), + }) + .await + .map(tonic::Response::into_inner) + .into_diagnostic() +} + /// Background task that renews the sandbox JWT at ~80% of its remaining /// lifetime. The new token replaces the value in [`TOKEN_SLOT`], so all /// in-flight and future clients pick it up on their next request. The @@ -1003,9 +1024,9 @@ pub async fn sync_policy_and_fetch_snapshot( /// Fetch provider environment variables for a sandbox from `OpenShell` server via gRPC. /// -/// Returns a map of environment variable names to values derived from provider -/// credentials configured on the sandbox. Returns an empty map if the sandbox -/// has no providers or the call fails. +/// Returns the credential snapshot and its exact readiness identity. An empty +/// environment represents a sandbox without provider credentials. Transport +/// failure returns an error so callers can revoke credentials and retry. pub async fn fetch_provider_environment( endpoint: &str, sandbox_id: &str, @@ -1022,7 +1043,14 @@ pub async fn fetch_provider_environment( .await .into_diagnostic()?; - let inner = response.into_inner(); + provider_environment_result(response.into_inner()) +} + +/// Preserve snapshot authority and reject invalid credential expiration times. +/// Unknown delivery reasons withhold credentials rather than implying readiness. +fn provider_environment_result( + inner: GetSandboxProviderEnvironmentResponse, +) -> Result { let credential_expires_at_ms = inner .credential_expiration_times .iter() @@ -1035,6 +1063,10 @@ pub async fn fetch_provider_environment( Ok(ProviderEnvironmentResult { environment: inner.environment, provider_env_revision: inner.provider_env_revision, + provider_attachment_epoch: inner.provider_attachment_epoch, + policy_hash: inner.policy_hash, + readiness_reason: crate::proto::ProviderReadinessReason::try_from(inner.readiness_reason) + .unwrap_or(crate::proto::ProviderReadinessReason::CredentialsWithheld), credential_expires_at_ms, dynamic_credentials: inner.dynamic_credentials, static_credential_bindings: inner.static_credential_bindings, @@ -1042,6 +1074,75 @@ pub async fn fetch_provider_environment( }) } +#[cfg(test)] +mod provider_environment_tests { + use super::*; + + #[test] + fn provider_environment_preserves_readiness_identity() { + let result = provider_environment_result(GetSandboxProviderEnvironmentResponse { + environment: HashMap::from([("TOKEN".to_string(), "synthetic".to_string())]), + provider_env_revision: 42, + provider_attachment_epoch: "attachment-epoch".to_string(), + policy_hash: "binding-policy".to_string(), + readiness_reason: crate::proto::ProviderReadinessReason::CredentialsWithheld.into(), + credential_expiration_times: HashMap::from([( + "TOKEN".to_string(), + prost_types::Timestamp { + seconds: 1_900_000_000, + nanos: 123_000_000, + }, + )]), + ..Default::default() + }) + .expect("valid provider environment"); + assert_eq!(result.provider_env_revision, 42); + assert_eq!(result.provider_attachment_epoch, "attachment-epoch"); + assert_eq!(result.policy_hash, "binding-policy"); + assert_eq!( + result.readiness_reason, + crate::proto::ProviderReadinessReason::CredentialsWithheld + ); + assert_eq!( + result.environment.get("TOKEN").map(String::as_str), + Some("synthetic") + ); + assert_eq!( + result.credential_expires_at_ms.get("TOKEN"), + Some(&1_900_000_000_123) + ); + } + + #[test] + fn provider_readiness_unknown_delivery_reason_is_withheld() { + let result = provider_environment_result(GetSandboxProviderEnvironmentResponse { + policy_hash: "binding-policy".to_string(), + readiness_reason: i32::MAX, + ..Default::default() + }) + .expect("valid provider environment"); + assert_eq!( + result.readiness_reason, + crate::proto::ProviderReadinessReason::CredentialsWithheld + ); + } + + #[test] + fn provider_environment_rejects_invalid_credential_expiration() { + let result = provider_environment_result(GetSandboxProviderEnvironmentResponse { + credential_expiration_times: HashMap::from([( + "TOKEN".to_string(), + prost_types::Timestamp { + seconds: 1_900_000_000, + nanos: -1, + }, + )]), + ..Default::default() + }); + assert!(result.is_err()); + } +} + pub async fn exchange_provider_subject_token( endpoint: &str, sandbox_id: &str, @@ -1127,6 +1228,8 @@ pub struct SettingsPollResult { /// When `policy_source` is `Global`, the version of the global policy revision. pub global_policy_version: u32, pub provider_env_revision: u64, + /// Attachment identity captured with this effective configuration. + pub provider_attachment_epoch: String, pub supervisor_middleware_services: Vec, /// Workspace the sandbox belongs to. pub workspace: String, @@ -1147,6 +1250,7 @@ fn settings_poll_result(inner: crate::proto::GetSandboxConfigResponse) -> Settin settings: inner.settings, global_policy_version: inner.global_policy_version, provider_env_revision: inner.provider_env_revision, + provider_attachment_epoch: inner.provider_attachment_epoch, supervisor_middleware_services: inner.supervisor_middleware_services, workspace: inner.workspace, policy_validation_failure_mode: inner @@ -1200,9 +1304,16 @@ mod settings_poll_tests { } } +/// Credential material and the authority snapshot that produced its bindings. pub struct ProviderEnvironmentResult { pub environment: HashMap, pub provider_env_revision: u64, + /// Attachment identity captured with the delivered credential records. + pub provider_attachment_epoch: String, + /// Effective policy used to derive the delivered endpoint bindings. + pub policy_hash: String, + /// Closed failure category; withheld material cannot establish readiness. + pub readiness_reason: crate::proto::ProviderReadinessReason, pub credential_expires_at_ms: HashMap, pub dynamic_credentials: HashMap, pub static_credential_bindings: HashMap, diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 4d893fa362..beec21de37 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -17,11 +17,27 @@ const MAX_RETAINED_CREDENTIAL_GENERATIONS: usize = 8; #[derive(Debug, Clone, Default)] pub struct ProviderCredentialSnapshot { + /// Identifies this local installation, including repairs at the same revision. + pub installation_id: String, pub revision: u64, pub child_env: HashMap, pub dynamic_credentials: HashMap, } +/// One atomic workload-facing snapshot and its local installation identity. +/// +/// Only the prepared environment crosses an isolation boundary; resolver +/// material remains in the supervisor. The identity distinguishes an empty +/// fail-closed snapshot from a later repair with the same provider revision. +pub struct ChildEnvironmentSnapshot { + /// Opaque identity of the installed supervisor snapshot. + pub installation_id: String, + /// Opaque provider content fingerprint, never an ordered counter. + pub revision: u64, + /// Prepared environment used by future workload processes. + pub environment: HashMap, +} + #[derive(Debug)] struct ProviderCredentialStateInner { current: Arc, @@ -89,6 +105,7 @@ impl ProviderCredentialState { revision, ); let snapshot = Arc::new(ProviderCredentialSnapshot { + installation_id: uuid::Uuid::new_v4().to_string(), revision, child_env, dynamic_credentials, @@ -136,6 +153,7 @@ impl ProviderCredentialState { &stable_handles, ); let snapshot = Arc::new(ProviderCredentialSnapshot { + installation_id: uuid::Uuid::new_v4().to_string(), revision, child_env, dynamic_credentials, @@ -178,6 +196,7 @@ impl ProviderCredentialState { /// or holding the gateway-side resolver material. pub fn from_child_env_snapshot(revision: u64, child_env: HashMap) -> Self { let snapshot = Arc::new(ProviderCredentialSnapshot { + installation_id: uuid::Uuid::new_v4().to_string(), revision, child_env, dynamic_credentials: HashMap::new(), @@ -221,6 +240,7 @@ impl ProviderCredentialState { } inner.current = Arc::new(ProviderCredentialSnapshot { + installation_id: uuid::Uuid::new_v4().to_string(), revision, child_env, dynamic_credentials: HashMap::new(), @@ -386,6 +406,7 @@ impl ProviderCredentialState { inner.suppressed_keys.insert(key.to_string()); let mut env = (*inner.current).clone(); env.child_env.remove(key); + env.installation_id = uuid::Uuid::new_v4().to_string(); inner.current = Arc::new(env); } @@ -431,6 +452,20 @@ impl ProviderCredentialState { Ok(Self::resolve_child_env_snapshot(&inner)) } + /// Capture installation identity and prepared environment under one lock. + pub fn child_environment_snapshot(&self) -> std::io::Result { + let inner = self + .inner + .read() + .map_err(|_| std::io::Error::other("provider credential state poisoned"))?; + let (revision, environment) = Self::resolve_child_env_snapshot(&inner); + Ok(ChildEnvironmentSnapshot { + installation_id: inner.current.installation_id.clone(), + revision, + environment, + }) + } + fn resolve_child_env_snapshot( inner: &ProviderCredentialStateInner, ) -> (u64, HashMap) { @@ -491,8 +526,9 @@ impl ProviderCredentialState { /// Compare and install a workload-facing environment snapshot. /// /// Provider environment revisions are opaque content identities, not - /// ordered counters. The expected revision makes retries idempotent while - /// rejecting updates based on a stale view of the boundary state. + /// ordered counters. The expected revision rejects a different current + /// fingerprint. Callers must also fence publication order when a failed + /// refresh and its repair can share that fingerprint. pub fn compare_and_install_child_env_snapshot( &self, expected_revision: u64, @@ -503,14 +539,19 @@ impl ProviderCredentialState { .inner .write() .map_err(|_| std::io::Error::other("provider credential state poisoned"))?; - if revision == inner.current.revision || expected_revision != inner.current.revision { + if expected_revision != inner.current.revision { return Ok(inner.current.revision); } + // A failed refresh can clear the map without changing its provider + // fingerprint. A matching expectation must therefore install even an + // equal revision. Boundary publication ordering fences delayed retries. + for key in &inner.suppressed_keys { child_env.remove(key); } inner.current = Arc::new(ProviderCredentialSnapshot { + installation_id: uuid::Uuid::new_v4().to_string(), revision, child_env, dynamic_credentials: HashMap::new(), @@ -587,6 +628,7 @@ impl ProviderCredentialState { } inner.current = Arc::new(ProviderCredentialSnapshot { + installation_id: uuid::Uuid::new_v4().to_string(), revision, child_env, dynamic_credentials, @@ -652,6 +694,7 @@ impl ProviderCredentialState { child_env.remove(key); } inner.current = Arc::new(ProviderCredentialSnapshot { + installation_id: uuid::Uuid::new_v4().to_string(), revision, child_env, dynamic_credentials, @@ -711,6 +754,7 @@ impl ProviderCredentialState { let dynamic_credentials = dynamic_credentials.unwrap_or_else(|| inner.current.dynamic_credentials.clone()); inner.current = Arc::new(ProviderCredentialSnapshot { + installation_id: uuid::Uuid::new_v4().to_string(), revision, child_env: HashMap::new(), dynamic_credentials, @@ -2427,6 +2471,26 @@ mod tests { assert!(env.is_empty(), "an empty snapshot must revoke the old env"); } + #[test] + fn child_environment_repair_replaces_an_empty_map_at_the_same_revision() { + let state = ProviderCredentialState::from_child_env_snapshot(6, HashMap::new()); + let failed = state.child_environment_snapshot().unwrap(); + state + .compare_and_install_child_env_snapshot( + 6, + 6, + HashMap::from([("TOKEN".to_string(), "reference".to_string())]), + ) + .unwrap(); + let repaired = state.child_environment_snapshot().unwrap(); + assert_ne!(failed.installation_id, repaired.installation_id); + assert_eq!(repaired.revision, 6); + assert_eq!( + repaired.environment.get("TOKEN").map(String::as_str), + Some("reference") + ); + } + #[test] fn poisoned_environment_update_returns_error_without_recovering_state() { let state = ProviderCredentialState::from_child_env_snapshot(4, HashMap::new()); diff --git a/crates/openshell-gateway-interceptors/src/proto_json.rs b/crates/openshell-gateway-interceptors/src/proto_json.rs index dde37190e6..0419bbd225 100644 --- a/crates/openshell-gateway-interceptors/src/proto_json.rs +++ b/crates/openshell-gateway-interceptors/src/proto_json.rs @@ -308,6 +308,7 @@ mod tests { let codec = ProtoJsonCodec::from_descriptor_set(openshell_core::FILE_DESCRIPTOR_SET).unwrap(); let request = CreateSandboxRequest { + request_id: String::new(), spec: Some(SandboxSpec { providers: vec!["github".to_string()], ..SandboxSpec::default() @@ -336,6 +337,7 @@ mod tests { fn interceptor_view_omits_nested_secrets_but_keeps_non_secret_fields() { let codec = ProtoJsonCodec::openshell().unwrap(); let request = CreateProviderRequest { + request_id: String::new(), provider: Some(Provider { r#type: "github".to_string(), credentials: HashMap::from([( @@ -396,6 +398,7 @@ mod tests { fn generic_sandbox_environment_remains_visible() { let codec = ProtoJsonCodec::openshell().unwrap(); let request = CreateSandboxRequest { + request_id: String::new(), spec: Some(SandboxSpec { environment: HashMap::from([("FEATURE_FLAG".to_string(), "on".to_string())]), ..SandboxSpec::default() diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index 0bd1ba2b47..91ea949feb 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -755,6 +755,7 @@ mod tests { fn create_provider_operation(codec: &ProtoJsonCodec) -> ValidatedOperation { let request = CreateProviderRequest { + request_id: String::new(), provider: Some(Provider { r#type: "github".to_string(), credentials: HashMap::from([( @@ -1009,6 +1010,7 @@ mod tests { codec: codec.clone(), }; let request = UpdateConfigRequest { + request_id: String::new(), name: "demo".to_string(), expected_resource_version: u64::MAX - 1, annotations: HashMap::from([ @@ -1049,6 +1051,7 @@ mod tests { let codec = ProtoJsonCodec::from_descriptor_set(openshell_core::FILE_DESCRIPTOR_SET).unwrap(); let request = CreateSandboxRequest { + request_id: String::new(), spec: Some(SandboxSpec { template: Some(SandboxTemplate { resources: Some( diff --git a/crates/openshell-isolation-interface/src/contract.rs b/crates/openshell-isolation-interface/src/contract.rs index f671dd99e9..8e68d48c77 100644 --- a/crates/openshell-isolation-interface/src/contract.rs +++ b/crates/openshell-isolation-interface/src/contract.rs @@ -762,6 +762,30 @@ pub struct ExecSpec { pub trait BoundaryExec: Send + Sync { /// Spawn `spec` inside the boundary, returning an owned session. async fn exec(&self, spec: ExecSpec) -> Result; + + /// Install the current provider environment for future process launches. + /// + /// Success requires an authenticated acknowledgment from the running + /// boundary. Implementations serialize this operation with exec so an + /// older publication cannot replace the acknowledged environment. + async fn synchronize_provider_environment( + &self, + ) -> Result { + Err(BackendError::Unsupported( + "provider environment installation acknowledgment is unavailable".to_string(), + )) + } +} + +/// Evidence that the running workload boundary installed one provider snapshot. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProviderEnvironmentInstallation { + /// Local supervisor snapshot that produced the acknowledged environment. + pub installation_id: String, + /// Opaque provider content fingerprint. + pub revision: u64, + /// Authenticated and confirmed workload boundary session. + pub session_id: SandboxSessionId, } // ============================================================================ diff --git a/crates/openshell-prover-cli/Cargo.toml b/crates/openshell-prover-cli/Cargo.toml new file mode 100644 index 0000000000..337a97565d --- /dev/null +++ b/crates/openshell-prover-cli/Cargo.toml @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-prover-cli" +description = "Standalone OpenShell policy boundary checker" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[[bin]] +name = "openshell-prover" +path = "src/main.rs" + +[features] +bundled-z3 = ["openshell-prover/bundled-z3"] +prebuilt-z3 = ["openshell-prover/prebuilt-z3"] + +[dependencies] +clap.workspace = true +openshell-prover = { path = "../openshell-prover" } +serde.workspace = true +serde_json.workspace = true + +[target.'cfg(unix)'.dependencies] +nix.workspace = true +signal-hook.workspace = true + +[lints] +workspace = true diff --git a/crates/openshell-prover-cli/README.md b/crates/openshell-prover-cli/README.md new file mode 100644 index 0000000000..9b9488b8c4 --- /dev/null +++ b/crates/openshell-prover-cli/README.md @@ -0,0 +1,34 @@ + + +# OpenShell policy prover CLI + +This package builds the standalone `openshell-prover` executable. It is a thin synchronous adapter around the reusable containment engine in `openshell-prover`; it owns local file loading, command parsing, result rendering, and process exit codes. + +```shell +openshell-prover check candidate.yaml --boundary boundary.yaml +openshell-prover check candidate.yaml --boundary boundary.yaml --output json +``` + +The command checks whether a fully composed candidate policy stays within an operator-supplied boundary. It does not discover a gateway, fetch policy state, or apply policy changes. + +Results use these exit codes: + +| Exit code | Meaning | +| --- | --- | +| `0` | The candidate is within the boundary. | +| `1` | The candidate exceeds the boundary. | +| `2` | Usage, input, output, or internal error. | +| `3` | Unsupported policy semantics or an inconclusive solve. | +| `130` | Interrupted with Ctrl-C on Unix; graceful JSON output reports an inconclusive cancellation. | + +Build and test the package with: + +```shell +cargo build -p openshell-prover-cli --bin openshell-prover +cargo test -p openshell-prover-cli +``` + +See the [policy prover reference](../../docs/reference/policy-prover.mdx) for installed usage and interpretation guidance. diff --git a/crates/openshell-prover-cli/src/main.rs b/crates/openshell-prover-cli/src/main.rs new file mode 100644 index 0000000000..4dd621eade --- /dev/null +++ b/crates/openshell-prover-cli/src/main.rs @@ -0,0 +1,573 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Standalone policy boundary checker. + +#[cfg(not(unix))] +use std::fs::File; +#[cfg(unix)] +use std::fs::OpenOptions; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use clap::{CommandFactory, Parser, Subcommand, ValueEnum}; +use openshell_prover::containment::{ + CheckOptions, CheckResult, CheckScope, ContainmentPolicy, Counterexample, parse_policy_str, +}; +use serde::Serialize; + +const MAX_POLICY_BYTES: u64 = 4 * 1024 * 1024; + +#[derive(Debug, Parser)] +#[command( + name = "openshell-prover", + about = "Verify OpenShell policy boundaries", + version +)] +struct Cli { + #[command(subcommand)] + command: Option, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Check whether a candidate policy is contained within a boundary policy. + Check { + /// Fully composed effective candidate policy. + candidate: PathBuf, + /// Operator-owned boundary policy. + #[arg(long, value_name = "FILE")] + boundary: PathBuf, + /// Result output format. + #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)] + output: OutputFormat, + /// Solver time budget (integer followed by ms, s, or m). + #[arg(long, default_value = "10s", value_parser = parse_duration)] + timeout: Duration, + }, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)] +enum OutputFormat { + Text, + Json, +} + +#[derive(Debug, Serialize)] +struct Envelope<'a> { + schema_version: u32, + prover_version: &'static str, + check: &'static str, + scope: Option>, + result: &'static str, + exit_code: u8, + inputs: InputsJson, + counterexample: Option>, + reason_code: Option<&'a str>, + reason: Option<&'a str>, +} + +#[derive(Debug, Serialize)] +struct ScopeJson<'a> { + model_version: &'a str, + policy_version: u32, + domains: Vec<&'a str>, +} + +#[derive(Debug, Serialize)] +struct InputsJson { + candidate: String, + boundary: String, +} + +#[derive(Debug, Serialize)] +#[serde(tag = "domain", rename_all = "snake_case")] +enum CounterexampleJson<'a> { + Filesystem { + access: &'a str, + path: &'a str, + }, + Network { + binary: Option<&'a str>, + ancestor_binary: Option<&'a str>, + binary_identity_required: bool, + host: &'a str, + port: u16, + protocol: &'a str, + method: Option<&'a str>, + path: Option<&'a str>, + }, +} + +fn main() -> ExitCode { + let cancelled = Arc::new(AtomicBool::new(false)); + #[cfg(unix)] + if let Err(error) = signal_hook::flag::register_conditional_shutdown( + signal_hook::consts::signal::SIGINT, + 130, + Arc::clone(&cancelled), + ) + .and_then(|_| { + signal_hook::flag::register(signal_hook::consts::signal::SIGINT, Arc::clone(&cancelled)) + }) { + let _ = writeln!( + io::stderr().lock(), + "openshell-prover: cannot install Ctrl-C handler: {error}" + ); + return ExitCode::from(2); + } + let cli = Cli::parse(); + let outcome = cli + .command + .map_or_else(show_help, |command| execute(command, &cancelled)); + + match outcome { + Ok(code) => ExitCode::from(code), + Err(error) => { + let _ = writeln!(io::stderr().lock(), "openshell-prover: {error}"); + ExitCode::from(2) + } + } +} + +fn show_help() -> Result { + Cli::command() + .print_help() + .map_err(|error| format!("failed to write help: {error}"))?; + writeln!(io::stdout().lock()).map_err(|error| format!("failed to write output: {error}"))?; + Ok(0) +} + +fn execute(command: Command, cancelled: &AtomicBool) -> Result { + match command { + Command::Check { + candidate, + boundary, + output, + timeout, + } => check(&candidate, &boundary, output, timeout, cancelled), + } +} + +fn check( + candidate_path: &Path, + boundary_path: &Path, + output: OutputFormat, + timeout: Duration, + cancelled: &AtomicBool, +) -> Result { + let inputs = InputsJson { + candidate: candidate_path.to_string_lossy().into_owned(), + boundary: boundary_path.to_string_lossy().into_owned(), + }; + + let candidate_source = match read_policy(candidate_path) { + Ok(source) => source, + Err(error) => return render_input_error(output, inputs, &error), + }; + if cancelled.load(Ordering::Relaxed) { + return render_cancelled(output, inputs); + } + let boundary_source = match read_policy(boundary_path) { + Ok(source) => source, + Err(error) => return render_input_error(output, inputs, &error), + }; + if cancelled.load(Ordering::Relaxed) { + return render_cancelled(output, inputs); + } + let candidate = match parse_input("candidate", &candidate_source) { + Ok(policy) => policy, + Err(error) => return render_input_error(output, inputs, &error), + }; + let boundary = match parse_input("boundary", &boundary_source) { + Ok(policy) => policy, + Err(error) => return render_input_error(output, inputs, &error), + }; + if cancelled.load(Ordering::Relaxed) { + return render_cancelled(output, inputs); + } + + let result = openshell_prover::containment::check_within_boundary_cancellable( + &boundary, + &candidate, + CheckOptions::new(timeout), + cancelled, + ); + let envelope = result_envelope(&result, inputs)?; + render(output, &envelope)?; + Ok(envelope.exit_code) +} + +fn parse_input(label: &str, source: &str) -> Result { + parse_policy_str(source).map_err(|error| { + format!( + "invalid {label} policy: {}", + escape_terminal(&error.to_string()) + ) + }) +} + +fn read_policy(path: &Path) -> Result { + // Reject unsupported inputs before opening them where possible. On Unix, + // also use O_NONBLOCK to close the replacement race between this check and + // open(): opening a FIFO must never hang the CLI before cancellation can be + // observed. O_NONBLOCK has no effect on reads from regular files. + let path_metadata = path.metadata().map_err(|error| { + format!( + "cannot open '{}': {error}", + escape_terminal(&path.to_string_lossy()) + ) + })?; + if !path_metadata.is_file() { + return Err(format!( + "policy path '{}' is not a regular file", + escape_terminal(&path.to_string_lossy()) + )); + } + + #[cfg(unix)] + let open_result = { + use std::os::unix::fs::OpenOptionsExt as _; + OpenOptions::new() + .read(true) + .custom_flags(nix::libc::O_NONBLOCK) + .open(path) + }; + #[cfg(not(unix))] + let open_result = File::open(path); + + let mut file = open_result.map_err(|error| { + format!( + "cannot open '{}': {error}", + escape_terminal(&path.to_string_lossy()) + ) + })?; + let metadata = file + .metadata() + .map_err(|error| format!("cannot inspect policy file: {error}"))?; + if !metadata.is_file() { + return Err(format!( + "policy path '{}' is not a regular file", + escape_terminal(&path.to_string_lossy()) + )); + } + if metadata.len() > MAX_POLICY_BYTES { + return Err(format!( + "policy file exceeds the {MAX_POLICY_BYTES}-byte input limit" + )); + } + + let mut bytes = Vec::new(); + Read::by_ref(&mut file) + .take(MAX_POLICY_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|error| format!("cannot read policy file: {error}"))?; + if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_POLICY_BYTES { + return Err(format!( + "policy file exceeds the {MAX_POLICY_BYTES}-byte input limit" + )); + } + String::from_utf8(bytes).map_err(|_| "policy file is not valid UTF-8".to_owned()) +} + +fn render_input_error( + output: OutputFormat, + inputs: InputsJson, + reason: &str, +) -> Result { + if output == OutputFormat::Json { + let envelope = Envelope { + schema_version: 1, + prover_version: env!("CARGO_PKG_VERSION"), + check: "boundary", + scope: None, + result: "error", + exit_code: 2, + inputs, + counterexample: None, + reason_code: Some("invalid_input"), + reason: Some(reason), + }; + render(output, &envelope)?; + } else { + writeln!(io::stderr().lock(), "openshell-prover: {reason}") + .map_err(|error| format!("failed to write diagnostic: {error}"))?; + } + Ok(2) +} + +fn render_cancelled(output: OutputFormat, inputs: InputsJson) -> Result { + let result = CheckResult::cancelled(); + let envelope = result_envelope(&result, inputs)?; + render(output, &envelope)?; + Ok(envelope.exit_code) +} + +fn result_envelope(result: &CheckResult, inputs: InputsJson) -> Result, String> { + let (scope, result_name, exit_code, counterexample, reason_code, reason) = match result { + CheckResult::Within(evidence) => (evidence.scope(), "within_boundary", 0, None, None, None), + CheckResult::Exceeds(evidence) => ( + evidence.scope(), + "exceeds_boundary", + 1, + Some(counterexample_json(evidence.counterexample())?), + None, + None, + ), + CheckResult::Unsupported(evidence) => ( + evidence.scope(), + "unsupported", + 3, + None, + Some(evidence.reason_code().as_str()), + Some(evidence.reason()), + ), + CheckResult::Inconclusive(evidence) => { + let exit_code = + if evidence.reason_code() == openshell_prover::containment::ReasonCode::Cancelled { + 130 + } else { + 3 + }; + ( + evidence.scope(), + "inconclusive", + exit_code, + None, + Some(evidence.reason_code().as_str()), + Some(evidence.reason()), + ) + } + }; + Ok(Envelope { + schema_version: 1, + prover_version: env!("CARGO_PKG_VERSION"), + check: "boundary", + scope: Some(scope_json(scope)), + result: result_name, + exit_code, + inputs, + counterexample, + reason_code, + reason, + }) +} + +fn scope_json(scope: &CheckScope) -> ScopeJson<'_> { + ScopeJson { + model_version: scope.model_version, + policy_version: scope.policy_version, + domains: scope.domains.iter().map(|domain| domain.as_str()).collect(), + } +} + +fn counterexample_json(counterexample: &Counterexample) -> Result, String> { + let converted = match counterexample { + Counterexample::Filesystem { access, path, .. } => CounterexampleJson::Filesystem { + access: access.as_str(), + path, + }, + Counterexample::Network { + binary, + ancestor_binary, + binary_identity_required, + host, + port, + protocol, + method, + path, + .. + } => CounterexampleJson::Network { + binary: binary.as_deref(), + ancestor_binary: ancestor_binary.as_deref(), + binary_identity_required: *binary_identity_required, + host, + port: *port, + protocol: protocol.as_str(), + method: method.as_deref(), + path: path.as_deref(), + }, + _ => return Err("unsupported counterexample kind returned by containment API".to_owned()), + }; + Ok(converted) +} + +fn render(output: OutputFormat, envelope: &Envelope<'_>) -> Result<(), String> { + let stdout = io::stdout(); + let mut stdout = stdout.lock(); + match output { + OutputFormat::Json => { + serde_json::to_writer_pretty(&mut stdout, envelope) + .map_err(|error| format!("failed to serialize result: {error}"))?; + writeln!(stdout).map_err(|error| format!("failed to write output: {error}")) + } + OutputFormat::Text => render_text(&mut stdout, envelope), + } +} + +fn render_text(mut writer: impl Write, envelope: &Envelope<'_>) -> Result<(), String> { + writeln!(writer, "result: {}", envelope.result) + .map_err(|error| format!("failed to write output: {error}"))?; + if let Some(scope) = &envelope.scope { + writeln!( + writer, + "scope: model={} policy={} domains={}", + escape_terminal(scope.model_version), + scope.policy_version, + scope.domains.join(",") + ) + .map_err(|error| format!("failed to write output: {error}"))?; + } + if let Some(counterexample) = &envelope.counterexample { + match counterexample { + CounterexampleJson::Filesystem { access, path } => writeln!( + writer, + "counterexample: filesystem {access} {}", + escape_terminal(path) + ), + CounterexampleJson::Network { + binary, + ancestor_binary, + binary_identity_required, + host, + port, + protocol, + method, + path, + } => writeln!( + writer, + "counterexample: network binary={} ancestor_binary={} binary_identity_required={} host={}:{} protocol={} method={} path={}", + binary.map_or("-".to_owned(), escape_terminal), + ancestor_binary.map_or("-".to_owned(), escape_terminal), + binary_identity_required, + escape_terminal(host), + port, + escape_terminal(protocol), + method.map_or("-".to_owned(), escape_terminal), + path.map_or("-".to_owned(), escape_terminal), + ), + } + .map_err(|error| format!("failed to write output: {error}"))?; + } + if let Some(reason) = envelope.reason { + writeln!(writer, "reason: {}", escape_terminal(reason)) + .map_err(|error| format!("failed to write output: {error}"))?; + } + Ok(()) +} + +fn parse_duration(value: &str) -> Result { + let (number, multiplier) = if let Some(number) = value.strip_suffix("ms") { + (number, 1_u64) + } else if let Some(number) = value.strip_suffix('s') { + (number, 1_000) + } else if let Some(number) = value.strip_suffix('m') { + (number, 60_000) + } else { + return Err("duration must end in ms, s, or m".to_owned()); + }; + let amount = number + .parse::() + .map_err(|_| "duration must use a positive integer".to_owned())?; + let millis = amount + .checked_mul(multiplier) + .ok_or_else(|| "duration is too large".to_owned())?; + if millis == 0 { + return Err("duration must be positive".to_owned()); + } + if millis > u64::from(u32::MAX) { + return Err(format!("duration must not exceed {}ms", u32::MAX)); + } + Ok(Duration::from_millis(millis)) +} + +fn escape_terminal(value: &str) -> String { + let mut escaped = String::with_capacity(value.len()); + for character in value.chars() { + if character.is_control() { + escaped.extend(character.escape_default()); + } else { + escaped.push(character); + } + } + escaped +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs::OpenOptions; + + struct BrokenWriter; + + impl Write for BrokenWriter { + fn write(&mut self, _buffer: &[u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "closed")) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + #[test] + fn parses_supported_durations() { + assert_eq!(parse_duration("250ms"), Ok(Duration::from_millis(250))); + assert_eq!(parse_duration("2s"), Ok(Duration::from_secs(2))); + assert_eq!(parse_duration("3m"), Ok(Duration::from_mins(3))); + } + + #[test] + fn rejects_invalid_durations() { + for value in ["0ms", "1", "1.5s", "-1s", "4294967296ms"] { + assert!(parse_duration(value).is_err(), "accepted {value}"); + } + } + + #[test] + fn escapes_terminal_control_characters() { + assert_eq!(escape_terminal("a\u{1b}[31m\nb"), "a\\u{1b}[31m\\nb"); + } + + #[test] + fn rejects_oversized_policy_before_parsing() { + let path = + std::env::temp_dir().join(format!("openshell-prover-oversized-{}", std::process::id())); + let file = OpenOptions::new() + .create_new(true) + .write(true) + .open(&path) + .expect("create oversized fixture"); + file.set_len(MAX_POLICY_BYTES + 1) + .expect("size oversized fixture"); + drop(file); + + let error = read_policy(&path).expect_err("oversized input must fail"); + std::fs::remove_file(path).expect("remove oversized fixture"); + assert!(error.contains("input limit")); + } + + #[test] + fn output_failures_are_reported() { + let envelope = Envelope { + schema_version: 1, + prover_version: env!("CARGO_PKG_VERSION"), + check: "boundary", + scope: None, + result: "within_boundary", + exit_code: 0, + inputs: InputsJson { + candidate: "candidate.yaml".to_owned(), + boundary: "boundary.yaml".to_owned(), + }, + counterexample: None, + reason_code: None, + reason: None, + }; + assert!(render_text(BrokenWriter, &envelope).is_err()); + } +} diff --git a/crates/openshell-prover-cli/tests/cli.rs b/crates/openshell-prover-cli/tests/cli.rs new file mode 100644 index 0000000000..5c8fa44f99 --- /dev/null +++ b/crates/openshell-prover-cli/tests/cli.rs @@ -0,0 +1,616 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::fmt::Write as _; +use std::fs; +use std::path::PathBuf; +#[cfg(unix)] +use std::process::Stdio; +use std::process::{Command, Output}; +#[cfg(unix)] +use std::thread; +#[cfg(unix)] +use std::time::Duration; + +use serde_json::Value; + +fn fixture(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(name) +} + +fn run(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_openshell-prover")) + .args(args) + .output() + .expect("run openshell-prover") +} + +fn check_json(candidate: &str, boundary: &str) -> Output { + run(&[ + "check", + fixture(candidate).to_str().expect("UTF-8 fixture path"), + "--boundary", + fixture(boundary).to_str().expect("UTF-8 fixture path"), + "--output", + "json", + ]) +} + +#[test] +fn help_and_version_succeed() { + for args in [ + &["--help"][..], + &["--version"][..], + &["check", "--help"][..], + ] { + let output = run(args); + assert!( + output.status.success(), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(!output.stdout.is_empty()); + } +} + +#[test] +fn bare_invocation_shows_help() { + let output = run(&[]); + assert!(output.status.success()); + assert!(String::from_utf8_lossy(&output.stdout).contains("Usage:")); +} + +#[test] +fn contained_policy_returns_stable_json_and_zero() { + let output = check_json("candidate-contained.yaml", "boundary.yaml"); + assert_eq!( + output.status.code(), + Some(0), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + assert!(output.stderr.is_empty()); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["schema_version"], 1); + assert_eq!(value["check"], "boundary"); + assert_eq!(value["result"], "within_boundary"); + assert_eq!(value["exit_code"], 0); + assert_eq!( + value["scope"], + serde_json::json!({ + "model_version": "boundary-v1", + "policy_version": 1, + "domains": ["filesystem", "network_l4", "network_rest"] + }) + ); + assert!(value["counterexample"].is_null()); +} + +#[test] +fn exceeding_policy_returns_counterexample_and_one() { + let output = check_json("candidate-exceeds.yaml", "boundary-no-write.yaml"); + assert_eq!( + output.status.code(), + Some(1), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "exceeds_boundary"); + assert_eq!(value["exit_code"], 1); + assert_eq!(value["counterexample"]["domain"], "filesystem"); +} + +#[test] +fn unsupported_policy_returns_reason_and_three() { + let output = check_json("unsupported.yaml", "boundary.yaml"); + assert_eq!( + output.status.code(), + Some(3), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "unsupported"); + assert_eq!(value["exit_code"], 3); + assert!(value["reason_code"].is_string()); + assert!(value["reason"].is_string()); +} + +#[test] +fn unsupported_network_surfaces_fail_closed_at_the_cli_boundary() { + let cases = [ + ( + "l4", + " path: /v1\n", + "mixes REST controls into L4 authority", + ), + ( + "rest", + " protocol: rest\n enforcement: log\n access: full\n", + "uses REST without enforced inspection", + ), + ( + "graphql", + " protocol: rest\n enforcement: enforce\n access: full\n persisted_queries: allow-list\n", + "uses authority outside the initial model", + ), + ( + "json-rpc", + " protocol: rest\n enforcement: enforce\n access: full\n json_rpc: {}\n", + "uses authority outside the initial model", + ), + ( + "mcp", + " protocol: mcp\n enforcement: enforce\n access: full\n mcp: {}\n", + "uses authority outside the initial model", + ), + ]; + + for (surface, endpoint_fields, expected_reason) in cases { + let path = std::env::temp_dir().join(format!( + "openshell-prover-unsupported-{surface}-{}.yaml", + std::process::id() + )); + fs::write( + &path, + format!( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n{endpoint_fields} binaries: [{{ path: /usr/bin/curl }}]\n" + ), + ) + .expect("write unsupported surface policy"); + + let output = run(&[ + "check", + path.to_str().expect("UTF-8 temporary path"), + "--boundary", + fixture("boundary-empty.yaml").to_str().unwrap(), + "--output", + "json", + ]); + fs::remove_file(path).expect("remove unsupported surface policy"); + + assert_eq!( + output.status.code(), + Some(3), + "{surface} stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "unsupported", "{surface}: {value}"); + assert_eq!( + value["reason_code"], "unsupported_policy_shape", + "{surface}: {value}" + ); + assert!( + value["reason"] + .as_str() + .is_some_and(|reason| reason.contains(expected_reason)), + "{surface}: {value}" + ); + } +} + +#[test] +fn canonical_schema_errors_fail_closed_in_both_inputs() { + let cases = [ + "version: 1\nmetadata: { policy_id: boundary }\n", + "version: 1\nfilesystem_policy: null\n", + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443, review: { required: true } }]\n", + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ rules: [{ allow: { method: GET, review: {} } }] }]\n", + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ credential_binding: { provider: demo, future: true } }]\n", + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ protocol: rest, mcp: {} }]\n", + r#"{"version":1,"version":1}"#, + r#"{"version":1,"future_authority":true}"#, + ]; + let path = std::env::temp_dir().join(format!( + "openshell-prover-schema-errors-{}.yaml", + std::process::id() + )); + let empty = fixture("boundary-empty.yaml"); + for source in cases { + fs::write(&path, source).expect("write invalid authored policy"); + for (candidate, boundary) in [(&path, &empty), (&empty, &path)] { + let output = run(&[ + "check", + candidate.to_str().unwrap(), + "--boundary", + boundary.to_str().unwrap(), + "--output", + "json", + ]); + assert_eq!(output.status.code(), Some(2), "source={source}"); + assert!(output.stderr.is_empty()); + let value: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(value["result"], "error"); + assert_eq!(value["reason_code"], "invalid_input"); + assert!(value["counterexample"].is_null()); + } + } + fs::remove_file(path).expect("remove invalid authored policy"); +} + +#[test] +fn underscore_host_exceeds_an_empty_boundary() { + let output = check_json("candidate-underscore-host.yaml", "boundary-empty.yaml"); + assert_eq!( + output.status.code(), + Some(1), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "exceeds_boundary"); + assert_eq!(value["counterexample"]["host"], "api_internal.example.com"); +} + +#[test] +fn non_ascii_network_literals_are_unsupported_in_both_inputs() { + for (candidate, boundary, input_label) in [ + ( + "candidate-unicode-network-selector.yaml", + "boundary-empty.yaml", + "candidate", + ), + ( + "boundary-empty.yaml", + "candidate-unicode-network-selector.yaml", + "boundary", + ), + ] { + let output = check_json(candidate, boundary); + assert_eq!( + output.status.code(), + Some(3), + "{input_label} stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "unsupported"); + assert_eq!(value["reason_code"], "unsupported_policy_shape"); + assert!( + value["reason"] + .as_str() + .is_some_and(|reason| reason.contains(input_label) && reason.contains("non-ASCII")), + "{value}" + ); + } + + let output = run(&[ + "check", + fixture("candidate-unicode-network-selector.yaml") + .to_str() + .unwrap(), + "--boundary", + fixture("boundary-empty.yaml").to_str().unwrap(), + ]); + assert_eq!(output.status.code(), Some(3)); + assert!(output.stderr.is_empty()); + let text = String::from_utf8(output.stdout).expect("UTF-8 text output"); + assert!(text.contains("result: unsupported"), "{text}"); + assert!(text.contains("candidate policy"), "{text}"); + assert!(text.contains("non-ASCII"), "{text}"); +} + +#[test] +fn embedded_nul_network_literal_is_unsupported_without_panicking() { + let path = std::env::temp_dir().join(format!( + "openshell-prover-nul-selector-{}.yaml", + std::process::id() + )); + fs::write( + &path, + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: \"G\\0ET\", path: '/**' } }]\n binaries: [{ path: /usr/bin/curl }]\n", + ) + .expect("write NUL selector policy"); + let output = run(&[ + "check", + path.to_str().expect("UTF-8 temporary path"), + "--boundary", + fixture("boundary-empty.yaml").to_str().unwrap(), + "--output", + "json", + ]); + fs::remove_file(path).expect("remove NUL selector policy"); + + assert_eq!(output.status.code(), Some(3)); + assert!(output.stderr.is_empty()); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "unsupported"); + assert_eq!(value["reason_code"], "unsupported_policy_shape"); + assert!(value["reason"].as_str().unwrap().contains("NUL")); +} + +#[test] +fn over_limit_mixed_protocol_policy_is_rejected_before_shape_validation() { + let path = std::env::temp_dir().join(format!( + "openshell-prover-resource-limit-{}.yaml", + std::process::id() + )); + let mut source = String::from("version: 1\nnetwork_policies:\n mixed:\n endpoints:\n"); + for index in 0..2_500 { + writeln!( + source, + " - {{ host: l4-{index}.example.com, port: 443 }}" + ) + .unwrap(); + } + for index in 0..2_500 { + let host = if index == 2_499 { + "l4-0.example.com".to_owned() + } else { + format!("rest-{index}.example.com") + }; + writeln!( + source, + " - {{ host: {host}, port: 443, protocol: rest, enforcement: enforce, access: read-only }}" + ) + .unwrap(); + } + fs::write(&path, source).expect("write resource-limit policy"); + + let output = run(&[ + "check", + path.to_str().expect("UTF-8 temporary path"), + "--boundary", + fixture("boundary.yaml").to_str().unwrap(), + "--output", + "json", + ]); + fs::remove_file(path).expect("remove resource-limit policy"); + + assert_eq!(output.status.code(), Some(3)); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "inconclusive"); + assert_eq!(value["reason_code"], "resource_limit"); +} + +#[test] +fn invalid_json_mode_input_uses_error_envelope_and_two() { + let output = check_json("invalid.yaml", "boundary.yaml"); + assert_eq!( + output.status.code(), + Some(2), + "stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "error"); + assert_eq!(value["exit_code"], 2); + assert_eq!(value["reason_code"], "invalid_input"); +} + +#[test] +fn missing_json_mode_input_uses_error_envelope_and_two() { + let output = run(&[ + "check", + fixture("does-not-exist.yaml").to_str().unwrap(), + "--boundary", + fixture("boundary.yaml").to_str().unwrap(), + "--output", + "json", + ]); + assert_eq!(output.status.code(), Some(2)); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "error"); + assert_eq!(value["reason_code"], "invalid_input"); + assert!(value["reason"].as_str().unwrap().contains("cannot open")); +} + +#[test] +fn usage_errors_return_two() { + let output = run(&["check"]); + assert_eq!(output.status.code(), Some(2)); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).contains("required")); +} + +#[test] +fn removed_maximum_option_is_rejected() { + let output = run(&[ + "check", + fixture("candidate-contained.yaml").to_str().unwrap(), + "--maximum", + fixture("boundary.yaml").to_str().unwrap(), + ]); + assert_eq!(output.status.code(), Some(2)); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("unexpected argument '--maximum'"), + "{stderr}" + ); +} + +#[test] +fn timeout_must_be_positive() { + let output = run(&[ + "check", + fixture("candidate-contained.yaml").to_str().unwrap(), + "--boundary", + fixture("boundary.yaml").to_str().unwrap(), + "--timeout", + "0ms", + ]); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("positive")); +} + +#[test] +fn text_diagnostics_escape_terminal_controls() { + let output = run(&[ + "check", + "missing\u{1b}[31m.yaml", + "--boundary", + fixture("boundary.yaml").to_str().unwrap(), + ]); + assert_eq!(output.status.code(), Some(2)); + assert!(!output.stderr.contains(&0x1b)); + assert!(String::from_utf8_lossy(&output.stderr).contains("\\u{1b}")); +} + +#[cfg(unix)] +#[test] +fn fifo_input_is_rejected_without_blocking() { + use std::time::Instant; + + let path = std::env::temp_dir().join(format!("openshell-prover-fifo-{}", std::process::id())); + nix::unistd::mkfifo(&path, nix::sys::stat::Mode::S_IRUSR).expect("create FIFO fixture"); + + let mut child = Command::new(env!("CARGO_BIN_EXE_openshell-prover")) + .args([ + "check", + path.to_str().expect("UTF-8 temporary path"), + "--boundary", + fixture("boundary.yaml").to_str().unwrap(), + "--output", + "json", + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("start prover with FIFO input"); + + let deadline = Instant::now() + Duration::from_secs(2); + loop { + if child.try_wait().expect("poll prover").is_some() { + break; + } + if Instant::now() >= deadline { + child.kill().expect("terminate blocked prover"); + let _ = child.wait(); + fs::remove_file(&path).expect("remove FIFO fixture"); + panic!("prover blocked while opening a FIFO input"); + } + thread::sleep(Duration::from_millis(10)); + } + + let output = child.wait_with_output().expect("collect prover output"); + fs::remove_file(path).expect("remove FIFO fixture"); + assert_eq!(output.status.code(), Some(2)); + assert!(output.stderr.is_empty()); + let value: Value = serde_json::from_slice(&output.stdout).expect("single JSON object"); + assert_eq!(value["result"], "error"); + assert_eq!(value["reason_code"], "invalid_input"); + assert!( + value["reason"] + .as_str() + .expect("string reason") + .contains("not a regular file") + ); +} + +#[cfg(unix)] +#[test] +fn sigint_interrupts_the_check_with_exit_130() { + let directory = std::env::temp_dir().join(format!( + "openshell-prover-cancellation-{}", + std::process::id() + )); + fs::create_dir_all(&directory).unwrap(); + let policy = |paths: Vec| { + serde_json::json!({ + "version": 1, + "network_policies": {"many": { + "binaries": [{"path": "/usr/bin/curl"}], + "endpoints": [{"host": "api.example.com", "port": 443, + "protocol": "rest", "enforcement": "enforce", + "rules": paths.into_iter().map(|path| serde_json::json!({ + "allow": {"method": "GET", "path": path} + })).collect::>() + }] + }} + }) + }; + let candidate = directory.join("candidate.yaml"); + let boundary = directory.join("boundary.yaml"); + fs::write( + &candidate, + policy(vec!["/route*/**/tail*".into()]).to_string(), + ) + .unwrap(); + fs::write( + &boundary, + policy( + (0..300) + .map(|index| format!("/route{index}/**/tail*")) + .collect(), + ) + .to_string(), + ) + .unwrap(); + + let mut child = Command::new(env!("CARGO_BIN_EXE_openshell-prover")) + .args([ + "check", + candidate.to_str().expect("UTF-8 temporary path"), + "--boundary", + boundary.to_str().expect("UTF-8 temporary path"), + "--output", + "json", + "--timeout", + "10s", + ]) + .stdout(Stdio::piped()) + .spawn() + .expect("start cancellable prover"); + // Different policies force a real solve; an identical pair can exit via + // the equality shortcut before SIGINT ever exercises Z3's signal handling. + thread::sleep(Duration::from_millis(500)); + assert!( + child.try_wait().unwrap().is_none(), + "fixture must still be solving when interrupted" + ); + let signal = Command::new("kill") + .args(["-s", "INT", &child.id().to_string()]) + .status() + .expect("send SIGINT"); + assert!(signal.success()); + let output = child.wait_with_output().expect("wait for cancelled prover"); + assert_eq!(output.status.code(), Some(130)); + let value: Value = + serde_json::from_slice(&output.stdout).expect("structured cancellation JSON"); + assert_eq!(value["result"], "inconclusive"); + assert_eq!(value["reason_code"], "cancelled"); + assert_eq!(value["exit_code"], 130); + fs::remove_dir_all(directory).expect("remove cancellation policies"); +} + +#[cfg(unix)] +#[test] +fn symlink_descendants_require_sandbox_path_resolution() { + let directory = + std::env::temp_dir().join(format!("openshell-prover-symlink-{}", std::process::id())); + let safe = directory.join("safe"); + let outside = directory.join("outside"); + fs::create_dir_all(&safe).unwrap(); + fs::create_dir_all(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, safe.join("link")).unwrap(); + for access in ["read_only", "read_write"] { + let candidate = directory.join("candidate.yaml"); + let boundary = directory.join("boundary.yaml"); + for (file, path) in [(&candidate, safe.join("link")), (&boundary, safe.clone())] { + fs::write( + file, + serde_json::json!({"version": 1, "filesystem_policy": {access: [path]}}) + .to_string(), + ) + .unwrap(); + } + let output = run(&[ + "check", + candidate.to_str().unwrap(), + "--boundary", + boundary.to_str().unwrap(), + "--output", + "json", + ]); + assert_eq!(output.status.code(), Some(3)); + let value: Value = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(value["result"], "unsupported"); + assert_eq!(value["reason_code"], "unresolved_filesystem_path"); + } + fs::remove_dir_all(directory).unwrap(); +} diff --git a/crates/openshell-prover-cli/tests/fixtures/boundary-empty.yaml b/crates/openshell-prover-cli/tests/fixtures/boundary-empty.yaml new file mode 100644 index 0000000000..458bab0e43 --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/boundary-empty.yaml @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: 1 diff --git a/crates/openshell-prover-cli/tests/fixtures/boundary-no-write.yaml b/crates/openshell-prover-cli/tests/fixtures/boundary-no-write.yaml new file mode 100644 index 0000000000..9af13cd154 --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/boundary-no-write.yaml @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: 1 +filesystem_policy: + read_only: + - /usr diff --git a/crates/openshell-prover-cli/tests/fixtures/boundary.yaml b/crates/openshell-prover-cli/tests/fixtures/boundary.yaml new file mode 100644 index 0000000000..7c49a53efc --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/boundary.yaml @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: 1 +filesystem_policy: + read_only: + - /usr + - /etc + read_write: + - /tmp diff --git a/crates/openshell-prover-cli/tests/fixtures/candidate-contained.yaml b/crates/openshell-prover-cli/tests/fixtures/candidate-contained.yaml new file mode 100644 index 0000000000..308d88f1ba --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/candidate-contained.yaml @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: 1 +filesystem_policy: + read_only: + - /usr + read_write: + - /tmp diff --git a/crates/openshell-prover-cli/tests/fixtures/candidate-exceeds.yaml b/crates/openshell-prover-cli/tests/fixtures/candidate-exceeds.yaml new file mode 100644 index 0000000000..a59983cf93 --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/candidate-exceeds.yaml @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: 1 +filesystem_policy: + read_only: + - /usr/bin + read_write: + - /workspace diff --git a/crates/openshell-prover-cli/tests/fixtures/candidate-underscore-host.yaml b/crates/openshell-prover-cli/tests/fixtures/candidate-underscore-host.yaml new file mode 100644 index 0000000000..d2f2d37a84 --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/candidate-underscore-host.yaml @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: 1 +network_policies: + underscore-host: + endpoints: + - host: api_internal.example.com + port: 443 + binaries: + - path: /usr/bin/curl diff --git a/crates/openshell-prover-cli/tests/fixtures/candidate-unicode-network-selector.yaml b/crates/openshell-prover-cli/tests/fixtures/candidate-unicode-network-selector.yaml new file mode 100644 index 0000000000..bba84da6e9 --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/candidate-unicode-network-selector.yaml @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: 1 +network_policies: + unicode-binary: + endpoints: + - host: api.example.com + port: 443 + binaries: + - path: /usr/bin/é* diff --git a/crates/openshell-prover-cli/tests/fixtures/invalid.yaml b/crates/openshell-prover-cli/tests/fixtures/invalid.yaml new file mode 100644 index 0000000000..a904b71a19 --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/invalid.yaml @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: [ diff --git a/crates/openshell-prover-cli/tests/fixtures/unsupported.yaml b/crates/openshell-prover-cli/tests/fixtures/unsupported.yaml new file mode 100644 index 0000000000..5f3ac856fe --- /dev/null +++ b/crates/openshell-prover-cli/tests/fixtures/unsupported.yaml @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +version: 1 +process: + run_as_user: sandbox diff --git a/crates/openshell-prover/Cargo.toml b/crates/openshell-prover/Cargo.toml index 3e9f8cd1e9..e39154a537 100644 --- a/crates/openshell-prover/Cargo.toml +++ b/crates/openshell-prover/Cargo.toml @@ -24,5 +24,10 @@ owo-colors = { workspace = true } include_dir = { workspace = true } glob = { workspace = true } +[dev-dependencies] +openshell-core = { path = "../openshell-core" } +regorus = { version = "0.9", default-features = false, features = ["std", "arc", "glob"] } +serde_json = { workspace = true } + [lints] workspace = true diff --git a/crates/openshell-prover/README.md b/crates/openshell-prover/README.md index e63cc771aa..130ffe5971 100644 --- a/crates/openshell-prover/README.md +++ b/crates/openshell-prover/README.md @@ -8,6 +8,63 @@ attached credential set + a binary capability registry as a Z3 SMT model, then runs reachability queries to detect credentialed-reach and capability changes a reviewer should be aware of. +The crate also exposes an independent containment API for checking whether a +fully composed candidate policy stays within an operator-supplied boundary. The +`openshell-prover-cli` package wraps that API for local files. Containment and +the legacy proposal-risk queries answer different questions; gateway callers +continue to use the proposal-risk API until the managed-policy migration. + +Both prover entrypoints use the bounded `openshell-policy-schema` parser. +Containment rejects unknown fields and managed `metadata`/`review` annotations +as invalid input, then checks schema-valid controls against its supported model. +It uses shared filesystem defaults, port selection, and access-preset semantics. + +The containment model accepts ASCII literals in network binary selectors, +endpoint host and path selectors, and REST allow and deny method and path +selectors. It returns `unsupported_policy_shape` when either policy uses a +non-ASCII literal in one of those fields. This boundary does not apply to +filesystem paths or unrelated policy text. Embedded NUL bytes in network +selector fields are also unsupported. ASCII wildcards are modeled over the +runtime match language and can therefore match non-ASCII runtime values. A +solver string that cannot be decoded and validated exactly produces +`invalid_witness` rather than counterexample evidence. + +## Containment API compatibility + +The containment module is a reusable Rust API, but this contract does not make +the entire `openshell-prover` crate a stable published SDK. Construct options +through `CheckOptions::new`, and accept a policy only when the result is +`CheckResult::Within`: + +```rust +use std::time::Duration; +use openshell_prover::containment::{ + CheckOptions, CheckResult, check_within_boundary, parse_policy_str, +}; + +let boundary = parse_policy_str("version: 1\n")?; +let candidate = parse_policy_str("version: 1\n")?; +let result = check_within_boundary( + &boundary, + &candidate, + CheckOptions::new(Duration::from_secs(10)), +); +let authorized = matches!(result, CheckResult::Within(_)); +# Ok::<(), Box>(()) +``` + +`ReasonCode`, `CheckDomain`, `Protocol`, and `Counterexample` are open to new +variants. `CheckOptions`, `CheckScope`, `WithinEvidence`, and existing +counterexample variants are open to new fields. Match these types with `..` +and wildcard arms, use their accessors and `as_str()` identifiers, and treat +unknown values as a fail-closed result. Existing identifier strings are stable. + +`CheckResult` is intentionally closed to the four states `Within`, `Exceeds`, +`Unsupported`, and `Inconclusive`. `FilesystemAccess` is likewise closed to +`Read` and `Write`. Adding a result state or filesystem access mode is a +breaking API change. Rust source compatibility is separate from the CLI JSON +schema and containment model versions; this contract changes neither. + Used by the gateway to gate auto-approval of agent-authored policy proposals: any finding blocks auto-approval, an empty delta lets the chunk pass through (when the reviewer opts in via the @@ -47,8 +104,8 @@ pub struct ExfilPath { } ``` -The gateway's `finding_delta` keys paths by `(category, binary, -host:port, category, method)` so that adding a new method on an +The gateway's `finding_delta` keys paths by `(finding query, binary, +host:port, path category, method)` so that adding a new method on an already-reached host surfaces as exactly one new path (not the whole re-emission of the existing method set). @@ -115,10 +172,12 @@ not form part of the authored policy schema. - A list of `Finding` values, one per fired category. Each finding's `query` field holds the category name. -- The CLI renderer (`report::render_compact` / `render_report`) prints - human-readable output for the `openshell-prover` binary. +- The legacy report renderers (`report::render_compact` / `render_report`) + format proposal-risk findings for terminal consumers. - The gateway calls `report::finding_shorthand` to build the `validation_result` string persisted on each draft chunk. +- The containment API returns typed evidence to `openshell-prover-cli`, which + owns the standalone command's text and JSON formats and exit codes. ## Z3 model layout diff --git a/crates/openshell-prover/src/containment.rs b/crates/openshell-prover/src/containment.rs new file mode 100644 index 0000000000..86cc9dcd59 --- /dev/null +++ b/crates/openshell-prover/src/containment.rs @@ -0,0 +1,3230 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Sound, deliberately narrow policy-containment checks. +//! +//! This module is independent of the legacy proposal-risk model. It parses the +//! canonical authored schema and fails closed when authority falls outside its +//! supported containment model. +//! +//! Callers construct [`CheckOptions`] with [`CheckOptions::new`] and should +//! match extensible enums with a wildcard arm. [`CheckResult`] deliberately +//! remains exhaustive: its four outcomes are the stable, closed result-state +//! contract, and authorization should accept only [`CheckResult::Within`]. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; +use std::net::IpAddr; +use std::str::FromStr; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use openshell_policy_schema::{ + AccessPreset, FilesystemPolicy, L7Allow as Allow, L7DenyRule as DenyRule, LandlockPolicy, + NetworkBinary as Binary, NetworkEndpoint as Endpoint, NetworkMiddleware, + NetworkPolicyRule as NetworkRule, PolicyDocument, ProcessPolicy, +}; +use z3::ast::{Ast, Bool, Int, Regexp, String as Z3String}; +use z3::{Context, Params, SatResult, Solver}; + +const LAYER_L4: &str = "l4"; +const LAYER_REST: &str = "rest"; +const WORKDIR_SYMBOL: &str = ""; +const MAX_RULES: usize = 1_024; +const MAX_ENDPOINTS: usize = 4_096; +const MAX_BINARIES: usize = 4_096; +const MAX_PORT_ENTRIES: usize = 65_536; +const MAX_L7_RULES: usize = 16_384; +const MAX_PATTERN_BYTES: usize = 4 * 1024; +const MAX_TOTAL_PATTERN_BYTES: usize = 1024 * 1024; + +/// Parser error for a containment input. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParsePolicyError(String); + +impl fmt::Display for ParsePolicyError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +impl std::error::Error for ParsePolicyError {} + +/// Policy representation used by boundary checking, projected from the canonical +/// authored schema. Construction always goes through the shared bounded parser. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ContainmentPolicy { + filesystem_policy: FilesystemPolicy, + network_policies: BTreeMap, + landlock: Option, + process: Option, + network_middlewares: BTreeMap, +} + +trait ContainmentEndpoint { + fn protocol_kind(&self) -> Protocol; +} + +impl ContainmentEndpoint for Endpoint { + fn protocol_kind(&self) -> Protocol { + if self.is_l4() { + Protocol::L4 + } else { + Protocol::Rest + } + } +} + +/// Parse one captured YAML or JSON input using the canonical authored schema. +pub fn parse_policy_str(source: &str) -> Result { + let document = openshell_policy_schema::parse_policy(source) + .map_err(|error| ParsePolicyError(format!("invalid policy: {error:#}")))?; + let mut filesystem_policy = document.effective_filesystem_policy(); + normalize_filesystem_paths(&mut filesystem_policy)?; + let PolicyDocument { + version: _, + filesystem_policy: _, + network_policies, + landlock, + process, + network_middlewares, + } = document; + Ok(ContainmentPolicy { + filesystem_policy, + network_policies, + landlock, + process, + network_middlewares, + }) +} + +fn normalize_filesystem_paths(policy: &mut FilesystemPolicy) -> Result<(), ParsePolicyError> { + for path in policy.read_only.iter_mut().chain(&mut policy.read_write) { + *path = normalize_path(path)?; + } + Ok(()) +} + +fn normalize_path(path: &str) -> Result { + if !path.starts_with('/') { + return Err(ParsePolicyError(format!( + "filesystem path '{path}' must be absolute" + ))); + } + if path.split('/').any(|part| part == "..") { + return Err(ParsePolicyError(format!( + "filesystem path '{path}' contains an unsupported '..' segment" + ))); + } + Ok(openshell_policy_schema::normalize_path(path)) +} + +/// Per-invocation solver limits. These never modify Z3 global parameters. +/// +/// Construct options with [`CheckOptions::new`]. The struct is extensible so +/// future settings can receive defaults without breaking callers. +/// +/// ```compile_fail +/// use openshell_prover::containment::CheckOptions; +/// use std::time::Duration; +/// +/// let _options = CheckOptions { timeout: Duration::from_secs(1) }; +/// ``` +#[derive(Debug, Clone, Copy)] +#[non_exhaustive] +pub struct CheckOptions { + pub timeout: Duration, +} + +impl CheckOptions { + #[must_use] + pub const fn new(timeout: Duration) -> Self { + Self { timeout } + } +} + +/// Stable reason identifiers for automation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum ReasonCode { + UnsupportedPolicyShape, + UnresolvedWorkdir, + UnresolvedBinaryPath, + UnresolvedFilesystemPath, + SolverTimeout, + SolverUnknown, + ResourceLimit, + InvalidWitness, + Cancelled, +} + +impl ReasonCode { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::UnsupportedPolicyShape => "unsupported_policy_shape", + Self::UnresolvedWorkdir => "unresolved_workdir", + Self::UnresolvedBinaryPath => "unresolved_binary_path", + Self::UnresolvedFilesystemPath => "unresolved_filesystem_path", + Self::SolverTimeout => "solver_timeout", + Self::SolverUnknown => "solver_unknown", + Self::ResourceLimit => "resource_limit", + Self::InvalidWitness => "invalid_witness", + Self::Cancelled => "cancelled", + } + } +} + +/// Authority domains modeled by this engine version. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum CheckDomain { + Filesystem, + NetworkL4, + NetworkRest, +} + +impl CheckDomain { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Filesystem => "filesystem", + Self::NetworkL4 => "network_l4", + Self::NetworkRest => "network_rest", + } + } +} + +/// Scope attached to every completed or recoverably incomplete check. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct CheckScope { + pub model_version: &'static str, + pub policy_version: u32, + pub domains: &'static [CheckDomain], +} + +static DOMAINS: &[CheckDomain] = &[ + CheckDomain::Filesystem, + CheckDomain::NetworkL4, + CheckDomain::NetworkRest, +]; +fn check_scope() -> &'static CheckScope { + static SCOPE: CheckScope = CheckScope { + model_version: "boundary-v1", + policy_version: 1, + domains: DOMAINS, + }; + &SCOPE +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FilesystemAccess { + Read, + Write, +} + +impl FilesystemAccess { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Read => "read", + Self::Write => "write", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum Protocol { + L4, + Rest, +} + +impl Protocol { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::L4 => "l4", + Self::Rest => "rest", + } + } +} + +/// Concrete action showing why containment failed. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum Counterexample { + #[non_exhaustive] + Filesystem { + access: FilesystemAccess, + path: String, + }, + #[non_exhaustive] + Network { + binary: Option, + ancestor_binary: Option, + binary_identity_required: bool, + host: String, + port: u16, + protocol: Protocol, + method: Option, + path: Option, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct WithinEvidence; + +impl WithinEvidence { + #[must_use] + pub fn scope(&self) -> &'static CheckScope { + check_scope() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ExceedsEvidence(Counterexample); + +impl ExceedsEvidence { + #[must_use] + pub fn scope(&self) -> &'static CheckScope { + check_scope() + } + + #[must_use] + pub const fn counterexample(&self) -> &Counterexample { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReasonEvidence { + code: ReasonCode, + reason: String, +} + +impl ReasonEvidence { + #[must_use] + pub fn scope(&self) -> &'static CheckScope { + check_scope() + } + + #[must_use] + pub const fn reason_code(&self) -> ReasonCode { + self.code + } + + #[must_use] + pub fn reason(&self) -> &str { + &self.reason + } +} + +/// Result of a boundary proof attempt. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CheckResult { + Within(WithinEvidence), + Exceeds(ExceedsEvidence), + Unsupported(ReasonEvidence), + Inconclusive(ReasonEvidence), +} + +impl CheckResult { + /// Construct the standard typed result for a caller-observed cancellation. + #[must_use] + pub fn cancelled() -> Self { + cancelled_result() + } +} + +struct SymbolicAction { + binary: Z3String, + ancestor_binary: Z3String, + host: Z3String, + port: Int, + layer: Z3String, + method: Z3String, + path: Z3String, +} + +enum NetworkSolve { + Within, + Exceeds(Counterexample), + Incomplete(CheckResult), +} + +/// Determine whether every modeled candidate action is allowed by `boundary`. +#[must_use] +pub fn check_within_boundary( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, + options: CheckOptions, +) -> CheckResult { + check_within_boundary_inner(boundary, candidate, options, None) +} + +/// Determine containment while allowing a caller-owned cancellation flag to +/// interrupt the solver. The caller remains responsible for signal handling. +#[must_use] +pub fn check_within_boundary_cancellable( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, + options: CheckOptions, + cancelled: &AtomicBool, +) -> CheckResult { + check_within_boundary_inner(boundary, candidate, options, Some(cancelled)) +} + +fn check_within_boundary_inner( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, + options: CheckOptions, + cancelled: Option<&AtomicBool>, +) -> CheckResult { + if let Some(result) = + preflight_and_validate_policies(boundary, candidate, options, cancelled, |policy| { + validate_supported_policy(policy, cancelled) + }) + { + return result; + } + if let Some(reason) = unresolved_workdir_reason(boundary, candidate) { + return unsupported(ReasonCode::UnresolvedWorkdir, reason); + } + if boundary == candidate { + return CheckResult::Within(WithinEvidence); + } + let filesystem_result = check_filesystem(boundary, candidate); + if let Some(result @ CheckResult::Exceeds(_)) = filesystem_result { + return result; + } + let started = Instant::now(); + for binary_identity_required in [false, true] { + match solve_network_mode( + boundary, + candidate, + binary_identity_required, + started, + options.timeout, + cancelled, + ) { + NetworkSolve::Within => {} + NetworkSolve::Exceeds(counterexample) => { + return CheckResult::Exceeds(ExceedsEvidence(counterexample)); + } + NetworkSolve::Incomplete(result) => return result, + } + if binary_identity_required && has_ambiguous_candidate_binary_path(boundary, candidate) { + return unsupported( + ReasonCode::UnresolvedBinaryPath, + "network containment depends on image-specific binary symlink resolution" + .to_owned(), + ); + } + } + if unresolved_exact_deny_symlink(boundary, candidate) { + return unsupported( + ReasonCode::UnresolvedBinaryPath, + "network deny containment depends on image-specific exact binary symlink resolution" + .to_owned(), + ); + } + filesystem_result.unwrap_or(CheckResult::Within(WithinEvidence)) +} + +fn preflight_and_validate_policies( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, + options: CheckOptions, + cancelled: Option<&AtomicBool>, + mut validate: F, +) -> Option +where + F: FnMut(&ContainmentPolicy) -> Result<(), PolicyValidationError>, +{ + // Cancellation and aggregate limits intentionally take precedence over + // semantic shape errors. This keeps validation work bounded and lets an + // already-cancelled invocation stop before inspecting either policy. + if cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return Some(cancelled_result()); + } + if let Some(reason) = resource_limit_reason(boundary, candidate) { + if cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return Some(cancelled_result()); + } + return Some(CheckResult::Inconclusive(ReasonEvidence { + code: ReasonCode::ResourceLimit, + reason, + })); + } + if options.timeout.is_zero() { + return Some(CheckResult::Inconclusive(ReasonEvidence { + code: ReasonCode::SolverTimeout, + reason: "solver timeout must be positive".to_owned(), + })); + } + for (context, policy) in [("boundary", boundary), ("candidate", candidate)] { + match validate(policy) { + Ok(()) => {} + Err(PolicyValidationError::Cancelled) => return Some(cancelled_result()), + Err(PolicyValidationError::Unsupported(feature)) => { + return Some(unsupported( + feature.reason_code, + format!("{context} policy {}", feature.detail), + )); + } + } + } + if cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return Some(cancelled_result()); + } + None +} + +fn solve_network_mode( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, + binary_identity_required: bool, + started: Instant, + timeout: Duration, + cancelled: Option<&AtomicBool>, +) -> NetworkSolve { + if network_is_structurally_contained(boundary, candidate, binary_identity_required) { + return NetworkSolve::Within; + } + let solver = Solver::new(); + let action = symbolic_action(if binary_identity_required { + "strict_boundary_policy_action" + } else { + "relaxed_boundary_policy_action" + }); + assert_action_domain(&solver, &action, binary_identity_required); + solver.assert(Bool::and(&[ + policy_allows(candidate, &action, binary_identity_required), + !policy_allows(boundary, &action, binary_identity_required), + ])); + + let Some(remaining) = timeout.checked_sub(started.elapsed()) else { + return NetworkSolve::Incomplete(solver_timeout_result()); + }; + let remaining_ms = u32::try_from(remaining.as_millis()).unwrap_or(u32::MAX); + if remaining_ms == 0 { + return NetworkSolve::Incomplete(solver_timeout_result()); + } + let mut params = Params::new(); + params.set_u32("timeout", remaining_ms); + if cancelled.is_some() { + // The caller owns SIGINT. Z3's handler would replace it during check(), + // leaving the cancellation flag unset even when the solve is interrupted. + params.set_bool("ctrl_c", false); + } + solver.set_params(¶ms); + let solve_result = solver_check(&solver, cancelled); + if cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return NetworkSolve::Incomplete(cancelled_result()); + } + match solve_result { + SatResult::Unsat => NetworkSolve::Within, + SatResult::Unknown => { + let reason = solver + .get_reason_unknown() + .unwrap_or_else(|| "Z3 returned unknown".to_owned()); + let code = if reason.to_ascii_lowercase().contains("timeout") { + ReasonCode::SolverTimeout + } else { + ReasonCode::SolverUnknown + }; + NetworkSolve::Incomplete(CheckResult::Inconclusive(ReasonEvidence { code, reason })) + } + SatResult::Sat => solver + .get_model() + .and_then(|model| counterexample_from_model(&model, &action, binary_identity_required)) + .filter(|counterexample| { + counterexample_satisfies_predicate(boundary, candidate, counterexample) + }) + .map_or_else( + || { + NetworkSolve::Incomplete(CheckResult::Inconclusive(ReasonEvidence { + code: ReasonCode::InvalidWitness, + reason: "solver returned a model that could not be decoded".to_owned(), + })) + }, + NetworkSolve::Exceeds, + ), + } +} + +fn solver_timeout_result() -> CheckResult { + CheckResult::Inconclusive(ReasonEvidence { + code: ReasonCode::SolverTimeout, + reason: "solver timeout elapsed".to_owned(), + }) +} + +fn cancelled_result() -> CheckResult { + CheckResult::Inconclusive(ReasonEvidence { + code: ReasonCode::Cancelled, + reason: "containment check was cancelled".to_owned(), + }) +} + +fn solver_check(solver: &Solver, cancelled: Option<&AtomicBool>) -> SatResult { + let Some(cancelled) = cancelled else { + return solver.check(); + }; + let finished = AtomicBool::new(false); + let context = Context::thread_local(); + let handle = context.handle(); + std::thread::scope(|scope| { + let watcher = scope.spawn(|| { + while !finished.load(Ordering::Acquire) && !cancelled.load(Ordering::Relaxed) { + std::thread::park_timeout(Duration::from_millis(10)); + } + if cancelled.load(Ordering::Relaxed) { + handle.interrupt(); + } + }); + let result = solver.check(); + finished.store(true, Ordering::Release); + watcher.thread().unpark(); + watcher.join().expect("cancellation watcher must not panic"); + result + }) +} + +fn unsupported(code: ReasonCode, reason: String) -> CheckResult { + CheckResult::Unsupported(ReasonEvidence { code, reason }) +} + +/// Prove straightforward REST containment without invoking the solver. This +/// covers the common case where selectors are identical and the candidate only +/// narrows explicit method/path grants. More complex unions still use Z3. +fn network_is_structurally_contained( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, + binary_identity_required: bool, +) -> bool { + if boundary + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .any(|endpoint| !endpoint.deny_rules.is_empty()) + { + return false; + } + candidate.network_policies.values().all(|candidate_rule| { + boundary.network_policies.values().any(|boundary_rule| { + rule_structurally_contains(boundary_rule, candidate_rule, binary_identity_required) + }) + }) +} + +fn rule_structurally_contains( + boundary: &NetworkRule, + candidate: &NetworkRule, + binary_identity_required: bool, +) -> bool { + (!binary_identity_required + || candidate.binaries.iter().all(|candidate_binary| { + boundary + .binaries + .iter() + .any(|boundary_binary| boundary_binary.path == candidate_binary.path) + })) + && candidate.endpoints.iter().all(|candidate_endpoint| { + boundary.endpoints.iter().any(|boundary_endpoint| { + rest_endpoint_structurally_contains(boundary_endpoint, candidate_endpoint) + }) + }) +} + +fn rest_endpoint_structurally_contains(boundary: &Endpoint, candidate: &Endpoint) -> bool { + if boundary.protocol_kind() != Protocol::Rest + || candidate.protocol_kind() != Protocol::Rest + || !boundary.host.eq_ignore_ascii_case(&candidate.host) + || boundary.path != candidate.path + || !candidate + .effective_ports() + .iter() + .all(|port| boundary.effective_ports().contains(port)) + || !boundary.access.is_empty() + || !candidate.access.is_empty() + || !boundary.deny_rules.is_empty() + || !candidate.deny_rules.is_empty() + { + return false; + } + + candidate.rules.iter().all(|candidate_rule| { + if candidate_rule.allow.method.is_empty() { + return false; + } + boundary.rules.iter().any(|boundary_rule| { + method_pattern_contains(&boundary_rule.allow.method, &candidate_rule.allow.method) + && path_pattern_contains(&boundary_rule.allow.path, &candidate_rule.allow.path) + }) + }) +} + +fn method_pattern_contains(boundary: &str, candidate: &str) -> bool { + boundary == "*" + || boundary.eq_ignore_ascii_case(candidate) + || (boundary.eq_ignore_ascii_case("GET") && candidate.eq_ignore_ascii_case("HEAD")) +} + +fn path_pattern_contains(boundary: &str, candidate: &str) -> bool { + // Inputs are already validated. Keep this sufficient proof deliberately + // limited to equality and a terminal recursive path segment. + let boundary = if boundary.is_empty() { "**" } else { boundary }; + let candidate = if candidate.is_empty() { + "**" + } else { + candidate + }; + boundary == candidate + || boundary == "**" + || boundary.strip_suffix("/**").is_some_and(|prefix| { + candidate + .strip_prefix(prefix) + .is_some_and(|suffix| suffix.starts_with('/')) + }) +} + +fn symbolic_action(name: &str) -> SymbolicAction { + let _context = Context::thread_local(); + SymbolicAction { + binary: Z3String::new_const(format!("{name}_binary")), + ancestor_binary: Z3String::new_const(format!("{name}_ancestor_binary")), + host: Z3String::new_const(format!("{name}_host")), + port: Int::new_const(format!("{name}_port")), + layer: Z3String::new_const(format!("{name}_layer")), + method: Z3String::new_const(format!("{name}_method")), + path: Z3String::new_const(format!("{name}_path")), + } +} + +fn assert_action_domain(solver: &Solver, action: &SymbolicAction, binary_identity_required: bool) { + if binary_identity_required { + solver.assert(action.binary.regex_matches(&glob_regex("/**", "/"))); + solver.assert(action.binary.length().le(4_096)); + solver.assert( + action + .ancestor_binary + .regex_matches(&glob_regex("/**", "/")), + ); + solver.assert(action.ancestor_binary.length().le(4_096)); + } + // Keep `action.host` unconstrained: the runtime applies host globs to raw + // proxy input before DNS validation, so DNS structure and resolver length + // limits are not properties of the action domain. + solver.assert(Int::from_u64(1).le(&action.port)); + solver.assert(action.port.le(65_535)); + solver.assert(str_eq_any(&action.layer, &[LAYER_L4, LAYER_REST])); + solver.assert(!action.method.eq("")); + solver.assert( + Z3String::from_str("/") + .expect("valid Z3 string") + .prefix(&action.path), + ); + solver.assert(action.path.length().le(4_096)); + for forbidden in ["//", "/./", "/../", ";", "?", "#"] { + solver.assert(!action.path.contains(forbidden)); + } + solver.assert(!action.path.eq("/.")); + solver.assert(!action.path.eq("/..")); + solver.assert(!Z3String::from_str("/.").unwrap().suffix(&action.path)); + solver.assert(!Z3String::from_str("/..").unwrap().suffix(&action.path)); +} + +fn policy_allows( + policy: &ContainmentPolicy, + action: &SymbolicAction, + binary_identity_required: bool, +) -> Bool { + let allowed = bool_or( + policy + .network_policies + .values() + .map(|rule| rule_allows(rule, action, binary_identity_required)), + ); + let denied = bool_or( + policy + .network_policies + .values() + .map(|rule| rule_denies(rule, action, binary_identity_required)), + ); + Bool::and(&[allowed, !denied]) +} + +fn rule_allows( + rule: &NetworkRule, + action: &SymbolicAction, + binary_identity_required: bool, +) -> Bool { + Bool::and(&[ + binaries_match(rule, action, binary_identity_required), + bool_or( + rule.endpoints + .iter() + .map(|endpoint| endpoint_allows(endpoint, action)), + ), + ]) +} + +fn rule_denies( + rule: &NetworkRule, + action: &SymbolicAction, + binary_identity_required: bool, +) -> Bool { + Bool::and(&[ + binaries_match(rule, action, binary_identity_required), + bool_or( + rule.endpoints + .iter() + .map(|endpoint| endpoint_denies(endpoint, action)), + ), + ]) +} + +fn binaries_match( + rule: &NetworkRule, + action: &SymbolicAction, + binary_identity_required: bool, +) -> Bool { + if !binary_identity_required { + return Bool::from_bool(true); + } + bool_or(rule.binaries.iter().flat_map(|binary| { + let pattern = glob_regex(&binary.path, "/"); + [ + action.binary.regex_matches(&pattern), + action.ancestor_binary.regex_matches(&pattern), + ] + })) +} + +fn endpoint_allows(endpoint: &Endpoint, action: &SymbolicAction) -> Bool { + let common = endpoint_matches_connection(endpoint, action); + match endpoint.protocol_kind() { + Protocol::L4 => common, + Protocol::Rest => Bool::and(&[ + common, + action.layer.eq(LAYER_REST), + endpoint_path_matches(endpoint, action), + rest_endpoint_allows(endpoint, action), + ]), + } +} + +fn endpoint_denies(endpoint: &Endpoint, action: &SymbolicAction) -> Bool { + if endpoint.protocol_kind() != Protocol::Rest || endpoint.deny_rules.is_empty() { + return Bool::from_bool(false); + } + Bool::and(&[ + endpoint_matches_connection(endpoint, action), + action.layer.eq(LAYER_REST), + endpoint_path_matches(endpoint, action), + bool_or( + endpoint + .deny_rules + .iter() + .map(|deny| method_and_path_match(&deny.method, &deny.path, action)), + ), + ]) +} + +fn rest_endpoint_allows(endpoint: &Endpoint, action: &SymbolicAction) -> Bool { + match AccessPreset::parse(&endpoint.access) { + Some(AccessPreset::Full) => any_method_matches(action, "**"), + Some(preset) => methods_match(action, preset.methods("rest"), "**"), + None => bool_or( + endpoint + .rules + .iter() + .map(|rule| method_and_path_match(&rule.allow.method, &rule.allow.path, action)), + ), + } +} + +fn endpoint_matches_connection(endpoint: &Endpoint, action: &SymbolicAction) -> Bool { + Bool::and(&[ + bool_or( + endpoint + .effective_ports() + .into_iter() + .map(|port| action.port.eq(Int::from_u64(u64::from(port)))), + ), + action + .host + .regex_matches(&glob_regex(&endpoint.host.to_ascii_lowercase(), ".")), + ]) +} + +fn endpoint_path_matches(endpoint: &Endpoint, action: &SymbolicAction) -> Bool { + let path = if endpoint.path.is_empty() { + "**" + } else { + &endpoint.path + }; + action.path.regex_matches(&glob_regex(path, "/")) +} + +fn method_and_path_match(method: &str, path: &str, action: &SymbolicAction) -> Bool { + if method.is_empty() { + return Bool::from_bool(false); + } + let path = if path.is_empty() { "**" } else { path }; + if method == "*" { + any_method_matches(action, path) + } else if method.eq_ignore_ascii_case("GET") { + methods_match(action, &["GET", "HEAD"], path) + } else { + methods_match(action, &[method], path) + } +} + +fn any_method_matches(action: &SymbolicAction, path: &str) -> Bool { + action.path.regex_matches(&glob_regex(path, "/")) +} + +fn methods_match(action: &SymbolicAction, methods: &[&str], path: &str) -> Bool { + Bool::and(&[ + str_eq_any_case_insensitive(&action.method, methods), + action.path.regex_matches(&glob_regex(path, "/")), + ]) +} + +fn counterexample_from_model( + model: &z3::Model, + action: &SymbolicAction, + binary_identity_required: bool, +) -> Option { + let port = model.eval(&action.port, true)?.as_u64()?; + let layer = model_string_exact(model, &action.layer)?; + let binary = if binary_identity_required { + let binary = model_string_exact(model, &action.binary)?; + if !is_canonical_runtime_binary_path(&binary) { + return None; + } + Some(binary) + } else { + None + }; + let ancestor_binary = if binary_identity_required { + let binary = model_string_exact(model, &action.ancestor_binary)?; + if !is_canonical_runtime_binary_path(&binary) { + return None; + } + Some(binary) + } else { + None + }; + let host = model_string_exact(model, &action.host)?; + if !is_canonical_dns_host(&host) { + return None; + } + let protocol = if layer == LAYER_L4 { + Protocol::L4 + } else { + Protocol::Rest + }; + let (method, path) = if protocol == Protocol::Rest { + let method = model_string_exact(model, &action.method)?; + let path = model_string_exact(model, &action.path)?; + if !is_http_method(&method) || !is_canonical_rest_path(&path) { + return None; + } + (Some(method), Some(path)) + } else { + (None, None) + }; + Some(Counterexample::Network { + binary, + ancestor_binary, + binary_identity_required, + host, + port: u16::try_from(port).ok()?, + protocol, + method, + path, + }) +} + +/// Decode a model string only when encoding it again produces the exact same +/// solver value. `as_string` uses a lossy C-string boundary in the Rust Z3 +/// binding, so accepting its output alone could publish an altered witness. +fn model_string_exact(model: &z3::Model, value: &Z3String) -> Option { + let evaluated = model.eval(value, true)?; + let decoded = evaluated.as_string()?; + // Some Z3 versions expose non-ASCII UTF-8 bytes through `Z3_get_string` + // as `\u{..}` sequences. The binding does not distinguish that encoding + // from literal text, so do not risk publishing the serialization as a + // concrete witness. + if decoded.contains("\\u{") { + return None; + } + let reconstructed = Z3String::from_str(&decoded).ok()?; + (evaluated.eq(reconstructed).simplify().as_bool() == Some(true)).then_some(decoded) +} + +fn counterexample_satisfies_predicate( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, + counterexample: &Counterexample, +) -> bool { + let Counterexample::Network { + binary, + ancestor_binary, + binary_identity_required, + host, + port, + protocol, + method, + path, + } = counterexample + else { + return false; + }; + let concrete = SymbolicAction { + binary: Z3String::from_str(binary.as_deref().unwrap_or("")).unwrap(), + ancestor_binary: Z3String::from_str(ancestor_binary.as_deref().unwrap_or("")).unwrap(), + host: Z3String::from_str(host).unwrap(), + port: Int::from_u64(u64::from(*port)), + layer: Z3String::from_str(protocol.as_str()).unwrap(), + method: Z3String::from_str(method.as_deref().unwrap_or("GET")).unwrap(), + path: Z3String::from_str(path.as_deref().unwrap_or("/")).unwrap(), + }; + Bool::and(&[ + policy_allows(candidate, &concrete, *binary_identity_required), + !policy_allows(boundary, &concrete, *binary_identity_required), + ]) + .simplify() + .as_bool() + == Some(true) +} + +fn is_canonical_runtime_binary_path(path: &str) -> bool { + path.len() <= 4 * 1024 && is_canonical_pattern_path(path) && !path.chars().any(char::is_control) +} + +fn is_canonical_dns_host(host: &str) -> bool { + !host.is_empty() + && host.len() <= 253 + && host.split('.').all(|label| { + !label.is_empty() + && label.len() <= 63 + && label.bytes().all(|byte| { + byte.is_ascii_lowercase() + || byte.is_ascii_digit() + || matches!(byte, b'-' | b'_') + }) + && label.as_bytes().first().is_some_and(|byte| *byte != b'-') + && label.as_bytes().last().is_some_and(|byte| *byte != b'-') + }) +} + +fn is_http_method(method: &str) -> bool { + !method.is_empty() + && method.bytes().all(|byte| { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'!' | b'#' + | b'$' + | b'%' + | b'&' + | b'\'' + | b'*' + | b'+' + | b'-' + | b'.' + | b'^' + | b'_' + | b'`' + | b'|' + | b'~' + ) + }) +} + +fn is_canonical_rest_path(path: &str) -> bool { + if path.is_empty() + || path.len() > 4 * 1024 + || !path.starts_with('/') + || path.contains("//") + || path.contains(';') + || path.contains('?') + || path.contains('#') + { + return false; + } + let bytes = path.as_bytes(); + if bytes.iter().any(|byte| !(0x21..=0x7e).contains(byte)) + || path.split('/').any(|segment| matches!(segment, "." | "..")) + { + return false; + } + let mut index = 0; + while index < bytes.len() { + if bytes[index] != b'%' { + if bytes[index] != b'/' && !is_literal_canonical_pchar(bytes[index]) { + return false; + } + index += 1; + continue; + } + if index + 2 >= bytes.len() + || !bytes[index + 1].is_ascii_hexdigit() + || !bytes[index + 2].is_ascii_hexdigit() + || bytes[index + 1].is_ascii_lowercase() + || bytes[index + 2].is_ascii_lowercase() + { + return false; + } + let decoded = u8::from_str_radix(&path[index + 1..index + 3], 16).expect("checked hex"); + if decoded == b'/' + || decoded == b';' + || decoded.is_ascii_control() + || is_literal_canonical_pchar(decoded) + { + return false; + } + index += 3; + } + true +} + +fn is_literal_canonical_pchar(byte: u8) -> bool { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'-' | b'.' + | b'_' + | b'~' + | b'!' + | b'$' + | b'&' + | b'\'' + | b'(' + | b')' + | b'*' + | b'+' + | b',' + | b'=' + | b':' + | b'@' + ) +} + +fn unresolved_workdir_reason( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, +) -> Option { + let boundary_writes = &boundary.filesystem_policy.read_write; + let mut boundary_reads = boundary.filesystem_policy.read_only.clone(); + boundary_reads.extend(boundary_writes.iter().cloned()); + + if candidate.filesystem_policy.include_workdir + && !boundary.filesystem_policy.include_workdir + && !boundary_writes.iter().any(|path| path == "/") + { + return Some( + "candidate filesystem authority depends on an unresolved image workdir".to_owned(), + ); + } + if boundary.filesystem_policy.include_workdir + && (candidate + .filesystem_policy + .read_write + .iter() + .any(|path| !path_is_covered(path, boundary_writes)) + || candidate + .filesystem_policy + .read_only + .iter() + .any(|path| !path_is_covered(path, &boundary_reads))) + { + return Some( + "boundary filesystem authority depends on an unresolved image workdir".to_owned(), + ); + } + None +} + +// The glob crate rejects some runtime-supported patterns (for example `cu**`). +// Its parse errors cannot rule out overlap in either symlink uncertainty guard. +fn has_ambiguous_candidate_binary_path( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, +) -> bool { + boundary.network_policies.values().any(|boundary_rule| { + boundary_rule + .binaries + .iter() + .filter(|binary| binary.path.contains('*') && binary.path != "/**") + .any(|boundary_binary| { + candidate.network_policies.values().any(|candidate_rule| { + endpoint_authority_sets_overlap( + &candidate_rule.endpoints, + &boundary_rule.endpoints, + ) && candidate_rule.binaries.iter().any(|candidate_binary| { + !candidate_binary.path.contains('*') + && glob::Pattern::new(&boundary_binary.path) + .map_or(true, |pattern| pattern.matches(&candidate_binary.path)) + && !boundary.network_policies.values().any(|exact_rule| { + endpoint_authority_sets_equal( + &candidate_rule.endpoints, + &exact_rule.endpoints, + ) && exact_rule + .binaries + .iter() + .any(|exact_binary| exact_binary.path == candidate_binary.path) + }) + }) + }) + }) + }) +} + +fn unresolved_exact_deny_symlink( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, +) -> bool { + boundary.network_policies.values().any(|boundary_rule| { + let boundary_deny_endpoints = boundary_rule + .endpoints + .iter() + .filter(|endpoint| !endpoint.deny_rules.is_empty()) + .collect::>(); + if boundary_deny_endpoints.is_empty() { + return false; + } + boundary_rule + .binaries + .iter() + .filter(|binary| !binary.path.contains('*')) + .any(|boundary_binary| { + candidate.network_policies.values().any(|candidate_rule| { + let endpoints_overlap = candidate_rule + .endpoints + .iter() + .filter(|endpoint| !endpoint.deny_rules.is_empty()) + .any(|candidate_endpoint| { + boundary_deny_endpoints.iter().any(|boundary_endpoint| { + endpoint_authority_may_overlap( + candidate_endpoint, + boundary_endpoint, + ) + }) + }); + endpoints_overlap + && candidate_rule.binaries.iter().any(|candidate_binary| { + candidate_binary.path.contains('*') + && candidate_binary.path != "/**" + && glob::Pattern::new(&candidate_binary.path) + .map_or(true, |pattern| pattern.matches(&boundary_binary.path)) + }) + }) + }) + }) +} + +fn endpoint_authority_sets_overlap(left: &[Endpoint], right: &[Endpoint]) -> bool { + left.iter().any(|endpoint| { + right + .iter() + .any(|other| endpoint_authority_may_overlap(endpoint, other)) + }) +} + +fn endpoint_authority_sets_equal(left: &[Endpoint], right: &[Endpoint]) -> bool { + left.iter().all(|endpoint| { + right + .iter() + .any(|other| endpoint_authority_equal(endpoint, other)) + }) && right.iter().all(|endpoint| { + left.iter() + .any(|other| endpoint_authority_equal(endpoint, other)) + }) +} + +fn endpoint_authority_may_overlap(left: &Endpoint, right: &Endpoint) -> bool { + let ports_overlap = left + .effective_ports() + .iter() + .any(|port| right.effective_ports().contains(port)); + let hosts_may_overlap = left.host.eq_ignore_ascii_case(&right.host) + || left.host.contains('*') + || right.host.contains('*'); + ports_overlap && hosts_may_overlap +} + +fn endpoint_authority_equal(left: &Endpoint, right: &Endpoint) -> bool { + let mut left = left.clone(); + let mut right = right.clone(); + let rules_equal = left.rules.iter().all(|rule| right.rules.contains(rule)) + && right.rules.iter().all(|rule| left.rules.contains(rule)); + let denies_equal = left + .deny_rules + .iter() + .all(|rule| right.deny_rules.contains(rule)) + && right + .deny_rules + .iter() + .all(|rule| left.deny_rules.contains(rule)); + left.rules.clear(); + right.rules.clear(); + left.deny_rules.clear(); + right.deny_rules.clear(); + rules_equal && denies_equal && left == right +} + +fn check_filesystem( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, +) -> Option { + let mut boundary_writes = boundary.filesystem_policy.read_write.clone(); + if boundary.filesystem_policy.include_workdir { + boundary_writes.push(WORKDIR_SYMBOL.to_owned()); + } + let mut boundary_reads = boundary.filesystem_policy.read_only.clone(); + boundary_reads.extend(boundary_writes.iter().cloned()); + + let mut unresolved = None; + for (access, candidates, maxima) in [ + ( + FilesystemAccess::Write, + &candidate.filesystem_policy.read_write, + &boundary_writes, + ), + ( + FilesystemAccess::Read, + &candidate.filesystem_policy.read_only, + &boundary_reads, + ), + ] { + for path in candidates { + if path_is_covered(path, maxima) { + continue; + } + if maxima.is_empty() { + return Some(CheckResult::Exceeds(ExceedsEvidence( + Counterexample::Filesystem { + access, + path: path.clone(), + }, + ))); + } + // Landlock resolves paths in the sandbox. Lexical descendants can + // point outside an ancestor, and unrelated paths can alias it. + unresolved = Some(unsupported( + ReasonCode::UnresolvedFilesystemPath, + format!( + "filesystem {access} containment for '{path}' depends on sandbox path resolution; use matching paths in candidate and boundary", + access = access.as_str() + ), + )); + } + } + unresolved +} + +fn path_is_covered(candidate: &str, boundary_paths: &[String]) -> bool { + boundary_paths + .iter() + .any(|boundary| boundary == "/" || candidate == boundary) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct UnsupportedFeature { + reason_code: ReasonCode, + detail: String, +} + +enum PolicyValidationError { + Unsupported(UnsupportedFeature), + Cancelled, +} + +impl From for PolicyValidationError { + fn from(feature: UnsupportedFeature) -> Self { + Self::Unsupported(feature) + } +} + +impl UnsupportedFeature { + fn policy_shape(detail: impl Into) -> Self { + Self { + reason_code: ReasonCode::UnsupportedPolicyShape, + detail: detail.into(), + } + } +} + +fn validate_supported_policy( + policy: &ContainmentPolicy, + cancelled: Option<&AtomicBool>, +) -> Result<(), PolicyValidationError> { + validate_supported_common_policy(policy)?; + for (rule_name, rule) in &policy.network_policies { + if cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return Err(PolicyValidationError::Cancelled); + } + validate_supported_network_rule(rule_name, rule, cancelled)?; + } + validate_no_cross_protocol_overlap(policy, cancelled) +} + +fn validate_supported_common_policy(policy: &ContainmentPolicy) -> Result<(), UnsupportedFeature> { + if policy.landlock.is_some() + || policy.process.is_some() + || !policy.network_middlewares.is_empty() + { + return Err(UnsupportedFeature::policy_shape( + "uses process, Landlock, or network middleware controls", + )); + } + Ok(()) +} + +fn validate_supported_network_rule( + rule_name: &str, + rule: &NetworkRule, + cancelled: Option<&AtomicBool>, +) -> Result<(), PolicyValidationError> { + for binary in &rule.binaries { + if cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return Err(PolicyValidationError::Cancelled); + } + validate_supported_binary(rule_name, binary)?; + } + for endpoint in &rule.endpoints { + if cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return Err(PolicyValidationError::Cancelled); + } + validate_supported_endpoint(rule_name, endpoint)?; + } + Ok(()) +} + +fn validate_supported_binary(rule_name: &str, binary: &Binary) -> Result<(), UnsupportedFeature> { + if let Some(reason) = unsupported_network_literal(&binary.path) { + return Err(UnsupportedFeature::policy_shape(format!( + "rule '{rule_name}' binary path {reason}" + ))); + } + if binary.path.is_empty() + || !is_canonical_pattern_path(&binary.path) + || unsupported_glob(&binary.path) + { + return Err(UnsupportedFeature::policy_shape(format!( + "rule '{rule_name}' uses an unsupported binary" + ))); + } + Ok(()) +} + +fn validate_supported_endpoint( + rule_name: &str, + endpoint: &Endpoint, +) -> Result<(), UnsupportedFeature> { + let context = format!("rule '{rule_name}'"); + validate_shared_endpoint(&context, endpoint)?; + validate_supported_endpoint_extensions(&context, endpoint)?; + match validate_supported_protocol(&context, endpoint)? { + Protocol::L4 => validate_supported_l4(&context, endpoint), + Protocol::Rest => validate_supported_rest(&context, endpoint), + } +} + +fn validate_shared_endpoint(context: &str, endpoint: &Endpoint) -> Result<(), UnsupportedFeature> { + if let Some(reason) = unsupported_network_literal(&endpoint.host) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} endpoint host {reason}" + ))); + } + if let Some(reason) = unsupported_network_literal(&endpoint.path) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} endpoint path {reason}" + ))); + } + if endpoint.host.is_empty() + || endpoint.effective_ports().is_empty() + || (endpoint.port != 0 && !endpoint.ports.is_empty()) + { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} has no unambiguous host and port" + ))); + } + if unsupported_host_glob(&endpoint.host) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} endpoint host uses an unsupported pattern" + ))); + } + if unsupported_glob(&endpoint.path) + || (!endpoint.path.is_empty() && !is_canonical_pattern_path(&endpoint.path)) + { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses an unsupported glob" + ))); + } + if !endpoint.path.is_empty() && !endpoint.path.starts_with('/') { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses a non-canonical endpoint path" + ))); + } + if endpoint.host.contains(':') { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses an IP-literal shape outside the DNS host model" + ))); + } + Ok(()) +} + +fn validate_supported_endpoint_extensions( + context: &str, + endpoint: &Endpoint, +) -> Result<(), UnsupportedFeature> { + if !endpoint.allowed_ips.is_empty() + || !matches!(endpoint.tls.as_str(), "" | "terminate" | "passthrough") + || endpoint.allow_encoded_slash + || endpoint.websocket_credential_rewrite + || endpoint.request_body_credential_rewrite + || endpoint.allow_uninspected_credentials + { + return unsupported_endpoint_extension(context); + } + validate_supported_graphql(context, endpoint)?; + validate_supported_credentials(context, endpoint)?; + validate_supported_json_rpc(context, endpoint)?; + validate_supported_mcp(context, endpoint) +} + +fn unsupported_endpoint_extension(context: &str) -> Result<(), UnsupportedFeature> { + Err(UnsupportedFeature::policy_shape(format!( + "{context} uses authority outside the initial model" + ))) +} + +fn validate_supported_graphql( + context: &str, + endpoint: &Endpoint, +) -> Result<(), UnsupportedFeature> { + if !endpoint.persisted_queries.is_empty() + || !endpoint.graphql_persisted_queries.is_empty() + || endpoint.graphql_max_body_bytes != 0 + { + return unsupported_endpoint_extension(context); + } + Ok(()) +} + +fn validate_supported_credentials( + context: &str, + endpoint: &Endpoint, +) -> Result<(), UnsupportedFeature> { + if !endpoint.credential_signing.is_empty() + || !endpoint.signing_service.is_empty() + || !endpoint.signing_region.is_empty() + || endpoint.credential_binding.is_some() + { + return unsupported_endpoint_extension(context); + } + Ok(()) +} + +fn validate_supported_json_rpc( + context: &str, + endpoint: &Endpoint, +) -> Result<(), UnsupportedFeature> { + if endpoint.json_rpc.is_some() { + return unsupported_endpoint_extension(context); + } + Ok(()) +} + +fn validate_supported_mcp(context: &str, endpoint: &Endpoint) -> Result<(), UnsupportedFeature> { + if endpoint.mcp.is_some() { + return unsupported_endpoint_extension(context); + } + Ok(()) +} + +fn validate_supported_protocol( + context: &str, + endpoint: &Endpoint, +) -> Result { + match endpoint.protocol.to_ascii_lowercase().as_str() { + "" | "tcp" => Ok(Protocol::L4), + "rest" => Ok(Protocol::Rest), + _ => Err(UnsupportedFeature::policy_shape(format!( + "{context} uses protocol '{}'; only L4 TCP and REST are modeled", + endpoint.protocol + ))), + } +} + +fn validate_supported_l4(context: &str, endpoint: &Endpoint) -> Result<(), UnsupportedFeature> { + if endpoint.protocol.eq_ignore_ascii_case("tcp") && endpoint.host.parse::().is_ok() { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses an IP literal with explicit TCP semantics" + ))); + } + if !endpoint.enforcement.is_empty() + || !endpoint.access.is_empty() + || !endpoint.path.is_empty() + || !endpoint.rules.is_empty() + || !endpoint.deny_rules.is_empty() + { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} mixes REST controls into L4 authority" + ))); + } + Ok(()) +} + +fn validate_supported_rest(context: &str, endpoint: &Endpoint) -> Result<(), UnsupportedFeature> { + if endpoint.enforcement != "enforce" { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses REST without enforced inspection" + ))); + } + if (!endpoint.access.is_empty() && !endpoint.rules.is_empty()) + || (endpoint.access.is_empty() && endpoint.rules.is_empty()) + || (!endpoint.access.is_empty() && AccessPreset::parse(&endpoint.access).is_none()) + { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} has an unsupported REST allow shape" + ))); + } + for rule in &endpoint.rules { + if let Some(reason) = unsupported_network_literal(&rule.allow.method) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} REST allow method {reason}" + ))); + } + if let Some(reason) = unsupported_network_literal(&rule.allow.path) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} REST allow path {reason}" + ))); + } + if unsupported_allow(&rule.allow) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses an unsupported REST allow rule" + ))); + } + } + for rule in &endpoint.deny_rules { + if let Some(reason) = unsupported_network_literal(&rule.method) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} REST deny method {reason}" + ))); + } + if let Some(reason) = unsupported_network_literal(&rule.path) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} REST deny path {reason}" + ))); + } + if unsupported_deny(rule) { + return Err(UnsupportedFeature::policy_shape(format!( + "{context} uses an unsupported REST deny rule" + ))); + } + } + Ok(()) +} + +#[derive(Default)] +struct ProtocolAuthorityIndex { + all: BTreeSet, + wildcards: BTreeSet, + exact: BTreeMap>, +} + +impl ProtocolAuthorityIndex { + fn overlaps(&self, host: &str, ports: &[u16]) -> bool { + ports.iter().any(|port| { + self.wildcards.contains(port) + || if host.contains('*') { + self.all.contains(port) + } else { + self.exact + .get(host) + .is_some_and(|ports_for_host| ports_for_host.contains(port)) + } + }) + } + + fn insert(&mut self, host: &str, ports: &[u16]) { + self.all.extend(ports); + if host.contains('*') { + self.wildcards.extend(ports); + } else { + self.exact.entry(host.to_owned()).or_default().extend(ports); + } + } +} + +fn validate_no_cross_protocol_overlap( + policy: &ContainmentPolicy, + cancelled: Option<&AtomicBool>, +) -> Result<(), PolicyValidationError> { + let mut l4 = ProtocolAuthorityIndex::default(); + let mut rest = ProtocolAuthorityIndex::default(); + for endpoint in policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + { + if cancelled.is_some_and(|flag| flag.load(Ordering::Relaxed)) { + return Err(PolicyValidationError::Cancelled); + } + let host = endpoint.host.to_ascii_lowercase(); + let ports = endpoint.effective_ports(); + let (current, other) = match endpoint.protocol_kind() { + Protocol::L4 => (&mut l4, &rest), + Protocol::Rest => (&mut rest, &l4), + }; + if other.overlaps(&host, &ports) { + return Err(UnsupportedFeature::policy_shape( + "contains overlapping L4 and REST endpoints whose inspection selection is not modeled", + ) + .into()); + } + current.insert(&host, &ports); + } + Ok(()) +} + +fn unsupported_network_literal(value: &str) -> Option<&'static str> { + if !value.is_ascii() { + Some("contains a non-ASCII literal") + } else if value.contains('\0') { + Some("contains an embedded NUL byte") + } else { + None + } +} + +fn resource_limit_reason( + boundary: &ContainmentPolicy, + candidate: &ContainmentPolicy, +) -> Option { + let policies = [boundary, candidate]; + let rule_count = policies + .iter() + .map(|policy| policy.network_policies.len()) + .fold(0_usize, usize::saturating_add); + if rule_count > MAX_RULES { + return Some(resource_limit_detail("rules", rule_count, MAX_RULES)); + } + + let endpoint_count = policies + .iter() + .flat_map(|policy| policy.network_policies.values()) + .map(|rule| rule.endpoints.len()) + .fold(0_usize, usize::saturating_add); + if endpoint_count > MAX_ENDPOINTS { + return Some(resource_limit_detail( + "endpoints", + endpoint_count, + MAX_ENDPOINTS, + )); + } + + let binary_count = policies + .iter() + .flat_map(|policy| policy.network_policies.values()) + .map(|rule| rule.binaries.len()) + .fold(0_usize, usize::saturating_add); + if binary_count > MAX_BINARIES { + return Some(resource_limit_detail( + "binaries", + binary_count, + MAX_BINARIES, + )); + } + + let mut port_entry_count = 0_usize; + let mut l7_count = 0_usize; + let mut total_pattern_bytes = 0_usize; + for policy in policies { + for path in policy + .filesystem_policy + .read_only + .iter() + .chain(&policy.filesystem_policy.read_write) + { + if let Some(reason) = account_pattern_bytes(path, &mut total_pattern_bytes) { + return Some(reason); + } + } + for rule in policy.network_policies.values() { + for binary in &rule.binaries { + if let Some(reason) = account_pattern_bytes(&binary.path, &mut total_pattern_bytes) + { + return Some(reason); + } + } + for endpoint in &rule.endpoints { + let endpoint_port_entries = + usize::from(endpoint.ports.is_empty() && endpoint.port != 0) + .max(endpoint.ports.len()); + port_entry_count = port_entry_count.saturating_add(endpoint_port_entries); + if port_entry_count > MAX_PORT_ENTRIES { + return Some(resource_limit_detail( + "port_entries", + port_entry_count, + MAX_PORT_ENTRIES, + )); + } + + l7_count = l7_count + .saturating_add(endpoint.rules.len()) + .saturating_add(endpoint.deny_rules.len()); + if l7_count > MAX_L7_RULES { + return Some(resource_limit_detail("l7_rules", l7_count, MAX_L7_RULES)); + } + + for value in [&endpoint.host, &endpoint.path] { + if let Some(reason) = account_pattern_bytes(value, &mut total_pattern_bytes) { + return Some(reason); + } + } + for rule in &endpoint.rules { + for value in [&rule.allow.path, &rule.allow.method] { + if let Some(reason) = account_pattern_bytes(value, &mut total_pattern_bytes) + { + return Some(reason); + } + } + } + for rule in &endpoint.deny_rules { + for value in [&rule.path, &rule.method] { + if let Some(reason) = account_pattern_bytes(value, &mut total_pattern_bytes) + { + return Some(reason); + } + } + } + } + } + } + None +} + +fn account_pattern_bytes(value: &str, total: &mut usize) -> Option { + if value.len() > MAX_PATTERN_BYTES { + return Some(resource_limit_detail( + "longest_pattern", + value.len(), + MAX_PATTERN_BYTES, + )); + } + *total = total.saturating_add(value.len()); + (*total > MAX_TOTAL_PATTERN_BYTES) + .then(|| resource_limit_detail("pattern_bytes", *total, MAX_TOTAL_PATTERN_BYTES)) +} + +fn resource_limit_detail(metric: &str, observed: usize, limit: usize) -> String { + format!("containment model exceeds resource limit ({metric}={observed}, limit={limit})") +} + +fn unsupported_allow(rule: &Allow) -> bool { + rule.method.is_empty() + || !rule.command.is_empty() + || !rule.query.is_empty() + || !rule.operation_type.is_empty() + || !rule.operation_name.is_empty() + || !rule.fields.is_empty() + || rule.tool.is_some() + || !rule.params.is_empty() + || (!rule.path.is_empty() && !rule.path.starts_with('/')) + || (!rule.path.is_empty() && !is_canonical_pattern_path(&rule.path)) + || unsupported_glob(&rule.path) +} + +fn unsupported_deny(rule: &DenyRule) -> bool { + rule.method.is_empty() + || !rule.command.is_empty() + || !rule.query.is_empty() + || !rule.operation_type.is_empty() + || !rule.operation_name.is_empty() + || !rule.fields.is_empty() + || rule.tool.is_some() + || !rule.params.is_empty() + || (!rule.path.is_empty() && !rule.path.starts_with('/')) + || (!rule.path.is_empty() && !is_canonical_pattern_path(&rule.path)) + || unsupported_glob(&rule.path) +} + +fn is_canonical_pattern_path(path: &str) -> bool { + path.starts_with('/') + && !path.contains("//") + && !path.split('/').any(|segment| matches!(segment, "." | "..")) +} + +fn unsupported_glob(pattern: &str) -> bool { + pattern + .chars() + .any(|character| matches!(character, '?' | '[' | ']' | '{' | '}' | '\\')) +} + +fn unsupported_host_glob(pattern: &str) -> bool { + if unsupported_glob(pattern) + || pattern == "*" + || pattern == "**" + || pattern.chars().any(char::is_whitespace) + || pattern.split('.').any(str::is_empty) + { + return true; + } + let labels = pattern.split('.').collect::>(); + let minimum_name_len = labels + .iter() + .map(|label| label.bytes().filter(|byte| *byte != b'*').count().max(1)) + .sum::() + + labels.len().saturating_sub(1); + minimum_name_len > 253 + || labels.iter().enumerate().any(|(index, label)| { + let first = label.as_bytes().first().copied(); + let last = label.as_bytes().last().copied(); + let minimum_label_len = label.bytes().filter(|byte| *byte != b'*').count().max(1); + minimum_label_len > 63 + || !label + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'*')) + || first == Some(b'-') + || last == Some(b'-') + || (label.contains("**") && *label != "**") + || (index > 0 && label.contains('*') && *label != "*" && *label != "**") + }) +} + +fn bool_or(values: impl IntoIterator) -> Bool { + let values = values.into_iter().collect::>(); + if values.is_empty() { + Bool::from_bool(false) + } else { + Bool::or(&values) + } +} + +fn str_eq_any(value: &Z3String, options: &[&str]) -> Bool { + bool_or(options.iter().map(|option| value.eq(*option))) +} + +fn str_eq_any_case_insensitive(value: &Z3String, options: &[&str]) -> Bool { + bool_or( + options + .iter() + .map(|option| value.eq(option.to_ascii_uppercase())), + ) +} + +fn glob_regex(pattern: &str, separator: &str) -> Regexp { + if pattern == "**" { + return Regexp::full(); + } + if separator == "/" { + return path_glob_regex(pattern); + } + let mut parts = Vec::new(); + let mut chars = pattern.chars().peekable(); + while let Some(character) = chars.next() { + if character == '*' && chars.peek() == Some(&'*') { + chars.next(); + parts.push(Regexp::full()); + } else if character == '*' { + let wildcard = non_separator_regex(separator); + parts.push(wildcard.star()); + } else { + parts.push(Regexp::literal(&character.to_string())); + } + } + if parts.is_empty() { + Regexp::literal("") + } else { + let refs = parts.iter().collect::>(); + Regexp::concat(&refs) + } +} + +fn path_glob_regex(pattern: &str) -> Regexp { + let mut parts = Vec::new(); + let mut segments = pattern.split('/').peekable(); + while let Some(segment) = segments.next() { + if segment == "**" { + // glob.match collapses consecutive recursive components. A middle + // ** includes its following slash and can match zero directories. + while segments.peek() == Some(&"**") { + segments.next(); + } + let recursive = Regexp::full(); + parts.push(if segments.peek().is_some() { + Regexp::union(&[ + &Regexp::literal(""), + &Regexp::concat(&[&recursive, &Regexp::literal("/")]), + ]) + } else { + recursive + }); + } else { + for character in segment.chars() { + // Embedded stars, including **, cannot cross a separator. + parts.push(if character == '*' { + non_separator_regex("/").star() + } else { + Regexp::literal(&character.to_string()) + }); + } + if segments.peek().is_some() { + parts.push(Regexp::literal("/")); + } + } + } + if parts.is_empty() { + Regexp::literal("") + } else { + Regexp::concat(&parts.iter().collect::>()) + } +} + +fn non_separator_regex(separator: &str) -> Regexp { + // Runtime globs match Unicode values. Describe a non-empty separator-free + // sequence from Z3's full string language instead of limiting wildcards to + // character ranges. This works with both supported Z3 versions; callers' + // `star` and `plus` operations preserve the runtime wildcard languages. + let contains_separator = Regexp::concat(&[ + &Regexp::full(), + &Regexp::literal(separator), + &Regexp::full(), + ]); + Regexp::intersect(&[ + &contains_separator.complement(), + &Regexp::literal("").complement(), + ]) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + use std::fmt::Write as _; + + fn parse(value: &str) -> ContainmentPolicy { + parse_policy_str(value).expect("valid policy") + } + + fn options() -> CheckOptions { + CheckOptions::new(Duration::from_secs(10)) + } + + #[test] + fn filesystem_containment_and_counterexample() { + let boundary = + parse("version: 1\nfilesystem_policy: { read_only: [/usr], read_write: [/tmp] }\n"); + let within = parse("version: 1\nfilesystem_policy: { read_only: [/usr, /tmp] }\n"); + let exceeds = parse("version: 1\nfilesystem_policy: { read_write: [/workspace] }\n"); + assert!(matches!( + check_within_boundary(&boundary, &within, options()), + CheckResult::Within(_) + )); + assert!(matches!( + check_within_boundary( + &parse("version: 1\nfilesystem_policy: {}\n"), + &exceeds, + options() + ), + CheckResult::Exceeds(_) + )); + } + + #[test] + fn absent_filesystem_policy_uses_the_runtime_workdir_default() { + let omitted = parse("version: 1\n"); + assert!(omitted.filesystem_policy.include_workdir); + + let explicit = parse("version: 1\nfilesystem_policy: {}\n"); + assert!(!explicit.filesystem_policy.include_workdir); + + assert!(matches!( + check_within_boundary(&explicit, &omitted, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedWorkdir + )); + } + + #[test] + fn l4_contains_rest_but_not_the_reverse() { + let l4 = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let rest = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&l4, &rest, options()), + CheckResult::Within(_) + )); + assert!(matches!( + check_within_boundary(&rest, &l4, options()), + CheckResult::Exceeds(_) + )); + } + + #[test] + fn network_containment_covers_disabled_binary_identity() { + let boundary = parse("version: 1\n"); + let candidate = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: []\n", + ); + let result = check_within_boundary(&boundary, &candidate, options()); + assert!(matches!( + result, + CheckResult::Exceeds(ref evidence) + if matches!( + evidence.counterexample(), + Counterexample::Network { + binary: None, + binary_identity_required: false, + .. + } + ) + )); + } + + #[test] + fn underscore_hosts_are_present_in_the_full_action_domain() { + let cases = [ + ("api_internal.example.com", ""), + ("_service.example.com", "tcp"), + ("a_b.test", "rest"), + ]; + + for (host, protocol) in cases { + let endpoint = if protocol == "rest" { + format!( + "{{ host: {host}, port: 443, protocol: rest, enforcement: enforce, access: read-only }}" + ) + } else if protocol == "tcp" { + format!("{{ host: {host}, port: 443, protocol: tcp }}") + } else { + format!("{{ host: {host}, port: 443 }}") + }; + let candidate = parse(&format!( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{endpoint}]\n binaries: []\n" + )); + let result = check_within_boundary(&parse("version: 1\n"), &candidate, options()); + assert!( + matches!( + result, + CheckResult::Exceeds(ref evidence) + if matches!( + evidence.counterexample(), + Counterexample::Network { host: witness, .. } if witness == host + ) + ), + "protocol={protocol:?} host={host}: {result:?}" + ); + } + } + + #[test] + fn underscore_hosts_preserve_exact_and_wildcard_containment() { + let boundary = parse( + "version: 1\nnetwork_policies:\n boundary:\n endpoints: [{ host: '*.example.com', port: 443 }]\n binaries: []\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n candidate:\n endpoints: [{ host: api_internal.example.com, port: 443 }]\n binaries: []\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Within(_) + )); + + let exact_boundary = parse( + "version: 1\nnetwork_policies:\n boundary:\n endpoints: [{ host: _service.example.com, port: 443, protocol: tcp }]\n binaries: []\n", + ); + let exact_candidate = parse( + "version: 1\nnetwork_policies:\n candidate:\n endpoints: [{ host: _service.example.com, port: 443, protocol: tcp }]\n binaries: []\n", + ); + assert!(matches!( + check_within_boundary(&exact_boundary, &exact_candidate, options()), + CheckResult::Within(_) + )); + } + + #[test] + fn host_action_domain_covers_noncanonical_wildcard_matches() { + for (pattern, host) in [ + ("*.example.com", ".example.com".to_owned()), + ("**.example.com", "api..example.com".to_owned()), + ("*.example.com", "é.example.com".to_owned()), + ("*.example.com", "$service.example.com".to_owned()), + ("*.example.com", "-api.example.com".to_owned()), + ("*.example.com", format!("{}.example.com", "a".repeat(242))), + ] { + let solver = Solver::new(); + let action = symbolic_action("host_superset"); + assert_action_domain(&solver, &action, false); + solver.assert(action.host.eq(Z3String::from_str(&host).unwrap())); + solver.assert(action.host.regex_matches(&glob_regex(pattern, "."))); + assert_eq!( + solver.check(), + SatResult::Sat, + "pattern={pattern:?} host={host:?}" + ); + } + } + + #[test] + fn host_literals_enforce_modeled_label_and_name_boundaries() { + let maximum_length = format!( + "{}.{}.{}.{}", + "a".repeat(63), + "b".repeat(63), + "c".repeat(63), + "d".repeat(61) + ); + assert_eq!(maximum_length.len(), 253); + assert!(is_canonical_dns_host(&maximum_length)); + assert!(!unsupported_host_glob(&maximum_length)); + assert!(is_canonical_dns_host("_service.example.com")); + assert!(is_canonical_dns_host("api-internal.example.com")); + + let oversized_label = format!("{}.example.com", "a".repeat(64)); + assert!(!is_canonical_dns_host(&oversized_label)); + assert!(unsupported_host_glob(&oversized_label)); + + let oversized_name = format!( + "{}.{}.{}.{}", + "a".repeat(63), + "b".repeat(63), + "c".repeat(63), + "d".repeat(62) + ); + assert_eq!(oversized_name.len(), 254); + assert!(!is_canonical_dns_host(&oversized_name)); + assert!(unsupported_host_glob(&oversized_name)); + assert!(unsupported_host_glob("api$.example.com")); + for unsupported in ["-api.example.com", "api-.example.com"] { + assert!(!is_canonical_dns_host(unsupported)); + assert!(unsupported_host_glob(unsupported)); + + let candidate = parse(&format!( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{{ host: {unsupported}, port: 443 }}]\n binaries: []\n" + )); + assert!(matches!( + check_within_boundary(&parse("version: 1\n"), &candidate, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnsupportedPolicyShape + && evidence.reason().contains("endpoint host") + )); + } + } + + #[test] + fn differing_binary_selectors_are_checked_when_identity_is_required() { + let boundary = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/wget }]\n", + ); + let result = check_within_boundary(&boundary, &candidate, options()); + assert!(matches!( + result, + CheckResult::Exceeds(ref evidence) + if matches!( + evidence.counterexample(), + Counterexample::Network { + binary_identity_required: true, + .. + } + ) + )); + } + + #[test] + fn explicit_deny_removes_authority() { + let boundary = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n access: full\n deny_rules: [{ method: DELETE, path: /** }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: DELETE, path: /private/resource } }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let result = check_within_boundary(&boundary, &candidate, options()); + assert!(matches!(result, CheckResult::Exceeds(_)), "{result:?}"); + } + + #[test] + fn host_wildcard_zero_length_suffix_preserves_exact_deny() { + let boundary = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: 'api*.example.com', port: 443, protocol: rest, enforcement: enforce, access: full }\n binaries: [{ path: /usr/bin/curl }]\n deny:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n access: full\n deny_rules: [{ method: GET, path: '/**' }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: 'api*.example.com', port: 443, protocol: rest, enforcement: enforce, access: full }\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let result = check_within_boundary(&boundary, &candidate, options()); + assert!(matches!( + result, + CheckResult::Exceeds(ref evidence) + if matches!( + evidence.counterexample(), + Counterexample::Network { host, .. } if host == "api.example.com" + ) + )); + } + + #[test] + fn ancestor_binary_can_supply_a_boundary_deny() { + let boundary = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }\n binaries: [{ path: /usr/bin/curl }]\n deny:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n access: read-only\n deny_rules: [{ method: '*', path: '/**' }]\n binaries: [{ path: /usr/bin/python3 }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }\n binaries: [{ path: /usr/bin/curl }]\n deny:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n access: read-only\n deny_rules: [{ method: '*', path: '/**' }]\n binaries: [{ path: /usr/bin/node }]\n", + ); + let result = check_within_boundary(&boundary, &candidate, options()); + assert!( + matches!( + result, + CheckResult::Exceeds(ref evidence) + if matches!( + evidence.counterexample(), + Counterexample::Network { + binary: Some(binary), + ancestor_binary: Some(ancestor), + binary_identity_required: true, + .. + } if (binary == "/usr/bin/curl" && ancestor == "/usr/bin/python3") + || (binary == "/usr/bin/python3" && ancestor == "/usr/bin/curl") + ) + ), + "{result:?}" + ); + } + + #[test] + fn exact_boundary_deny_under_candidate_glob_requires_image_resolution() { + let boundary = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }\n binaries: [{ path: '/**' }]\n deny:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n access: read-only\n deny_rules: [{ method: '*', path: '/**' }]\n binaries: [{ path: /venv/bin/python }]\n", + ); + for pattern in ["/venv/bin/*", "/venv/bin/py**", "/venv/bin/**thon"] { + let candidate = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }\n binaries: [{ path: '/**' }]\n deny:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n access: read-only\n deny_rules: [{ method: '*', path: '/**' }]\n binaries: [{ path: 'BINARY_GLOB' }]\n".replace("BINARY_GLOB", pattern).as_str(), + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedBinaryPath + )); + } + } + + #[test] + fn definite_network_expansion_precedes_symlink_uncertainty() { + let boundary = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }\n binaries: [{ path: '/**' }]\n deny:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n access: read-only\n deny_rules: [{ method: '*', path: '/**' }]\n binaries: [{ path: /venv/bin/python }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }\n binaries: [{ path: '/**' }]\n extra:\n endpoints: [{ host: extra.example.com, port: 443 }]\n binaries: [{ path: '/**' }]\n deny:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n access: read-only\n deny_rules: [{ method: '*', path: '/**' }]\n binaries: [{ path: '/venv/bin/*' }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Exceeds(_) + )); + } + + #[test] + fn overlapping_l4_and_rest_authority_is_unsupported() { + let boundary = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - { host: api.example.com, port: 443 }\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnsupportedPolicyShape + )); + } + + #[test] + fn methods_longer_than_sixty_four_bytes_are_in_the_action_domain() { + let method = "X".repeat(65); + let boundary = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, rules: [{ allow: { method: GET, path: '/**' } }] }\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let candidate = parse(&format!( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - {{ host: api.example.com, port: 443, protocol: rest, enforcement: enforce, rules: [{{ allow: {{ method: {method}, path: '/**' }} }}] }}\n binaries: [{{ path: /usr/bin/curl }}]\n" + )); + let result = check_within_boundary(&boundary, &candidate, options()); + assert!(matches!( + result, + CheckResult::Exceeds(ref evidence) + if matches!( + evidence.counterexample(), + Counterexample::Network { method: Some(value), .. } if value == &method + ) + )); + } + + #[test] + fn rest_methods_and_paths_must_be_narrower() { + let boundary = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: GET, path: '/repos/**' } }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let narrower = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: GET, path: '/repos/NVIDIA/**' } }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let broader_method = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: POST, path: '/repos/NVIDIA/**' } }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let options = CheckOptions::new(Duration::from_secs(30)); + let result = check_within_boundary(&boundary, &narrower, options); + assert!(matches!(result, CheckResult::Within(_)), "{result:?}"); + let result = check_within_boundary(&boundary, &broader_method, options); + assert!(matches!(result, CheckResult::Exceeds(_)), "{result:?}"); + } + + #[test] + fn structural_path_containment_requires_a_recursive_segment_boundary() { + assert!(path_pattern_contains("/repos/**", "/repos/NVIDIA/**")); + assert!(!path_pattern_contains("/repos/**", "/repository/NVIDIA/**")); + assert!(!path_pattern_contains("/repos**", "/repos/NVIDIA/**")); + } + + #[test] + fn structural_fast_path_does_not_ignore_separate_boundary_denies() { + let boundary = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, rules: [{ allow: { method: GET, path: '/repos/**' } }] }\n binaries: [{ path: /usr/bin/curl }]\n deny:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, access: full, deny_rules: [{ method: GET, path: '/repos/private/**' }] }\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n allow:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, rules: [{ allow: { method: GET, path: '/repos/private/**' } }] }\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(!network_is_structurally_contained( + &boundary, &candidate, true + )); + } + + #[test] + fn unknown_and_environment_dependent_shapes_fail_closed() { + assert!(parse_policy_str("version: 1\nfuture_authority: true\n").is_err()); + let workdir = parse("version: 1\nfilesystem_policy: { include_workdir: true }\n"); + let empty = parse("version: 1\nfilesystem_policy: {}\n"); + assert!(matches!( + check_within_boundary(&empty, &workdir, options()), + CheckResult::Unsupported(_) + )); + let boundary_workdir = parse("version: 1\nfilesystem_policy: { include_workdir: true }\n"); + let explicit = parse("version: 1\nfilesystem_policy: { read_write: [/workspace] }\n"); + assert!(matches!( + check_within_boundary(&boundary_workdir, &explicit, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedWorkdir + )); + } + + #[test] + fn mcp_authority_fails_closed_in_both_inputs() { + let mcp = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: mcp\n enforcement: enforce\n access: full\n mcp: {}\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let empty = parse("version: 1\n"); + for (boundary, candidate, side) in [(&mcp, &empty, "boundary"), (&empty, &mcp, "candidate")] + { + let result = check_within_boundary(boundary, candidate, options()); + assert!( + matches!( + result, + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnsupportedPolicyShape + && evidence.reason().contains(side) + ), + "side={side} result={result:?}" + ); + } + } + + #[test] + fn exact_binary_under_a_boundary_glob_requires_image_resolution() { + for pattern in ["/usr/bin/*3", "/usr/bin/py**", "/usr/bin/**3"] { + let boundary = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: 'BINARY_GLOB' }]\n".replace("BINARY_GLOB", pattern).as_str(), + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/python3 }]\n", + ); + let result = check_within_boundary(&boundary, &candidate, options()); + assert!( + matches!( + result, + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedBinaryPath + ), + "{result:?}" + ); + } + } + + #[test] + fn unrelated_boundary_glob_does_not_make_exact_containment_unsupported() { + let boundary = parse( + "version: 1\nnetwork_policies:\n exact:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n unrelated:\n endpoints: [{ host: other.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n exact:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Within(_) + )); + } + + #[test] + fn redundant_boundary_glob_does_not_hide_equivalent_exact_containment() { + let boundary = parse( + "version: 1\nnetwork_policies:\n exact:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n glob:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n exact:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let result = check_within_boundary(&boundary, &candidate, options()); + assert!(matches!(result, CheckResult::Within(_)), "{result:?}"); + } + + #[test] + fn unrelated_universal_glob_does_not_hide_symlink_ambiguity() { + let boundary = parse( + "version: 1\nnetwork_policies:\n ambiguous:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n unrelated:\n endpoints: [{ host: unrelated.example.com, port: 80 }]\n binaries: [{ path: '/**' }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n exact:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedBinaryPath + )); + } + + #[test] + fn shared_glob_does_not_hide_exact_binary_symlink_ambiguity() { + let boundary = parse( + "version: 1\nnetwork_policies:\n shared:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n shared:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/*' }, { path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedBinaryPath + )); + } + + #[test] + fn wildcard_endpoint_overlap_does_not_hide_symlink_ambiguity() { + let boundary = parse( + "version: 1\nnetwork_policies:\n shared:\n endpoints: [{ host: '*.example.com', port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n shared:\n endpoints: [{ host: '*.example.com', port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n exact:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedBinaryPath + )); + } + + #[test] + fn ambiguity_check_preserves_shared_unrelated_globs() { + let boundary = parse( + "version: 1\nnetwork_policies:\n exact:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n ambiguous:\n endpoints: [{ host: unrelated.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n shared:\n endpoints: [{ host: shared.example.com, port: 443 }, { host: mirror.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n exact:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n shared:\n endpoints: [{ host: mirror.example.com, port: 443 }, { host: shared.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Within(_) + )); + } + + #[test] + fn reflexive_and_rule_order_invariant() { + let first = parse( + "version: 1\nnetwork_policies:\n a:\n endpoints: [{ host: '*.example.com', port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n b:\n endpoints: [{ host: api.example.org, port: 8443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let second = parse( + "version: 1\nnetwork_policies:\n b:\n endpoints: [{ host: api.example.org, port: 8443 }]\n binaries: [{ path: /usr/bin/curl }]\n a:\n endpoints: [{ host: '*.example.com', port: 443 }]\n binaries: [{ path: '/usr/bin/*' }]\n", + ); + let reflexive = check_within_boundary(&first, &first, options()); + assert!(matches!(reflexive, CheckResult::Within(_)), "{reflexive:?}"); + assert!(matches!( + check_within_boundary(&first, &second, options()), + CheckResult::Within(_) + )); + assert!(matches!( + check_within_boundary(&second, &first, options()), + CheckResult::Within(_) + )); + } + + #[test] + fn containment_is_transitive() { + let broad = parse("version: 1\nfilesystem_policy: { read_write: [/workspace, /tmp] }\n"); + let middle = parse("version: 1\nfilesystem_policy: { read_write: [/workspace] }\n"); + let narrow = parse("version: 1\nfilesystem_policy: { read_only: [/workspace] }\n"); + assert!(matches!( + check_within_boundary(&broad, &middle, options()), + CheckResult::Within(_) + )); + assert!(matches!( + check_within_boundary(&middle, &narrow, options()), + CheckResult::Within(_) + )); + assert!(matches!( + check_within_boundary(&broad, &narrow, options()), + CheckResult::Within(_) + )); + } + + #[test] + fn removed_binary_harness_field_is_invalid_input() { + assert!(parse_policy_str( + "version: 1\nnetwork_policies:\n n:\n binaries: [{ path: /usr/bin/curl, harness: true }]\n" + ).is_err()); + } + + fn mixed_protocol_policy(endpoint_count: usize) -> ContainmentPolicy { + let l4 = parse( + "version: 1 +network_policies: + n: + endpoints: [{ host: l4-0.example.com, port: 443 }] +", + ) + .network_policies["n"] + .endpoints[0] + .clone(); + let rest = parse( + "version: 1 +network_policies: + n: + endpoints: [{ host: rest.example.com, port: 443, protocol: rest, enforcement: enforce, access: read-only }] +", + ) + .network_policies["n"] + .endpoints[0] + .clone(); + let l4_count = endpoint_count / 2; + let mut endpoints = Vec::with_capacity(endpoint_count); + for index in 0..l4_count { + let mut endpoint = l4.clone(); + endpoint.host = format!("l4-{index}.example.com"); + endpoints.push(endpoint); + } + for index in l4_count..endpoint_count { + let mut endpoint = rest.clone(); + endpoint.host = if index + 1 == endpoint_count { + "l4-0.example.com".to_owned() + } else { + format!("rest-{index}.example.com") + }; + endpoints.push(endpoint); + } + let mut policy = parse( + "version: 1 +", + ); + policy.network_policies.insert( + "mixed".to_owned(), + NetworkRule { + name: String::new(), + endpoints, + binaries: Vec::new(), + }, + ); + policy + } + + fn l4_policy(endpoint_count: usize, host_prefix: &str) -> ContainmentPolicy { + let template = parse( + "version: 1 +network_policies: + n: + endpoints: [{ host: api.example.com, port: 443 }] +", + ) + .network_policies["n"] + .endpoints[0] + .clone(); + let endpoints = (0..endpoint_count) + .map(|index| { + let mut endpoint = template.clone(); + endpoint.host = format!("{host_prefix}-{index}.example.com"); + endpoint + }) + .collect(); + let mut policy = parse( + "version: 1 +", + ); + policy.network_policies.insert( + "l4".to_owned(), + NetworkRule { + name: String::new(), + endpoints, + binaries: Vec::new(), + }, + ); + policy + } + + #[test] + fn resource_limits_precede_mixed_protocol_validation_for_either_input() { + let empty = parse( + "version: 1 +", + ); + let oversized = mixed_protocol_policy(MAX_ENDPOINTS + 1); + + assert!(matches!( + validate_supported_policy(&oversized, None), + Err(PolicyValidationError::Unsupported(_)) + )); + for (boundary, candidate) in [(&oversized, &empty), (&empty, &oversized)] { + let result = + preflight_and_validate_policies(boundary, candidate, options(), None, |_| { + panic!("semantic validation must not run after failed preflight") + }); + assert!(matches!( + result, + Some(CheckResult::Inconclusive(ref evidence)) + if evidence.reason_code() == ReasonCode::ResourceLimit + )); + assert!(matches!( + check_within_boundary(boundary, candidate, options()), + CheckResult::Inconclusive(ref evidence) + if evidence.reason_code() == ReasonCode::ResourceLimit + )); + } + } + + #[test] + fn aggregate_resource_limit_skips_both_validators() { + let boundary = l4_policy(MAX_ENDPOINTS / 2 + 1, "boundary"); + let candidate = l4_policy(MAX_ENDPOINTS / 2 + 1, "candidate"); + let empty = parse( + "version: 1 +", + ); + assert!(resource_limit_reason(&boundary, &empty).is_none()); + assert!(resource_limit_reason(&empty, &candidate).is_none()); + + let result = + preflight_and_validate_policies(&boundary, &candidate, options(), None, |_| { + panic!("semantic validation must not run after aggregate preflight failure") + }); + assert!(matches!( + result, + Some(CheckResult::Inconclusive(ref evidence)) + if evidence.reason_code() == ReasonCode::ResourceLimit + )); + } + + #[test] + fn permitted_preflight_invokes_both_validators() { + let boundary = l4_policy(1, "boundary"); + let candidate = l4_policy(1, "candidate"); + let calls = Cell::new(0); + let result = + preflight_and_validate_policies(&boundary, &candidate, options(), None, |_| { + calls.set(calls.get() + 1); + Ok(()) + }); + assert!(result.is_none()); + assert_eq!(calls.get(), 2); + } + + #[test] + fn aggregate_endpoint_limit_accepts_exactly_the_limit() { + let empty = parse( + "version: 1 +", + ); + let at_limit = mixed_protocol_policy(MAX_ENDPOINTS); + let over_limit = mixed_protocol_policy(MAX_ENDPOINTS + 1); + assert!(resource_limit_reason(&empty, &at_limit).is_none()); + assert!(resource_limit_reason(&at_limit, &empty).is_none()); + assert_eq!( + resource_limit_reason(&empty, &over_limit).as_deref(), + Some("containment model exceeds resource limit (endpoints=4097, limit=4096)") + ); + assert_eq!( + resource_limit_reason(&over_limit, &empty).as_deref(), + Some("containment model exceeds resource limit (endpoints=4097, limit=4096)") + ); + } + + #[test] + fn pattern_limit_diagnostic_reports_the_observed_count() { + let empty = parse( + "version: 1 +", + ); + let mut oversized = empty.clone(); + oversized + .filesystem_policy + .read_only + .push("x".repeat(MAX_PATTERN_BYTES + 1)); + assert_eq!( + resource_limit_reason(&empty, &oversized).as_deref(), + Some("containment model exceeds resource limit (longest_pattern=4097, limit=4096)") + ); + } + + #[test] + fn cancellation_precedes_resource_limits_and_validation() { + let empty = parse( + "version: 1 +", + ); + let oversized = mixed_protocol_policy(MAX_ENDPOINTS + 1); + let cancelled = AtomicBool::new(true); + assert!(matches!( + check_within_boundary_cancellable(&empty, &oversized, options(), &cancelled), + CheckResult::Inconclusive(ref evidence) + if evidence.reason_code() == ReasonCode::Cancelled + )); + } + + #[test] + fn indexed_cross_protocol_overlap_matches_pairwise_reference() { + fn pairwise(policy: &ContainmentPolicy) -> bool { + let endpoints = policy + .network_policies + .values() + .flat_map(|rule| &rule.endpoints) + .collect::>(); + endpoints.iter().enumerate().any(|(index, endpoint)| { + endpoints[index + 1..].iter().any(|other| { + endpoint.protocol_kind() != other.protocol_kind() + && endpoint_authority_may_overlap(endpoint, other) + }) + }) + } + + let policies = [ + "version: 1 +network_policies: + n: + endpoints: [{ host: api.example.com, port: 443 }, { host: API.EXAMPLE.COM, port: 443, protocol: rest }] +", + "version: 1 +network_policies: + n: + endpoints: [{ host: '*.example.com', ports: [80, 443] }, { host: api.other.test, port: 443, protocol: rest }] +", + "version: 1 +network_policies: + n: + endpoints: [{ host: api.example.com, port: 80 }, { host: api.example.com, port: 443, protocol: rest }] +", + "version: 1 +network_policies: + n: + endpoints: [{ host: api.example.com, ports: [80, 443] }, { host: other.example.com, ports: [443, 8443], protocol: rest }] +", + "version: 1 +network_policies: + a: + endpoints: [{ host: api.example.com, port: 443 }] + b: + endpoints: [{ host: api.example.com, port: 443 }, { host: api.example.com, port: 443, protocol: rest }] +", + ]; + for source in policies { + let policy = parse(source); + let indexed = validate_no_cross_protocol_overlap(&policy, None).is_err(); + assert_eq!(indexed, pairwise(&policy), "{source}"); + } + } + + #[test] + fn excessive_model_size_is_inconclusive() { + let boundary = parse("version: 1\n"); + let mut candidate = parse("version: 1\n"); + for index in 0..=1_024 { + candidate.network_policies.insert( + format!("rule-{index}"), + NetworkRule { + name: String::new(), + endpoints: Vec::new(), + binaries: Vec::new(), + }, + ); + } + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Inconclusive(ref evidence) + if evidence.reason_code() == ReasonCode::ResourceLimit + )); + } + + #[test] + fn shared_schema_preserves_filesystem_presence_and_json_inputs() { + let absent = parse(r#"{"version":1}"#); + let empty = parse(r#"{"version":1,"filesystem_policy":{}}"#); + assert!(absent.filesystem_policy.include_workdir); + assert!(!empty.filesystem_policy.include_workdir); + assert!(matches!( + check_within_boundary(&empty, &absent, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedWorkdir + )); + let normalized = parse("version: 1\nfilesystem_policy: { read_only: ['/usr//./lib/'] }\n"); + assert_eq!(normalized.filesystem_policy.read_only, ["/usr/lib"]); + } + + #[test] + fn invalid_version_and_relative_path_are_input_errors() { + assert!(parse_policy_str("version: 2\n").is_err()); + assert!(parse_policy_str("version: 1\nfilesystem_policy: { read_only: [tmp] }\n").is_err()); + assert!(parse_policy_str("version: 1\nversion: 1\n").is_err()); + let mut deep = String::from("version: 1\nfuture:\n"); + for depth in 0..=openshell_policy_schema::ParseLimits::default().max_depth { + writeln!(deep, "{}level-{depth}:", " ".repeat(depth + 1)).unwrap(); + } + writeln!( + deep, + "{}true", + " ".repeat(openshell_policy_schema::ParseLimits::default().max_depth + 2) + ) + .unwrap(); + assert!(parse_policy_str(&deep).is_err()); + } + + #[test] + fn rest_counterexamples_must_be_canonical_runtime_paths() { + for path in ["/", "/repos/NVIDIA/", "/a%20b"] { + assert!(is_canonical_rest_path(path), "rejected {path}"); + } + for path in ["/a//b", "/a/../b", "/a/./b", "/a;b", "/a%2fb", "/a%41"] { + assert!(!is_canonical_rest_path(path), "accepted {path}"); + } + } + + #[test] + fn a_pre_cancelled_check_is_inconclusive() { + let policy = parse("version: 1\n"); + let cancelled = AtomicBool::new(true); + assert!(matches!( + check_within_boundary_cancellable(&policy, &policy, options(), &cancelled), + CheckResult::Inconclusive(ref evidence) + if evidence.reason_code() == ReasonCode::Cancelled + )); + } + + #[test] + fn deprecated_tls_spelling_does_not_change_authority() { + let boundary = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n tls: terminate\n enforcement: enforce\n access: read-only\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let candidate = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules:\n - allow: { method: GET, path: '/v1/**' }\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Within(_) + )); + } + + #[test] + fn host_wildcards_do_not_cross_or_elide_labels() { + let boundary = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: '*.example.com', port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let nested = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: deep.api.example.com, port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&boundary, &nested, options()), + CheckResult::Exceeds(_) + )); + let recursive = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: '**.example.com', port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + assert!(matches!( + check_within_boundary(&recursive, &nested, options()), + CheckResult::Within(_) + )); + } + + #[test] + fn host_model_matches_the_runtime_matcher() { + let cases = [ + ("api.example.com", "api.example.com"), + ("api.example.com", "other.example.com"), + ("*.example.com", "api.example.com"), + ("*.example.com", "deep.api.example.com"), + ("**.example.com", "deep.api.example.com"), + ("**.example.com", "example.com"), + ("api*.example.com", "api.example.com"), + ("api*.example.com", "api-v2.example.com"), + ("api*.example.com", "api_internal.example.com"), + ("*.example.com", "_service.example.com"), + ("*.example.com", ".example.com"), + ("**.example.com", "api..example.com"), + ("*.example.com", "é.example.com"), + ("*.example.com", "$service.example.com"), + ("*.example.com", "-api.example.com"), + ("api-internal.example.com", "api-internal.example.com"), + ]; + let mut runtime = regorus::Engine::new(); + for (pattern, host) in cases { + let query = format!( + "glob.match({}, [\".\"], {})", + serde_json::to_string(pattern).unwrap(), + serde_json::to_string(host).unwrap() + ); + let actual = runtime.eval_query(query, false).unwrap(); + let expected = actual.result[0].expressions[0].value == regorus::Value::from(true); + let solver = Solver::new(); + let modeled = Z3String::from_str(host) + .unwrap() + .regex_matches(&glob_regex(pattern, ".")); + solver.assert(!modeled); + let prover = solver.check() == SatResult::Unsat; + assert_eq!(prover, expected, "pattern={pattern} host={host}"); + } + } + + #[test] + fn filesystem_normalization_matches_the_runtime_helper() { + for path in ["/", "/usr//bin/", "/workspace/./cache"] { + let parsed = parse(&format!( + "version: 1\nfilesystem_policy: {{ read_only: [{path}] }}\n" + )); + assert_eq!( + parsed.filesystem_policy.read_only[0], + openshell_core::paths::normalize_path(path) + ); + } + } + + #[test] + fn filesystem_comparisons_do_not_assume_path_ancestry_or_distinctness() { + for access in ["read_only", "read_write"] { + let boundary = parse(&format!( + "version: 1\nfilesystem_policy: {{ {access}: [/safe] }}\n" + )); + for path in [ + "/safe/link", + "/safe/child/file", + "/elsewhere", + "/safe-prefix", + ] { + let candidate = parse(&format!( + "version: 1\nfilesystem_policy: {{ {access}: [{path}] }}\n" + )); + assert!( + matches!( + check_within_boundary(&boundary, &candidate, options()), + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnresolvedFilesystemPath + ), + "access={access} path={path}" + ); + } + let matching = parse(&format!( + "version: 1\nfilesystem_policy: {{ {access}: [/safe, /safe] }}\n" + )); + assert!(matches!( + check_within_boundary(&boundary, &matching, options()), + CheckResult::Within(_) + )); + let root = parse(&format!( + "version: 1\nfilesystem_policy: {{ {access}: [/] }}\n" + )); + assert!(matches!( + check_within_boundary(&root, &boundary, options()), + CheckResult::Within(_) + )); + } + } + + #[test] + fn path_globs_match_the_runtime_builtin() { + let mut runtime = regorus::Engine::new(); + for pattern in [ + "/a/**/b", + "/**/b", + "/a/**/**/b", + "/a/**", + "/a/**/**", + "/a/**/", + "/a/*/b", + "/a/x**/b", + "/a/**x/b", + "/a/***/b", + "/a/**/x*/**/b", + ] { + for path in [ + "/a/b", + "/a/x/b", + "/a/x/y/b", + "/b", + "/a/", + "/a", + "/a/xb", + "/a/x/z/xb/y/b", + "/a/c", + "/a/é/b", + "/a/汉/b", + "/a/e\u{301}/b", + "/a/😀/b", + ] { + let query = format!( + "glob.match({}, [\"/\"], {})", + serde_json::to_string(pattern).unwrap(), + serde_json::to_string(path).unwrap() + ); + let actual = runtime.eval_query(query, false).unwrap(); + let expected = actual.result[0].expressions[0].value == regorus::Value::from(true); + let solver = Solver::new(); + solver.assert( + Z3String::from_str(path) + .unwrap() + .regex_matches(&glob_regex(pattern, "/")), + ); + assert_eq!( + solver.check() == SatResult::Sat, + expected, + "pattern={pattern} path={path}" + ); + } + } + } + + #[test] + fn z3_string_boundary_decodes_exactly_or_fails_closed() { + for (expected, exactly_decodable) in [ + ("ascii", true), + (r"a\b", true), + ("é", false), + ("e\u{301}", false), + ("𐐷", false), + ("😀", false), + ] { + let solver = Solver::new(); + let value = Z3String::fresh_const("round_trip"); + solver.assert(value.eq(Z3String::from_str(expected).unwrap())); + assert_eq!(solver.check(), SatResult::Sat, "value={expected:?}"); + let model = solver.get_model().unwrap(); + let decoded = model_string_exact(&model, &value); + if exactly_decodable { + assert_eq!(decoded.as_deref(), Some(expected), "value={expected:?}"); + } else if let Some(decoded) = decoded { + assert_eq!(decoded, expected, "value={expected:?}"); + } + } + } + + #[test] + fn unicode_network_literals_are_unsupported_in_both_inputs() { + let policies = [ + ( + "binary path", + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: api.example.com, port: 443 }]\n binaries: [{ path: '/usr/bin/é*' }]\n", + ), + ( + "endpoint host", + "version: 1\nnetwork_policies:\n n:\n endpoints: [{ host: 'é.example.com', port: 443 }]\n binaries: [{ path: /usr/bin/curl }]\n", + ), + ( + "endpoint path", + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - { host: api.example.com, port: 443, protocol: rest, enforcement: enforce, path: '/é/**', access: full }\n binaries: [{ path: /usr/bin/curl }]\n", + ), + ( + "REST allow method", + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: 'GÉT', path: '/**' } }]\n binaries: [{ path: /usr/bin/curl }]\n", + ), + ( + "REST allow path", + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: GET, path: '/é/**' } }]\n binaries: [{ path: /usr/bin/curl }]\n", + ), + ( + "REST deny method", + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: GET, path: '/**' } }]\n deny_rules: [{ method: 'DÉLETE', path: '/**' }]\n binaries: [{ path: /usr/bin/curl }]\n", + ), + ( + "REST deny path", + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: GET, path: '/**' } }]\n deny_rules: [{ method: GET, path: '/é/**' }]\n binaries: [{ path: /usr/bin/curl }]\n", + ), + ]; + let empty = parse("version: 1\n"); + for (field, yaml) in policies { + let policy = parse(yaml); + for (boundary, candidate, label) in [ + (&policy, &empty, "boundary"), + (&empty, &policy, "candidate"), + (&policy, &policy, "boundary"), + ] { + let result = check_within_boundary(boundary, candidate, options()); + assert!( + matches!( + result, + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnsupportedPolicyShape + && evidence.reason().contains(label) + && evidence.reason().contains(field) + ), + "field={field} input={label} result={result:?}" + ); + } + } + } + + #[test] + fn embedded_nul_network_literal_is_unsupported_before_solving() { + assert_eq!(unsupported_network_literal("ascii"), None); + assert_eq!( + unsupported_network_literal("é"), + Some("contains a non-ASCII literal") + ); + assert_eq!( + unsupported_network_literal("G\0ET"), + Some("contains an embedded NUL byte") + ); + + let policy = parse( + "version: 1\nnetwork_policies:\n n:\n endpoints:\n - host: api.example.com\n port: 443\n protocol: rest\n enforcement: enforce\n rules: [{ allow: { method: \"G\\0ET\", path: '/**' } }]\n binaries: [{ path: /usr/bin/curl }]\n", + ); + let empty = parse("version: 1\n"); + for (boundary, candidate, label) in [ + (&policy, &empty, "boundary"), + (&empty, &policy, "candidate"), + (&policy, &policy, "boundary"), + ] { + let result = check_within_boundary(boundary, candidate, options()); + assert!( + matches!( + result, + CheckResult::Unsupported(ref evidence) + if evidence.reason_code() == ReasonCode::UnsupportedPolicyShape + && evidence.reason().contains(label) + && evidence.reason().contains("REST allow method") + && evidence.reason().contains("NUL") + ), + "input={label} result={result:?}" + ); + } + } +} diff --git a/crates/openshell-prover/src/lib.rs b/crates/openshell-prover/src/lib.rs index 8efb21e6df..b8bd2bfc13 100644 --- a/crates/openshell-prover/src/lib.rs +++ b/crates/openshell-prover/src/lib.rs @@ -8,6 +8,7 @@ //! paths and write-bypass violations. pub mod accepted_risks; +pub mod containment; pub mod credentials; pub mod finding; pub mod model; diff --git a/crates/openshell-prover/tests/containment_api.rs b/crates/openshell-prover/tests/containment_api.rs new file mode 100644 index 0000000000..a3ac2d7465 --- /dev/null +++ b/crates/openshell-prover/tests/containment_api.rs @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Compile-time and behavioral coverage for the supported external API shape. + +use std::time::Duration; + +use openshell_prover::containment::{ + CheckDomain, CheckOptions, CheckResult, Counterexample, Protocol, ReasonCode, + check_within_boundary, parse_policy_str, +}; + +fn authorize(result: &CheckResult) -> bool { + matches!(result, CheckResult::Within(_)) +} + +fn result_state(result: &CheckResult) -> &'static str { + // CheckResult is intentionally exhaustive: adding an outcome is a breaking + // API change that requires callers to choose new fail-closed semantics. + match result { + CheckResult::Within(_) => "within", + CheckResult::Exceeds(_) => "exceeds", + CheckResult::Unsupported(_) => "unsupported", + CheckResult::Inconclusive(_) => "inconclusive", + } +} + +fn protocol_name(protocol: Protocol) -> &'static str { + match protocol { + Protocol::L4 => "l4", + Protocol::Rest => "rest", + _ => "unknown", + } +} + +fn domain_name(domain: CheckDomain) -> &'static str { + match domain { + CheckDomain::Filesystem => "filesystem", + CheckDomain::NetworkL4 => "network_l4", + CheckDomain::NetworkRest => "network_rest", + _ => "unknown", + } +} + +#[test] +fn external_callers_use_extensible_construction_and_matching_patterns() { + let boundary = parse_policy_str( + "version: 1\nfilesystem_policy: { read_only: [/data], include_workdir: false }\n", + ) + .expect("boundary should parse"); + let candidate = parse_policy_str( + "version: 1\nfilesystem_policy: { read_write: [/data], include_workdir: false }\n", + ) + .expect("candidate should parse"); + + let mut options = CheckOptions::new(Duration::from_secs(2)); + assert_eq!(options.timeout, Duration::from_secs(2)); + options.timeout = Duration::from_secs(3); + let result = check_within_boundary(&boundary, &candidate, options); + + assert_eq!(result_state(&result), "exceeds"); + assert!(!authorize(&result)); + let CheckResult::Exceeds(evidence) = &result else { + panic!("expected filesystem violation, got {result:?}"); + }; + assert_eq!(evidence.scope().model_version, "boundary-v1"); + assert!( + evidence + .scope() + .domains + .iter() + .any(|domain| domain_name(*domain) == "filesystem") + ); + match evidence.counterexample() { + Counterexample::Filesystem { access, path, .. } => { + assert_eq!(access.as_str(), "write"); + assert_eq!(path, "/data"); + } + Counterexample::Network { protocol, .. } => { + assert_ne!(protocol_name(*protocol), "unknown"); + } + _ => panic!("unknown counterexample kinds must fail closed"), + } +} + +#[test] +fn external_callers_read_reason_evidence_and_authorize_only_within() { + let policy = parse_policy_str( + "version: 1\nfilesystem_policy: { read_only: [/data], include_workdir: false }\n", + ) + .expect("policy should parse"); + + let within = check_within_boundary(&policy, &policy, CheckOptions::new(Duration::from_secs(1))); + assert!(authorize(&within)); + + let inconclusive = check_within_boundary(&policy, &policy, CheckOptions::new(Duration::ZERO)); + assert!(!authorize(&inconclusive)); + let CheckResult::Inconclusive(evidence) = &inconclusive else { + panic!("expected timeout evidence, got {inconclusive:?}"); + }; + assert_eq!(evidence.reason(), "solver timeout must be positive"); + assert_eq!(evidence.reason_code().as_str(), "solver_timeout"); + match evidence.reason_code() { + ReasonCode::SolverTimeout => {} + _ => panic!("unexpected reason code"), + } + assert_eq!(evidence.scope().policy_version, 1); +} diff --git a/crates/openshell-prover/tests/runtime_parity.rs b/crates/openshell-prover/tests/runtime_parity.rs new file mode 100644 index 0000000000..f124e82623 --- /dev/null +++ b/crates/openshell-prover/tests/runtime_parity.rs @@ -0,0 +1,468 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Regression tests against the network supervisor's actual Rego policy. + +use openshell_prover::containment::{ + CheckOptions, CheckResult, Counterexample, check_within_boundary, parse_policy_str, +}; +use regorus::{Engine, Value}; +use serde_json::json; +use std::time::Duration; + +const SANDBOX_POLICY_REGO: &str = + include_str!("../../openshell-supervisor-network/data/sandbox-policy.rego"); + +fn check(boundary: &str, candidate: &str) -> CheckResult { + let boundary = parse_policy_str(boundary).expect("boundary policy should parse"); + let candidate = parse_policy_str(candidate).expect("candidate policy should parse"); + check_within_boundary( + &boundary, + &candidate, + CheckOptions::new(Duration::from_secs(5)), + ) +} + +fn runtime_engine(policy: &str) -> Engine { + runtime_engine_with_identity(policy, true) +} + +fn runtime_engine_with_identity(policy: &str, require_binary_identity: bool) -> Engine { + let yaml: serde_yml::Value = serde_yml::from_str(policy).expect("valid policy YAML"); + let mut data = serde_json::to_value(yaml).expect("policy converts to JSON"); + data.as_object_mut().expect("policy is an object").insert( + "runtime".to_owned(), + json!({ "require_binary_identity": require_binary_identity }), + ); + + let mut engine = Engine::new(); + engine + .add_policy("sandbox-policy.rego".into(), SANDBOX_POLICY_REGO.into()) + .expect("runtime Rego should compile"); + engine + .add_data_json(&data.to_string()) + .expect("runtime policy data should load"); + engine +} + +fn runtime_input(binary: &str, ancestors: &[&str], host: &str, method: &str) -> Value { + serde_json::from_value(json!({ + "exec": { + "path": binary, + "ancestors": ancestors, + "cmdline_paths": [], + }, + "network": { + "host": host, + "port": 443, + }, + "request": { + "method": method, + "path": "/", + "query_params": {}, + }, + })) + .expect("input converts to a Rego value") +} + +fn eval_bool(engine: &mut Engine, input: &Value, rule: &str) -> bool { + engine.set_input(input.clone()); + engine + .eval_rule(rule.into()) + .expect("runtime rule should evaluate") + == Value::from(true) +} + +fn eval_array_len(engine: &mut Engine, input: &Value, rule: &str) -> usize { + engine.set_input(input.clone()); + match engine + .eval_rule(rule.into()) + .expect("runtime rule should evaluate") + { + Value::Array(values) => values.len(), + Value::Undefined => 0, + value => panic!("expected array from {rule}, got {value:?}"), + } +} + +#[test] +fn underscore_host_counterexample_replays_at_runtime() { + let boundary = "version: 1\n"; + let candidate = r" +version: 1 +network_policies: + egress: + endpoints: [{ host: api_internal.example.com, ports: [443] }] + binaries: [{ path: /usr/bin/curl }] +"; + let result = check(boundary, candidate); + let CheckResult::Exceeds(evidence) = result else { + panic!("expected exceeding witness, got {result:?}"); + }; + let Counterexample::Network { + host, + binary_identity_required, + .. + } = evidence.counterexample() + else { + panic!("expected a network counterexample"); + }; + assert_eq!(host, "api_internal.example.com"); + + let input = runtime_input("/usr/bin/curl", &[], host, "GET"); + assert!(eval_bool( + &mut runtime_engine_with_identity(candidate, *binary_identity_required), + &input, + "data.openshell.sandbox.allow_network" + )); + assert!(!eval_bool( + &mut runtime_engine_with_identity(boundary, *binary_identity_required), + &input, + "data.openshell.sandbox.allow_network" + )); +} + +#[test] +fn recursive_path_globs_preserve_zero_directory_grants_and_denies() { + let policy = |grant: &str, deny: Option<&str>, endpoint: &str| { + json!({ + "version": 1, + "network_policies": {"n": { + "binaries": [{"path": "/usr/bin/curl"}], + "endpoints": [{ + "host": "api.example.com", "ports": [443], + "protocol": "rest", "enforcement": "enforce", "path": endpoint, + "rules": [{"allow": {"method": "GET", "path": grant}}], + "deny_rules": deny.into_iter().map(|path| json!({"method": "GET", "path": path})).collect::>() + }] + }} + }).to_string() + }; + for (boundary, candidate, within) in [ + ( + policy("/**", Some("/a/**/b"), ""), + policy("/a/b", None, ""), + false, + ), + ( + policy("/a/**/b", Some("/a/b"), ""), + policy("/a/**/b", None, ""), + false, + ), + (policy("/a/**/b", None, ""), policy("/a/b", None, ""), true), + ( + policy("/**", None, "/a/**/b"), + policy("/a/b", None, ""), + true, + ), + ] { + let input: Value = serde_json::from_value(json!({ + "exec": {"path": "/usr/bin/curl", "ancestors": [], "cmdline_paths": []}, + "network": {"host": "api.example.com", "port": 443}, + "request": {"method": "GET", "path": "/a/b", "query_params": {}} + })) + .unwrap(); + assert!(eval_bool( + &mut runtime_engine(&candidate), + &input, + "data.openshell.sandbox.allow_request" + )); + assert_eq!( + eval_bool( + &mut runtime_engine(&boundary), + &input, + "data.openshell.sandbox.allow_request" + ), + within + ); + let result = check(&boundary, &candidate); + if within { + assert!(matches!(result, CheckResult::Within(_)), "{result:?}"); + } else { + assert!(matches!(result, CheckResult::Exceeds(_)), "{result:?}"); + } + } +} + +#[test] +fn ascii_wildcards_match_unicode_runtime_paths_in_allows_and_denies() { + let candidate = r#" +version: 1 +network_policies: + grant: + endpoints: + - host: api.example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{ allow: { method: GET, path: "/items/*" } }] + binaries: [{ path: /usr/bin/curl }] +"#; + let boundary = r#" +version: 1 +network_policies: + grant: + endpoints: + - host: api.example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{ allow: { method: GET, path: "/**" } }] + deny_rules: [{ method: GET, path: "/items/*" }] + binaries: [{ path: /usr/bin/curl }] +"#; + + for path in ["/items/é", "/items/汉", "/items/e\u{301}", "/items/😀"] { + let input: Value = serde_json::from_value(json!({ + "exec": {"path": "/usr/bin/curl", "ancestors": [], "cmdline_paths": []}, + "network": {"host": "api.example.com", "port": 443}, + "request": {"method": "GET", "path": path, "query_params": {}} + })) + .unwrap(); + assert!( + eval_bool( + &mut runtime_engine(candidate), + &input, + "data.openshell.sandbox.allow_request" + ), + "candidate should allow {path:?}" + ); + assert!( + !eval_bool( + &mut runtime_engine(boundary), + &input, + "data.openshell.sandbox.allow_request" + ), + "boundary should deny {path:?}" + ); + } + assert!(matches!( + check(boundary, candidate), + CheckResult::Exceeds(_) + )); + + let binary_wildcard = r#" +version: 1 +network_policies: + grant: + endpoints: [{ host: api.example.com, ports: [443] }] + binaries: [{ path: "/usr/bin/*" }] +"#; + for binary in [ + "/usr/bin/é", + "/usr/bin/汉", + "/usr/bin/e\u{301}", + "/usr/bin/😀", + ] { + assert!( + eval_bool( + &mut runtime_engine(binary_wildcard), + &runtime_input(binary, &[], "api.example.com", "GET"), + "data.openshell.sandbox.allow_network" + ), + "runtime binary wildcard should allow {binary:?}" + ); + } +} + +#[test] +fn intra_label_host_wildcard_matches_empty_suffix_at_runtime() { + let boundary = r#" +version: 1 +network_policies: + grant: + endpoints: + - host: api*.example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{ allow: { method: GET, path: "/**" } }] + binaries: [{ path: /usr/bin/curl }] + exact_deny: + endpoints: + - host: api.example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{ allow: { method: GET, path: "/**" } }] + deny_rules: [{ method: GET, path: "/**" }] + binaries: [{ path: /usr/bin/curl }] +"#; + let candidate = r#" +version: 1 +network_policies: + grant: + endpoints: + - host: api*.example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{ allow: { method: GET, path: "/**" } }] + binaries: [{ path: /usr/bin/curl }] +"#; + let input = runtime_input("/usr/bin/curl", &[], "api.example.com", "GET"); + let mut boundary_runtime = runtime_engine(boundary); + let mut candidate_runtime = runtime_engine(candidate); + + assert!(eval_bool( + &mut candidate_runtime, + &input, + "data.openshell.sandbox.allow_request" + )); + assert!(!eval_bool( + &mut boundary_runtime, + &input, + "data.openshell.sandbox.allow_request" + )); + assert!(matches!( + check(boundary, candidate), + CheckResult::Exceeds(_) + )); +} + +#[test] +fn ancestor_identity_applies_to_runtime_denies() { + let boundary = policy_with_ancestor_deny("/usr/bin/python3"); + let candidate = policy_with_ancestor_deny("/usr/bin/node"); + let input = runtime_input("/usr/bin/curl", &["/usr/bin/python3"], "example.com", "GET"); + let mut boundary_runtime = runtime_engine(&boundary); + let mut candidate_runtime = runtime_engine(&candidate); + + assert!(eval_bool( + &mut candidate_runtime, + &input, + "data.openshell.sandbox.allow_request" + )); + assert!(!eval_bool( + &mut boundary_runtime, + &input, + "data.openshell.sandbox.allow_request" + )); + assert!(matches!( + check(&boundary, &candidate), + CheckResult::Exceeds(_) + )); +} + +fn policy_with_ancestor_deny(denied_binary: &str) -> String { + format!( + r#" +version: 1 +network_policies: + grant: + endpoints: + - host: example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{{ allow: {{ method: GET, path: "/**" }} }}] + binaries: [{{ path: /usr/bin/curl }}] + deny: + endpoints: + - host: example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{{ allow: {{ method: GET, path: "/**" }} }}] + deny_rules: [{{ method: "*", path: "/**" }}] + binaries: [{{ path: {denied_binary} }}] +"# + ) +} + +#[test] +fn inspected_endpoint_restricts_an_overlapping_l4_grant() { + let boundary = r#" +version: 1 +network_policies: + egress: + endpoints: + - { host: api.example.com, ports: [443] } + - host: api.example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{ allow: { method: GET, path: "/**" } }] + binaries: [{ path: /usr/bin/curl }] +"#; + let candidate = r" +version: 1 +network_policies: + egress: + endpoints: + - { host: api.example.com, ports: [443] } + binaries: [{ path: /usr/bin/curl }] +"; + let input = runtime_input("/usr/bin/curl", &[], "api.example.com", "POST"); + let mut boundary_runtime = runtime_engine(boundary); + let mut candidate_runtime = runtime_engine(candidate); + + assert_eq!( + eval_array_len( + &mut candidate_runtime, + &input, + "data.openshell.sandbox._matching_endpoint_configs" + ), + 0 + ); + assert_eq!( + eval_array_len( + &mut boundary_runtime, + &input, + "data.openshell.sandbox._matching_endpoint_configs" + ), + 1 + ); + assert!(!eval_bool( + &mut boundary_runtime, + &input, + "data.openshell.sandbox.allow_request" + )); + let result = check(boundary, candidate); + assert!( + matches!(result, CheckResult::Unsupported(_)), + "overlapping inspection must be rejected explicitly: {result:?}" + ); +} + +#[test] +fn runtime_accepts_methods_longer_than_sixty_four_bytes() { + let long_method = "X".repeat(65); + let boundary = rest_method_policy("GET"); + let candidate = rest_method_policy(&long_method); + let input = runtime_input("/usr/bin/curl", &[], "api.example.com", &long_method); + let mut boundary_runtime = runtime_engine(&boundary); + let mut candidate_runtime = runtime_engine(&candidate); + + assert!(eval_bool( + &mut candidate_runtime, + &input, + "data.openshell.sandbox.allow_request" + )); + assert!(!eval_bool( + &mut boundary_runtime, + &input, + "data.openshell.sandbox.allow_request" + )); + assert!(matches!( + check(&boundary, &candidate), + CheckResult::Exceeds(_) + )); +} + +fn rest_method_policy(method: &str) -> String { + format!( + r#" +version: 1 +network_policies: + egress: + endpoints: + - host: api.example.com + ports: [443] + protocol: rest + enforcement: enforce + rules: [{{ allow: {{ method: "{method}", path: "/**" }} }}] + binaries: [{{ path: /usr/bin/curl }}] +"# + ) +} diff --git a/crates/openshell-sandbox-backend/src/boundary_protocol.rs b/crates/openshell-sandbox-backend/src/boundary_protocol.rs index e619d68dc2..73668daae1 100644 --- a/crates/openshell-sandbox-backend/src/boundary_protocol.rs +++ b/crates/openshell-sandbox-backend/src/boundary_protocol.rs @@ -536,7 +536,8 @@ pub enum Request { provider_env: std::collections::HashMap, }, UpdateProviderEnvironment { - expected_revision: u64, + /// Ordered publication within this authenticated boundary session. + generation: u64, revision: u64, provider_env: std::collections::HashMap, }, @@ -634,12 +635,12 @@ impl fmt::Debug for Request { ) .finish(), Self::UpdateProviderEnvironment { - expected_revision, + generation, revision, provider_env, } => formatter .debug_struct("UpdateProviderEnvironment") - .field("expected_revision", expected_revision) + .field("generation", generation) .field("revision", revision) .field( "provider_env_keys", @@ -710,9 +711,13 @@ pub enum Response { Started { process_id: String, provider_env_revision: u64, + provider_env_generation: u64, }, ProviderEnvironmentUpdated { revision: u64, + generation: u64, + /// True only for this installed request or its exact idempotent replay. + applied: bool, }, ProcessAttached { terminal: bool, @@ -1298,7 +1303,7 @@ mod tests { second.insert("A".to_string(), "1".to_string()); second.insert("B".to_string(), "2".to_string()); let build = |provider_env| Request::UpdateProviderEnvironment { - expected_revision: 1, + generation: 1, revision: 2, provider_env, }; diff --git a/crates/openshell-sandbox-backend/src/runtime.rs b/crates/openshell-sandbox-backend/src/runtime.rs index 86964fc3c8..a411e77ec8 100644 --- a/crates/openshell-sandbox-backend/src/runtime.rs +++ b/crates/openshell-sandbox-backend/src/runtime.rs @@ -25,9 +25,10 @@ use openshell_isolation_interface::contract::{ BoundaryInput, BoundaryLoopbackConnector, BoundaryOutput, BoundaryProcess, BoundarySignal, BoundaryTerminal, ConfirmedBoundary, ExecSession, ExecSpec, IsolationBackend, LoopbackTarget, MediationTiming, NetworkMediationSource, PendingDnsQuery, PendingTcpOpen, ProcessAttachment, - ReadyBoundary, RunningBoundary, SandboxContext, TcpOpenDecision, TcpOpenDenial, - VerifiedBackendDescriptor, + ProviderEnvironmentInstallation, ReadyBoundary, RunningBoundary, SandboxContext, + TcpOpenDecision, TcpOpenDenial, VerifiedBackendDescriptor, }; +use sha2::{Digest as _, Sha256}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; #[cfg(unix)] use tokio::net::UnixStream; @@ -372,7 +373,8 @@ impl ReadyBoundary for RemoteReady { .await?; let Response::Started { process_id, - provider_env_revision, + provider_env_generation, + .. } = response else { return Err(unexpected_response("started", &response)); @@ -386,7 +388,7 @@ impl ReadyBoundary for RemoteReady { exec: Arc::new(RemoteExec { client: self.client.clone(), provider_credentials: self.provider_credentials, - boundary_revision: tokio::sync::Mutex::new(provider_env_revision), + publication_generation: tokio::sync::Mutex::new(provider_env_generation), }), loopback_connector: Arc::new(RemoteLoopbackConnector { client: self.client, @@ -551,30 +553,39 @@ async fn pump_process_responses( struct RemoteExec { client: Arc, provider_credentials: openshell_core::provider_credentials::ProviderCredentialState, - boundary_revision: tokio::sync::Mutex, + // Shared by proactive synchronization and exec. Reserve generations before + // dispatch so a timed-out request cannot overwrite a newer publication. + publication_generation: tokio::sync::Mutex, } -#[async_trait] -impl BoundaryExec for RemoteExec { - async fn exec(&self, spec: ExecSpec) -> Result { - let mut boundary_revision = self.boundary_revision.lock().await; +impl RemoteExec { + async fn synchronize( + &self, + generation: &mut u64, + ) -> Result { for _ in 0..3 { - let (revision, provider_env) = self + let snapshot = self .provider_credentials - .child_env_snapshot_with_gcp_resolved() + .child_environment_snapshot() .map_err(|error| { BackendError::Process(format!("snapshot provider environment: {error}")) })?; + *generation = generation.checked_add(1).ok_or_else(|| { + BackendError::Process("provider environment publication exhausted".to_string()) + })?; + let requested_generation = *generation; let response = self .client .call_idempotent(Request::UpdateProviderEnvironment { - expected_revision: *boundary_revision, - revision, - provider_env, + generation: requested_generation, + revision: snapshot.revision, + provider_env: snapshot.environment, }) .await?; let Response::ProviderEnvironmentUpdated { revision: effective_revision, + generation: effective_generation, + applied, } = response else { return Err(unexpected_response( @@ -582,9 +593,18 @@ impl BoundaryExec for RemoteExec { &response, )); }; - *boundary_revision = effective_revision; - if effective_revision == revision { - return open_exec_session(self.client.clone(), spec).await; + *generation = (*generation).max(effective_generation); + if applied + && effective_generation == requested_generation + && effective_revision == snapshot.revision + { + // The acknowledgment is for the exact request, including its + // map, even when a repaired map reuses a provider fingerprint. + return Ok(ProviderEnvironmentInstallation { + installation_id: snapshot.installation_id, + revision: snapshot.revision, + session_id: self.client.runtime_descriptor.session_id, + }); } } Err(BackendError::Process( @@ -593,6 +613,22 @@ impl BoundaryExec for RemoteExec { } } +#[async_trait] +impl BoundaryExec for RemoteExec { + async fn exec(&self, spec: ExecSpec) -> Result { + let mut generation = self.publication_generation.lock().await; + self.synchronize(&mut generation).await?; + open_exec_session(self.client.clone(), spec).await + } + + async fn synchronize_provider_environment( + &self, + ) -> Result { + let mut generation = self.publication_generation.lock().await; + self.synchronize(&mut generation).await + } +} + struct RemoteLoopbackConnector { client: Arc, } @@ -975,10 +1011,43 @@ struct BoundaryClient { #[derive(Clone)] struct CachedGrpcChannel { credential_epoch: openshell_core::jwt::CredentialEpoch, + bearer_fingerprint: [u8; 32], generation: u64, channel: tonic::transport::Channel, } +// Cache only a digest; authenticate with the exact captured header so a +// concurrent renewal cannot be recorded before its credential is sent. +struct BoundaryCredential { + epoch: openshell_core::jwt::CredentialEpoch, + authorization: tonic::metadata::AsciiMetadataValue, + fingerprint: [u8; 32], +} + +impl BoundaryCredential { + fn capture(slot: &openshell_core::jwt::SessionBearerTokenSlot) -> Result { + loop { + let epoch = slot.credential_epoch().ok_or_else(|| { + BackendError::Unavailable("Sandbox Protocol credential unavailable".to_string()) + })?; + let authorization = slot.authorization_metadata().map_err(|error| { + BackendError::Unavailable(format!( + "Sandbox Protocol credential unavailable: {error}" + )) + })?; + // Epochs are monotonic; retry if authorization crossed an epoch change. + if slot.credential_epoch() == Some(epoch) { + let fingerprint = Sha256::digest(authorization.as_encoded_bytes()).into(); + return Ok(Self { + epoch, + authorization, + fingerprint, + }); + } + } + } +} + impl BoundaryClient { fn new( runtime_descriptor: SandboxRuntimeDescriptor, @@ -1199,27 +1268,62 @@ impl BoundaryClient { } async fn ensure_current_credential_connection(&self) -> Result<(), BackendError> { - let credential_epoch = self.sandbox_bearer.credential_epoch().ok_or_else(|| { - BackendError::Unavailable("Sandbox Protocol credential unavailable".to_string()) - })?; + let credential = BoundaryCredential::capture(&self.sandbox_bearer)?; if self .grpc_channel .lock() .await .as_ref() - .is_none_or(|cached| cached.credential_epoch == credential_epoch) + .is_none_or(|cached| { + cached.credential_epoch == credential.epoch + && cached.bearer_fingerprint == credential.fingerprint + }) { return Ok(()); } - let _reconnect = self.reconnect.lock().await; - if self - .grpc_channel + let credential = BoundaryCredential::capture(&self.sandbox_bearer)?; + let Some(cached) = self.grpc_channel.lock().await.clone() else { + return Ok(()); + }; + if cached.credential_epoch == credential.epoch + && cached.bearer_fingerprint == credential.fingerprint + { + return Ok(()); + } + let confirm = self + .confirm_request .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let Some(confirm) = confirm else { + // Initial attach/confirm authenticates before the monitor runs. + return if cached.credential_epoch == credential.epoch { + Ok(()) + } else { + Err(BackendError::Unavailable( + "cannot rotate Sandbox Protocol connection before confirmation".to_string(), + )) + }; + }; + if cached.credential_epoch == credential.epoch { + // Renewal preserves the authorization epoch, but the boundary's + // connection deadline advances only on a newly authenticated RPC. + // Reconfirm on this channel to preserve pending accepts and streams. + let response = tokio::time::timeout( + REQUEST_TIMEOUT, + self.exchange_on_channel(cached.channel.clone(), &confirm, &credential), + ) .await - .as_ref() - .is_some_and(|cached| cached.credential_epoch == credential_epoch) - { + .map_err(|_| { + BackendError::Unavailable("boundary credential renewal timed out".to_string()) + })??; + expect_response(response, "confirmed")?; + if let Some(current) = self.grpc_channel.lock().await.as_mut() + && current.generation == cached.generation + { + current.bearer_fingerprint = credential.fingerprint; + } return Ok(()); } let attach = self @@ -1232,21 +1336,14 @@ impl BoundaryClient { "cannot rotate Sandbox Protocol connection before attach".to_string(), ) })?; - let confirm = self - .confirm_request - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - .ok_or_else(|| { - BackendError::Unavailable( - "cannot rotate Sandbox Protocol connection before confirmation".to_string(), - ) - })?; let channel = self.build_grpc_channel().await?; - self.exchange_on_channel(channel.clone(), &attach).await?; - self.exchange_on_channel(channel.clone(), &confirm).await?; + self.exchange_on_channel(channel.clone(), &attach, &credential) + .await?; + self.exchange_on_channel(channel.clone(), &confirm, &credential) + .await?; *self.grpc_channel.lock().await = Some(CachedGrpcChannel { - credential_epoch, + credential_epoch: credential.epoch, + bearer_fingerprint: credential.fingerprint, generation: self .next_connection_generation .fetch_add(1, Ordering::Relaxed), @@ -1292,16 +1389,17 @@ impl BoundaryClient { .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone(); - let credential_epoch = self.sandbox_bearer.credential_epoch().ok_or_else(|| { - BackendError::Unavailable("Sandbox Protocol credential unavailable".to_string()) - })?; + let credential = BoundaryCredential::capture(&self.sandbox_bearer)?; let channel = self.build_grpc_channel().await?; - self.exchange_on_channel(channel.clone(), &attach).await?; + self.exchange_on_channel(channel.clone(), &attach, &credential) + .await?; if let Some(confirm) = confirm { - self.exchange_on_channel(channel.clone(), &confirm).await?; + self.exchange_on_channel(channel.clone(), &confirm, &credential) + .await?; } *self.grpc_channel.lock().await = Some(CachedGrpcChannel { - credential_epoch, + credential_epoch: credential.epoch, + bearer_fingerprint: credential.fingerprint, generation: self .next_connection_generation .fetch_add(1, Ordering::Relaxed), @@ -1332,11 +1430,15 @@ impl BoundaryClient { &self, channel: tonic::transport::Channel, envelope: &RequestEnvelope, + credential: &BoundaryCredential, ) -> Result { let request_id = envelope.request_id.clone(); - let mut stream = - open_grpc_client_stream(channel, GrpcStreamKind::Exchange, &self.sandbox_bearer) - .await?; + let mut stream = open_grpc_client_stream_with_authorization( + channel, + GrpcStreamKind::Exchange, + credential.authorization.clone(), + ) + .await?; let frame = encode_frame(envelope) .map_err(|error| BackendError::Process(format!("encode control request: {error}")))?; stream.write_all(&frame).await.map_err(|error| { @@ -1444,12 +1546,11 @@ impl BoundaryClient { if let Some(cached) = state.as_ref() { return Ok(cached.channel.clone()); } - let credential_epoch = self.sandbox_bearer.credential_epoch().ok_or_else(|| { - BackendError::Unavailable("Sandbox Protocol credential unavailable".to_string()) - })?; + let credential = BoundaryCredential::capture(&self.sandbox_bearer)?; let channel = self.build_grpc_channel().await?; *state = Some(CachedGrpcChannel { - credential_epoch, + credential_epoch: credential.epoch, + bearer_fingerprint: credential.fingerprint, generation: self .next_connection_generation .fetch_add(1, Ordering::Relaxed), @@ -1566,6 +1667,17 @@ async fn open_grpc_client_stream( channel: tonic::transport::Channel, kind: GrpcStreamKind, sandbox_bearer: &openshell_core::jwt::SessionBearerTokenSlot, +) -> Result { + let authorization = sandbox_bearer.authorization_metadata().map_err(|error| { + BackendError::Unavailable(format!("Sandbox Protocol credential unavailable: {error}")) + })?; + open_grpc_client_stream_with_authorization(channel, kind, authorization).await +} + +async fn open_grpc_client_stream_with_authorization( + channel: tonic::transport::Channel, + kind: GrpcStreamKind, + authorization: tonic::metadata::AsciiMetadataValue, ) -> Result { let (application, bridge) = tokio::io::duplex(256 * 1024); let (reader, writer) = tokio::io::split(bridge); @@ -1575,9 +1687,6 @@ async fn open_grpc_client_stream( .max_decoding_message_size(64 * 1024) .max_encoding_message_size(64 * 1024); let mut request = tonic::Request::new(ReceiverStream::new(outbound_rx)); - let authorization = sandbox_bearer.authorization_metadata().map_err(|error| { - BackendError::Unavailable(format!("Sandbox Protocol credential unavailable: {error}")) - })?; request .metadata_mut() .insert("authorization", authorization); @@ -1754,6 +1863,8 @@ fn is_transport_unavailable(message: &str) -> bool { #[cfg(test)] mod tests { + mod credential_renewal; + use std::path::PathBuf; use std::pin::Pin; use std::task::{Context, Poll}; @@ -1796,6 +1907,7 @@ mod tests { requests: Arc, mediation_failures: Arc, mediation_ready: bool, + provider_environment_generation: u64, } type TestGrpcStream = Pin< @@ -1824,6 +1936,7 @@ mod tests { let wait_for_half_close = self.wait_for_half_close; let requests = self.requests.clone(); let mediation_ready = self.mediation_ready; + let provider_environment_generation = self.provider_environment_generation; let (outbound, outbound_rx) = tokio::sync::mpsc::channel(1); tokio::spawn(async move { let mut frame = Vec::new(); @@ -1885,9 +1998,15 @@ mod tests { } Request::Terminate { .. } => Response::Terminated, Request::TerminateBoundary => Response::BoundaryTerminated, - Request::UpdateProviderEnvironment { revision, .. } => { - Response::ProviderEnvironmentUpdated { revision } - } + Request::UpdateProviderEnvironment { + revision, + generation, + .. + } => Response::ProviderEnvironmentUpdated { + revision, + generation: generation.max(provider_environment_generation), + applied: generation > provider_environment_generation, + }, Request::Resize { .. } => Response::Resized, Request::LoopbackConnect { .. } => Response::PortConnected, Request::StartAgent { @@ -1896,6 +2015,7 @@ mod tests { } => Response::Started { process_id: "test-generation:main:0".to_string(), provider_env_revision, + provider_env_generation: provider_environment_generation, }, Request::AcceptNetwork => Response::Error { kind: crate::boundary_protocol::BoundaryErrorKind::Unavailable, @@ -1960,6 +2080,7 @@ mod tests { requests: requests.clone(), mediation_failures: Arc::new(std::sync::atomic::AtomicUsize::new(0)), mediation_ready: false, + provider_environment_generation: 0, }; let server = tokio::spawn(async move { let (stream, _) = listener.accept().await.unwrap(); @@ -1980,6 +2101,9 @@ mod tests { ); *client.grpc_channel.lock().await = Some(CachedGrpcChannel { credential_epoch: openshell_core::jwt::CredentialEpoch::new(1).expect("test epoch"), + bearer_fingerprint: BoundaryCredential::capture(&client.sandbox_bearer) + .expect("test bearer") + .fingerprint, generation: 1, channel, }); @@ -2020,6 +2144,7 @@ mod tests { requests: server_requests.clone(), mediation_failures: Arc::new(std::sync::atomic::AtomicUsize::new(0)), mediation_ready: false, + provider_environment_generation: 0, }; tokio::spawn(async move { tonic::transport::Server::builder() @@ -2094,6 +2219,7 @@ mod tests { requests: server_requests.clone(), mediation_failures: server_failures.clone(), mediation_ready: true, + provider_environment_generation: 0, }; tokio::spawn(async move { tonic::transport::Server::builder() @@ -2147,6 +2273,7 @@ mod tests { requests, mediation_failures: Arc::new(std::sync::atomic::AtomicUsize::new(0)), mediation_ready: false, + provider_environment_generation: 0, }; let server = tokio::spawn(async move { let (stream, _) = listener.accept().await.unwrap(); @@ -2319,6 +2446,7 @@ mod tests { requests: Arc::new(std::sync::atomic::AtomicUsize::new(0)), mediation_failures: Arc::new(std::sync::atomic::AtomicUsize::new(0)), mediation_ready: false, + provider_environment_generation: 0, }; tonic::transport::Server::builder() .add_service(IsolationBoundaryServer::new(service)) @@ -2638,6 +2766,7 @@ mod tests { requests: handled.clone(), mediation_failures: Arc::new(std::sync::atomic::AtomicUsize::new(0)), mediation_ready: false, + provider_environment_generation: 0, }; let server = tokio::spawn(async move { loop { @@ -2696,6 +2825,110 @@ mod tests { server.abort(); } + #[tokio::test] + async fn reconstructed_backend_resumes_the_running_boundary_publication_generation() { + let certificate = test_certificate(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let requests = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let service = TestGrpcBoundary { + wait_for_half_close: false, + expected_token: "a".repeat(32), + requests: requests.clone(), + mediation_failures: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + mediation_ready: false, + provider_environment_generation: 50, + }; + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let stream = tokio_rustls::TlsAcceptor::from(certificate.server_config) + .accept(stream) + .await + .unwrap(); + tonic::transport::Server::builder() + .add_service(IsolationBoundaryServer::new(service)) + .serve_with_incoming(tokio_stream::iter([Ok::<_, std::io::Error>(TestTlsIo( + Box::new(stream), + ))])) + .await + .unwrap(); + }); + let credentials = + openshell_core::provider_credentials::ProviderCredentialState::from_child_env_snapshot( + 6, + HashMap::new(), + ); + let context = sandbox(); + let ready = Box::new(RemoteReady { + client: Arc::new(BoundaryClient::new( + tls_runtime_descriptor(address, certificate.client_tls), + test_bearer(&"a".repeat(32)), + )), + agent: context.agent, + policy: context.policy, + sandbox_id: context.sandbox_id, + ca_file_paths: Arc::new(std::sync::Mutex::new(None)), + provider_credentials: credentials.clone(), + }); + let running = ready.start_agent().await.unwrap(); + assert_eq!(requests.load(Ordering::Acquire), 1); + let installed = running + .exec() + .synchronize_provider_environment() + .await + .unwrap(); + assert_eq!( + requests.load(Ordering::Acquire), + 2, + "the first update must advance the returned generation, without rejected catch-up calls" + ); + assert_eq!( + installed.installation_id, + credentials.snapshot().installation_id + ); + assert_eq!(installed.session_id, test_session_id()); + server.abort(); + let _ = server.await; + } + + #[tokio::test] + async fn provider_environment_acknowledges_the_exact_local_snapshot_and_checked_generation() { + let certificate = test_certificate(); + let (address, server) = spawn_tls_boundary(certificate.server_config, "a".repeat(32)).await; + let credentials = + openshell_core::provider_credentials::ProviderCredentialState::from_child_env_snapshot( + 6, + HashMap::new(), + ); + let client = Arc::new(BoundaryClient::new( + tls_runtime_descriptor(address, certificate.client_tls), + test_bearer(&"a".repeat(32)), + )); + let exec = RemoteExec { + client, + provider_credentials: credentials.clone(), + publication_generation: tokio::sync::Mutex::new(0), + }; + let empty = exec.synchronize_provider_environment().await.unwrap(); + credentials + .install_child_env_snapshot(6, HashMap::from([("TOKEN".into(), "restored".into())])); + let repaired = exec.synchronize_provider_environment().await.unwrap(); + assert_eq!(empty.revision, repaired.revision); + assert_ne!(empty.installation_id, repaired.installation_id); + assert_eq!( + repaired.installation_id, + credentials.snapshot().installation_id + ); + assert_eq!(*exec.publication_generation.lock().await, 2); + *exec.publication_generation.lock().await = u64::MAX; + assert!( + exec.synchronize_provider_environment().await.is_err(), + "publication exhaustion must fail before sending another request" + ); + server.abort(); + let _ = server.await; + } + #[tokio::test] async fn tls_tcp_flushes_large_control_requests_before_reading_response() { let certificate = test_certificate(); diff --git a/crates/openshell-sandbox-backend/src/runtime/tests/credential_renewal.rs b/crates/openshell-sandbox-backend/src/runtime/tests/credential_renewal.rs new file mode 100644 index 0000000000..9e82bfe0e1 --- /dev/null +++ b/crates/openshell-sandbox-backend/src/runtime/tests/credential_renewal.rs @@ -0,0 +1,248 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use tokio_stream::StreamExt as _; + +#[derive(Clone)] +struct RenewingGrpcBoundary { + inner: TestGrpcBoundary, + expected_token: Arc>, + failures: Arc, + failure_code: tonic::Code, +} + +#[tonic::async_trait] +impl IsolationBoundary for RenewingGrpcBoundary { + type ExchangeStream = TestGrpcStream; + type MediateStream = TestGrpcStream; + + async fn exchange( + &self, + request: tonic::Request>, + ) -> Result, tonic::Status> { + if self + .failures + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |remaining| { + remaining.checked_sub(1) + }) + .is_ok() + { + return Err(tonic::Status::new( + self.failure_code, + "injected boundary failure", + )); + } + let mut inner = self.inner.clone(); + inner.expected_token = self.expected_token.read().unwrap().clone(); + inner.exchange(request).await + } + + async fn mediate( + &self, + request: tonic::Request>, + ) -> Result, tonic::Status> { + self.exchange(request).await + } +} + +async fn renewing_boundary_client( + failure_code: tonic::Code, +) -> ( + Arc, + RenewingGrpcBoundary, + Arc, + tokio::task::JoinHandle<()>, +) { + let certificate = test_certificate(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let service = RenewingGrpcBoundary { + inner: TestGrpcBoundary { + wait_for_half_close: false, + expected_token: "a".repeat(32), + requests: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + mediation_failures: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + mediation_ready: false, + provider_environment_generation: 0, + }, + expected_token: Arc::new(std::sync::RwLock::new("a".repeat(32))), + failures: Arc::new(std::sync::atomic::AtomicUsize::new(0)), + failure_code, + }; + let server_service = service.clone(); + let server_accepted = accepted.clone(); + let server = tokio::spawn(async move { + // Aborting the fixture also closes every child TLS connection. + let mut connections = tokio::task::JoinSet::new(); + loop { + let (stream, _) = listener.accept().await.unwrap(); + let stream = tokio_rustls::TlsAcceptor::from(certificate.server_config.clone()) + .accept(stream) + .await + .unwrap(); + server_accepted.fetch_add(1, Ordering::AcqRel); + let service = server_service.clone(); + connections.spawn(async move { + tonic::transport::Server::builder() + .add_service(IsolationBoundaryServer::new(service)) + .serve_with_incoming( + tokio_stream::iter([Ok::<_, std::io::Error>(TestTlsIo(Box::new(stream)))]) + .chain(tokio_stream::pending()), + ) + .await + .unwrap(); + }); + } + }); + let client = Arc::new(BoundaryClient::new( + tls_runtime_descriptor(address, certificate.client_tls), + test_bearer(&"a".repeat(32)), + )); + client + .call_idempotent(Request::Attach { + supervisor_instance_id: client.supervisor_instance_id, + policy: Box::new(SandboxPolicyWire::from(sandbox().policy)), + resource_claims: std::collections::BTreeMap::new(), + }) + .await + .unwrap(); + client.call_idempotent(Request::Confirm).await.unwrap(); + (client, service, accepted, server) +} + +#[tokio::test] +async fn same_epoch_renewal_reauthenticates_without_closing_pending_stream() { + let (client, service, accepted, server) = + renewing_boundary_client(tonic::Code::Unavailable).await; + // Authenticate a stream that remains open across both bearer renewals. + let mut pending = client + .open_grpc_stream(GrpcStreamKind::Exchange) + .await + .unwrap(); + for (index, token) in ["b".repeat(32), "c".repeat(32)].into_iter().enumerate() { + *service.expected_token.write().unwrap() = token.clone(); + client + .sandbox_bearer + .update( + SecretJwt::parse(token).unwrap(), + i64::MAX, + openshell_core::jwt::CredentialEpoch::new(1).unwrap(), + ) + .unwrap(); + tokio::time::timeout( + Duration::from_secs(2), + client.ensure_current_credential_connection(), + ) + .await + .expect("renewal must complete") + .unwrap(); + assert_eq!( + service.inner.requests.load(Ordering::Acquire), + 3 + index, + "each renewed bearer must authenticate a Confirm RPC" + ); + assert_eq!( + accepted.load(Ordering::Acquire), + 1, + "renewal must reuse the physical connection" + ); + } + let request = BoundaryClient::prepare_request(Request::Wait { + process_id: "pending".into(), + }) + .unwrap(); + pending + .write_all(&encode_frame(&request).unwrap()) + .await + .unwrap(); + let response = tokio::time::timeout( + Duration::from_secs(2), + crate::boundary_protocol::read_frame_async::<_, ResponseEnvelope>(&mut pending), + ) + .await + .expect("pending stream must survive renewal") + .unwrap(); + assert!(matches!(response.response, Response::Exited { .. })); + server.abort(); +} + +#[tokio::test] +async fn failed_renewal_keeps_authenticated_fingerprint_and_retries() { + for failure_code in [tonic::Code::Unavailable, tonic::Code::PermissionDenied] { + let (client, service, accepted, server) = renewing_boundary_client(failure_code).await; + let original = client.grpc_channel.lock().await.clone().unwrap(); + let renewed_token = "b".repeat(32); + *service.expected_token.write().unwrap() = renewed_token.clone(); + client + .sandbox_bearer + .update( + SecretJwt::parse(renewed_token).unwrap(), + i64::MAX, + openshell_core::jwt::CredentialEpoch::new(1).unwrap(), + ) + .unwrap(); + + // A refused confirmation must remain visible to the monitor, including + // an authentication denial; no fingerprint may suppress its next check. + service.failures.store(1, Ordering::Release); + let result = client.ensure_current_credential_connection().await; + match failure_code { + tonic::Code::PermissionDenied => { + assert!(matches!(result, Err(BackendError::Denied(_)))); + } + _ => assert!(matches!(result, Err(BackendError::Unavailable(_)))), + } + let failed = client.grpc_channel.lock().await.clone().unwrap(); + assert_eq!(failed.bearer_fingerprint, original.bearer_fingerprint); + assert_eq!(failed.generation, original.generation); + assert_eq!(service.inner.requests.load(Ordering::Acquire), 2); + + client.ensure_current_credential_connection().await.unwrap(); + let confirmed = client.grpc_channel.lock().await.clone().unwrap(); + assert_ne!(confirmed.bearer_fingerprint, original.bearer_fingerprint); + assert_eq!(confirmed.generation, original.generation); + assert_eq!(service.inner.requests.load(Ordering::Acquire), 3); + assert_eq!(accepted.load(Ordering::Acquire), 1); + + // The confirmed credential needs no further RPC until it changes. + client.ensure_current_credential_connection().await.unwrap(); + assert_eq!(service.inner.requests.load(Ordering::Acquire), 3); + server.abort(); + } +} + +#[tokio::test] +async fn confirmation_authenticates_captured_bearer_after_slot_changes() { + let (client, service, accepted, server) = + renewing_boundary_client(tonic::Code::Unavailable).await; + let credential = BoundaryCredential::capture(&client.sandbox_bearer).unwrap(); + // Race a later slot update with an already captured confirmation. The peer + // still expects the captured token; rereading the slot would be rejected. + client + .sandbox_bearer + .update( + SecretJwt::parse("b".repeat(32)).unwrap(), + i64::MAX, + openshell_core::jwt::CredentialEpoch::new(1).unwrap(), + ) + .unwrap(); + let channel = client + .grpc_channel + .lock() + .await + .as_ref() + .unwrap() + .channel + .clone(); + let envelope = BoundaryClient::prepare_request(Request::Confirm).unwrap(); + let response = client + .exchange_on_channel(channel, &envelope, &credential) + .await + .unwrap(); + assert!(matches!(response, Response::Confirmed { .. })); + assert_eq!(service.inner.requests.load(Ordering::Acquire), 3); + assert_eq!(accepted.load(Ordering::Acquire), 1); + server.abort(); +} diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 3326570d96..a926074f95 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -1863,10 +1863,10 @@ mod linux { provider_env, ), Request::UpdateProviderEnvironment { - expected_revision, + generation, revision, provider_env, - } => self.update_provider_environment(expected_revision, revision, provider_env), + } => self.update_provider_environment(generation, revision, provider_env), Request::Wait { process_id } => self.wait(&process_id), Request::Signal { process_id, signal } => self.signal(&process_id, signal), Request::Terminate { process_id } => self.terminate(&process_id), @@ -2336,6 +2336,7 @@ mod linux { Response::Started { process_id: process.process_id(), provider_env_revision: process.provider_credentials.snapshot().revision, + provider_env_generation: *lock(&process.provider_environment_generation), } } else { guest_error( @@ -2400,12 +2401,13 @@ mod linux { Response::Started { process_id, provider_env_revision, + provider_env_generation: 0, } } fn update_provider_environment( &self, - expected_revision: u64, + generation: u64, revision: u64, provider_env: std::collections::HashMap, ) -> Response { @@ -2419,14 +2421,34 @@ mod linux { }; process.clone() }; + // The session-scoped publication order is separate from opaque + // provider fingerprints. Holding it through installation prevents + // a delayed request from replacing a newer same-revision repair. + let mut installed_generation = lock(&process.provider_environment_generation); + let current = match process.provider_credentials.child_environment_snapshot() { + Ok(snapshot) => snapshot, + Err(error) => return guest_error(BoundaryErrorKind::Process, error.to_string()), + }; + if generation <= *installed_generation { + return Response::ProviderEnvironmentUpdated { + revision: current.revision, + generation: *installed_generation, + applied: false, + }; + } let revision = match process .provider_credentials - .compare_and_install_child_env_snapshot(expected_revision, revision, provider_env) + .compare_and_install_child_env_snapshot(current.revision, revision, provider_env) { Ok(revision) => revision, Err(error) => return guest_error(BoundaryErrorKind::Process, error.to_string()), }; - Response::ProviderEnvironmentUpdated { revision } + *installed_generation = generation; + Response::ProviderEnvironmentUpdated { + revision, + generation, + applied: true, + } } fn wait(&self, process_id: &str) -> Response { @@ -2699,6 +2721,7 @@ mod linux { attached: Arc, boundary_runtime: Arc, provider_credentials: ProviderCredentialState, + provider_environment_generation: Mutex, } struct ManagedProcessLaunch { @@ -2792,6 +2815,7 @@ mod linux { attached: Arc::new(AtomicBool::new(false)), boundary_runtime, provider_credentials, + provider_environment_generation: Mutex::new(0), }) } @@ -4598,13 +4622,14 @@ mod linux { let Response::Started { process_id, provider_env_revision: 0, + provider_env_generation: 0, } = start() else { panic!("initial start did not succeed"); }; let update = RequestEnvelope::new(Request::UpdateProviderEnvironment { - expected_revision: 0, + generation: 1, revision: 7, provider_env: std::collections::HashMap::from([( "REPLAY_TEST".to_string(), @@ -4614,11 +4639,19 @@ mod linux { .expect("build replayed update"); assert_eq!( boundary.dispatch(update.clone()), - Response::ProviderEnvironmentUpdated { revision: 7 } + Response::ProviderEnvironmentUpdated { + revision: 7, + generation: 1, + applied: true, + } ); assert_eq!( boundary.dispatch(update.clone()), - Response::ProviderEnvironmentUpdated { revision: 7 }, + Response::ProviderEnvironmentUpdated { + revision: 7, + generation: 1, + applied: true, + }, "the same request ID and payload must replay its recorded response" ); let mut changed = RequestEnvelope::new(Request::Terminate { @@ -4662,6 +4695,7 @@ mod linux { Response::Started { process_id: process_id.clone(), provider_env_revision: 7, + provider_env_generation: 1, } ); @@ -4684,9 +4718,44 @@ mod linux { Response::Error { kind, .. } if kind == BoundaryErrorKind::Denied )); + // Failed refresh and recovery can retain the same provider + // fingerprint. Distinct publications must still replace the map, + // while a delayed older clear must never undo the repair. + assert_eq!( + boundary.update_provider_environment(2, 7, std::collections::HashMap::default()), + Response::ProviderEnvironmentUpdated { + revision: 7, + generation: 2, + applied: true + } + ); + assert_eq!( + boundary.update_provider_environment( + 3, + 7, + std::collections::HashMap::from([( + "REPLAY_TEST".to_string(), + "reconnected".to_string() + ),]) + ), + Response::ProviderEnvironmentUpdated { + revision: 7, + generation: 3, + applied: true + } + ); + assert_eq!( + boundary.update_provider_environment(2, 7, std::collections::HashMap::default()), + Response::ProviderEnvironmentUpdated { + revision: 7, + generation: 3, + applied: false + } + ); + let exec_spec = ExecSpecWire { program: "/bin/sh".to_string(), - args: vec!["-c".to_string(), "printf reconnected".to_string()], + args: vec!["-c".to_string(), "printf '%s' \"$REPLAY_TEST\"".to_string()], env: Vec::new(), workdir: None, pty: false, @@ -4869,19 +4938,24 @@ mod linux { Response::Started { process_id: process.process_id(), provider_env_revision: 0, + provider_env_generation: 0, } ); assert_eq!( boundary.update_provider_environment( - 0, + 1, 2, std::collections::HashMap::from([( "ROTATED_TOKEN".to_string(), "refreshed".to_string(), )]), ), - Response::ProviderEnvironmentUpdated { revision: 2 } + Response::ProviderEnvironmentUpdated { + revision: 2, + generation: 1, + applied: true, + } ); assert_eq!( boundary.update_provider_environment( @@ -4892,11 +4966,19 @@ mod linux { "stale".to_string(), )]), ), - Response::ProviderEnvironmentUpdated { revision: 2 } + Response::ProviderEnvironmentUpdated { + revision: 2, + generation: 1, + applied: false, + } ); assert_eq!( boundary.update_provider_environment(2, 1, std::collections::HashMap::new()), - Response::ProviderEnvironmentUpdated { revision: 1 }, + Response::ProviderEnvironmentUpdated { + revision: 1, + generation: 2, + applied: true, + }, "a numerically smaller opaque revision must revoke the environment" ); assert_eq!( @@ -4908,12 +4990,20 @@ mod linux { "out-of-order".to_string(), )]), ), - Response::ProviderEnvironmentUpdated { revision: 1 }, - "a stale expected revision must not overwrite current state" + Response::ProviderEnvironmentUpdated { + revision: 1, + generation: 2, + applied: false, + }, + "a stale publication must not overwrite current state" ); assert_eq!( boundary.update_provider_environment(1, 1, std::collections::HashMap::new()), - Response::ProviderEnvironmentUpdated { revision: 1 }, + Response::ProviderEnvironmentUpdated { + revision: 1, + generation: 2, + applied: false, + }, "a duplicate update must be idempotent" ); @@ -4938,6 +5028,7 @@ mod linux { Response::Started { process_id: process.process_id(), provider_env_revision: 1, + provider_env_generation: 2, }, "a replacement control must resume from the boundary's current revision" ); diff --git a/crates/openshell-sandbox/src/managed_children.rs b/crates/openshell-sandbox/src/managed_children.rs index 28b02bd946..d224176e97 100644 --- a/crates/openshell-sandbox/src/managed_children.rs +++ b/crates/openshell-sandbox/src/managed_children.rs @@ -166,6 +166,101 @@ fn direct_child_pids() -> io::Result> { #[cfg(test)] mod tests { use super::*; + use nix::sys::wait::{Id, WaitPidFlag, WaitStatus, waitid, waitpid}; + use nix::unistd::Pid; + use std::process::Command; + use std::sync::mpsc; + use std::time::Duration; + + #[test] + fn fast_child_remains_waitable_after_orphan_reap_attempt() { + let mut registry = lock(); + let mut child = Command::new("sh") + .args(["-c", "exit 11"]) + .spawn() + .expect("spawn fast child"); + let child_pid = child.id(); + let managed_child = registry.register(child_pid).expect("register fast child"); + drop(registry); + let pid = Pid::from_raw(i32::try_from(child_pid).unwrap()); + + // Observe the completed child without consuming its status, exactly + // as the orphan reaper does before its managed-PID check. + loop { + match waitid( + Id::Pid(pid), + WaitPidFlag::WEXITED | WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT, + ) { + Ok(WaitStatus::StillAlive) => std::thread::yield_now(), + Ok(_) => break, + Err(error) => panic!("observe fast child: {error}"), + } + } + + let registry = lock(); + let reaped = if registry.contains(pid.as_raw()) { + None + } else { + Some(waitpid(pid, Some(WaitPidFlag::WNOHANG))) + }; + drop(registry); + assert!( + reaped.is_none(), + "the orphan reaper must leave a registered child to its explicit waiter" + ); + + let wait = child.wait(); + unregister(managed_child); + assert!( + wait.is_ok(), + "the explicit child waiter must retain the exit status" + ); + } + + #[test] + fn reaper_cannot_steal_child_while_registration_is_in_progress() { + // Keep the logical spawn paused before its PID is registered. This is + // the exact window that previously let the orphan reaper consume a + // fast child's status. + let pid = 1_000_002_u32; + let (spawn_entered_tx, spawn_entered_rx) = mpsc::channel(); + let (complete_spawn_tx, complete_spawn_rx) = mpsc::channel(); + let (registered_tx, registered_rx) = mpsc::channel(); + let (reap_attempted_tx, reap_attempted_rx) = mpsc::channel(); + let (reap_result_tx, reap_result_rx) = mpsc::channel(); + + let spawn = std::thread::spawn(move || { + let mut registry = lock(); + spawn_entered_tx.send(()).unwrap(); + complete_spawn_rx.recv().unwrap(); + let managed_child = registry.register(pid).expect("register child"); + assert!(registered_tx.send(managed_child).is_ok()); + }); + spawn_entered_rx.recv().unwrap(); + + let reaper = std::thread::spawn(move || { + reap_attempted_tx.send(()).unwrap(); + let registry = lock(); + reap_result_tx + .send(registry.contains(i32::try_from(pid).unwrap())) + .unwrap(); + }); + reap_attempted_rx.recv().unwrap(); + + assert!( + reap_result_rx + .recv_timeout(Duration::from_millis(50)) + .is_err(), + "the reaper must wait until the child is registered" + ); + + complete_spawn_tx.send(()).unwrap(); + let managed_child = registered_rx.recv().unwrap(); + spawn.join().unwrap(); + assert!(reap_result_rx.recv().unwrap()); + reaper.join().unwrap(); + unregister(managed_child); + } #[test] fn stale_unregister_preserves_reused_pid_registration() { @@ -182,7 +277,7 @@ mod tests { #[test] fn child_pid_parser_observes_a_live_child() { - let mut child = std::process::Command::new("sleep") + let mut child = Command::new("sleep") .arg("30") .spawn() .expect("spawn child"); diff --git a/crates/openshell-sdk/README.md b/crates/openshell-sdk/README.md index 5f889f61f0..3758338dfc 100644 --- a/crates/openshell-sdk/README.md +++ b/crates/openshell-sdk/README.md @@ -130,6 +130,40 @@ let _sandbox = client # } ``` +## Wait for a provider change + +Provider attach, detach, and update responses include a `ProviderMutationReceipt`: a saved record identifying the exact change requested for one sandbox. Pass that record to `provider_readiness::wait_for_provider` to wait until the current sandbox runtime confirms it applied the change. Detach completes with `Revoked`; attach and update complete with `Ready`. + +```rust +use std::time::Duration; +use openshell_sdk::{OpenShellClient, raw::ProviderMutationReceipt}; +use openshell_sdk::provider_readiness::{ + ProviderWaitOutcome, wait_for_provider, +}; + +async fn wait_for_change( + client: &OpenShellClient, + change: &ProviderMutationReceipt, +) -> Result<(), Box> { + let mut grpc = client.raw_grpc_fresh().await?; + let result = wait_for_provider(&mut grpc, change, Duration::from_secs(30)).await?; + match result.outcome { + ProviderWaitOutcome::Complete => println!("The sandbox applied the change."), + ProviderWaitOutcome::TimedOut => println!("Still waiting; check the same change again."), + ProviderWaitOutcome::Terminal => println!("The change failed, was withheld, or was replaced."), + } + Ok(()) +} +``` + +The result preserves the last known status when the deadline expires. A later change cannot satisfy a wait for the original request. `provider_status` queries once, and `wait_for_provider_until` accepts a shared deadline for waiting on the sandboxes selected by one provider update. Status responses contain configuration identities and safe reason categories, without credentials or raw installation errors. + +For ordinary static credentials, launch a new client after update readiness to receive the updated reference. Existing processes keep their revision-scoped references; a successful wait does not retarget them or prove that the old upstream key can be retired. After detach completes, retained references cannot resolve and new processes do not receive them. + +The status's `operation` field is the common operation's historical outcome, keyed by the receipt ID. These helpers complete from the live provider state and its matching evidence; a historical applied operation cannot override a disconnected, expired, or superseded live result. + +These helpers use the raw client's authentication slot. They do not perform OIDC refresh themselves. Follow the raw-client refresh guidance above if a request returns `Unauthenticated`, then resume waiting for the same change ID. + ## Modules | Module | Purpose | @@ -145,6 +179,7 @@ let _sandbox = client | `pagination` | Lazy `Pager` and response `Page`. | | `types` | Curated request/response types and proto conversions. | | `raw` | Escape hatch re-exporting the generated tonic clients. | +| `provider_readiness` | Check and wait for an exact provider change to take effect. | ## Notes diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 47f30dfe67..473f34d625 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -170,6 +170,7 @@ impl OpenShellClient { let response = self .unary(|mut grpc| { let request = proto::CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(template.clone()), workspace_scope: Some(proto::workspace_selector("default")), }; @@ -282,6 +283,7 @@ impl OpenShellClient { let response = self .unary(|mut grpc| { let request = proto::DeleteSandboxTemplateRequest { + request_id: String::new(), allow_missing: opts.allow_missing, name: name.to_string(), workspace_scope: Some(proto::workspace_selector("default")), @@ -354,6 +356,7 @@ impl OpenShellClient { let response = self .unary(|mut grpc| { let request = proto::DeleteSandboxRequest { + request_id: String::new(), allow_missing: opts.allow_missing, name: name.to_string(), workspace_scope: Some(proto::workspace_selector("default")), @@ -372,6 +375,7 @@ impl OpenShellClient { let response = self .unary(|mut grpc| { let request = proto::StopSandboxRequest { + request_id: String::new(), name: name.to_string(), workspace_scope: Some(proto::workspace_selector("default")), }; @@ -386,6 +390,7 @@ impl OpenShellClient { let response = self .unary(|mut grpc| { let request = proto::StartSandboxRequest { + request_id: String::new(), name: name.to_string(), workspace_scope: Some(proto::workspace_selector("default")), }; @@ -509,6 +514,7 @@ impl OpenShellClient { let response = self .unary(|mut grpc| { let request = proto::CreateWorkspaceRequest { + request_id: String::new(), name: name.to_string(), labels: labels.clone(), }; @@ -582,6 +588,7 @@ impl OpenShellClient { let response = self .unary(|mut grpc| { let request = proto::DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: opts.allow_missing, name: name.to_string(), }; @@ -796,6 +803,7 @@ impl WorkspaceScopedClient { .client .unary(|mut grpc| { let request = proto::CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(template.clone()), workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; @@ -871,6 +879,7 @@ impl WorkspaceScopedClient { .client .unary(|mut grpc| { let request = proto::DeleteSandboxTemplateRequest { + request_id: String::new(), allow_missing: opts.allow_missing, name: name.to_string(), workspace_scope: Some(proto::workspace_selector(&self.workspace)), @@ -944,6 +953,7 @@ impl WorkspaceScopedClient { .client .unary(|mut grpc| { let request = proto::DeleteSandboxRequest { + request_id: String::new(), allow_missing: opts.allow_missing, name: name.to_string(), workspace_scope: Some(proto::workspace_selector(&self.workspace)), @@ -963,6 +973,7 @@ impl WorkspaceScopedClient { .client .unary(|mut grpc| { let request = proto::StopSandboxRequest { + request_id: String::new(), name: name.to_string(), workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; @@ -978,6 +989,7 @@ impl WorkspaceScopedClient { .client .unary(|mut grpc| { let request = proto::StartSandboxRequest { + request_id: String::new(), name: name.to_string(), workspace_scope: Some(proto::workspace_selector(&self.workspace)), }; @@ -1175,6 +1187,7 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { gpu: Some(proto::GpuResourceRequirements { count: None }), }); proto::CreateSandboxRequest { + request_id: String::new(), spec: Some(proto::SandboxSpec { environment, template, @@ -1206,6 +1219,7 @@ fn create_sandbox_from_template_request( policy, } = spec; proto::CreateSandboxRequest { + request_id: String::new(), spec: Some(proto::SandboxSpec { providers, command, diff --git a/crates/openshell-sdk/src/lib.rs b/crates/openshell-sdk/src/lib.rs index e12e1cad8a..78f7375f8b 100644 --- a/crates/openshell-sdk/src/lib.rs +++ b/crates/openshell-sdk/src/lib.rs @@ -37,6 +37,7 @@ pub mod edge_tunnel; pub mod error; pub mod oidc; pub mod pagination; +pub mod provider_readiness; pub mod raw; pub mod refresh; pub mod transport; diff --git a/crates/openshell-sdk/src/provider_readiness.rs b/crates/openshell-sdk/src/provider_readiness.rs new file mode 100644 index 0000000000..e11f3c8977 --- /dev/null +++ b/crates/openshell-sdk/src/provider_readiness.rs @@ -0,0 +1,841 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Receipt-bound provider status and bounded waits over the raw provider API. +//! +//! A wait pins the original desired identity. It cannot succeed by following a +//! later mutation, and its deadline covers RPC execution as well as polling. + +use crate::raw::GrpcClient; +use openshell_core::proto::{ + GetSandboxProviderStatusRequest, ProviderMutationKind, ProviderMutationReceipt, + ProviderReadinessReason, ProviderReadinessState, ProviderReadinessStatus, +}; +use std::future::Future; +use std::time::Duration; +use thiserror::Error; +use tokio::time::Instant; +use tonic::service::Interceptor; +use tonic::service::interceptor::InterceptedService; +use tonic::transport::Channel; + +/// Maximum duration accepted by provider waits. +pub const MAX_PROVIDER_WAIT: Duration = Duration::from_hours(1); + +/// Completion of a bounded wait, separate from the gateway's installed state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProviderWaitOutcome { + /// The original receipt's authority was installed or revoked as requested. + Complete, + /// The deadline elapsed; the last observed state remains authoritative. + TimedOut, + /// Installation failed, was withheld, or the desired authority was superseded. + Terminal, +} + +/// Last safe status and the reason a provider wait returned. +#[derive(Clone, Debug)] +pub struct ProviderWaitResult { + /// Status for the original receipt, including on timeout. + pub status: ProviderReadinessStatus, + /// Whether installation completed, failed, or exhausted the deadline. + pub outcome: ProviderWaitOutcome, +} + +/// Errors safe to display without including raw secret-bearing RPC messages. +#[derive(Clone, Debug, Error)] +pub enum ProviderReadinessError { + /// Provider waits require a positive timeout of at most one hour. + #[error("provider wait timeout must be greater than zero and at most 3600 seconds")] + InvalidTimeout, + /// A receipt must identify a sandbox, workspace, provider, and desired state. + #[error("provider readiness receipt is incomplete")] + InvalidReceipt, + /// The gateway returned no usable status or an unknown protocol state. + #[error("gateway returned an invalid provider readiness status")] + InvalidStatus, + /// The RPC failed; only its protocol code is exposed. + #[error("provider readiness request failed ({code})")] + Rpc { + /// gRPC status code without the server's diagnostic message or metadata. + code: tonic::Code, + }, +} + +/// Query a provider receipt or reconstruct current state when its ID is empty. +/// A receipt ID selects its provider when the request omits the provider name. +/// +/// # Errors +/// Returns a safe protocol error if the gateway is unavailable or omits status. +pub async fn provider_status( + client: &mut GrpcClient>, + request: GetSandboxProviderStatusRequest, +) -> Result +where + I: Interceptor + Clone + Send + Sync, +{ + let expected = request.clone(); + let status = client + .get_sandbox_provider_status(request) + .await + .map_err(|error| ProviderReadinessError::Rpc { code: error.code() })? + .into_inner() + .status + .ok_or(ProviderReadinessError::InvalidStatus)?; + validate_status_for_request(&status, &expected)?; + Ok(status) +} + +fn validate_status_for_request( + status: &ProviderReadinessStatus, + expected: &GetSandboxProviderStatusRequest, +) -> Result<(), ProviderReadinessError> { + validate_status(status)?; + let receipt = status + .receipt + .as_ref() + .ok_or(ProviderReadinessError::InvalidStatus)?; + // Either a receipt ID or a provider name must select the authority. Every + // supplied selector must still bind the response to that authority. + if (expected.receipt_id.is_empty() && expected.provider_name.is_empty()) + || (!expected.receipt_id.is_empty() && receipt.receipt_id != expected.receipt_id) + || (!expected.provider_name.is_empty() && receipt.provider_name != expected.provider_name) + || expected.workspace_scope.as_ref().is_some_and(|scope| { + !matches!( + scope.selection.as_ref(), + Some(openshell_core::proto::workspace_selector::Selection::Workspace(workspace)) + if workspace == &receipt.workspace + ) + }) + || receipt + .desired + .as_ref() + .is_none_or(|desired| desired.sandbox_name != expected.sandbox_name) + { + return Err(ProviderReadinessError::InvalidStatus); + } + Ok(()) +} + +/// Wait for the exact authority named by a provider receipt. +/// +/// Detach requires `REVOKED`; attach and update require `READY`. A reconstructed +/// observation waits for ready or revoked according to its original provider ID. +/// This raw helper uses the authentication slot on the supplied client. +/// +/// # Errors +/// Rejects an invalid timeout/receipt, malformed responses, or failed RPCs. +pub async fn wait_for_provider( + client: &mut GrpcClient>, + receipt: &ProviderMutationReceipt, + timeout: Duration, +) -> Result +where + I: Interceptor + Clone + Send + Sync, +{ + let deadline = provider_wait_deadline(timeout)?; + wait_for_provider_until(client, receipt, deadline).await +} + +/// Wait using a shared deadline, so a multi-sandbox update has one total bound. +/// +/// # Errors +/// Returns safe protocol errors without retaining the underlying RPC message. +pub async fn wait_for_provider_until( + client: &mut GrpcClient>, + receipt: &ProviderMutationReceipt, + deadline: Instant, +) -> Result +where + I: Interceptor + Clone + Send + Sync, +{ + wait_with(receipt, deadline, Duration::from_millis(250), |request| { + let mut client = client.clone(); + async move { provider_status(&mut client, request).await } + }) + .await +} + +/// Continue a bounded wait from a status that has already been observed. +/// +/// Completed observations return immediately. A later failed or timed-out RPC +/// cannot discard the last observed pending state and replace it with saved intent. +/// +/// # Errors +/// Rejects malformed receipts/statuses and reports only safe protocol errors. +pub async fn wait_for_provider_status_until( + client: &mut GrpcClient>, + status: &ProviderReadinessStatus, + deadline: Instant, +) -> Result +where + I: Interceptor + Clone + Send + Sync, +{ + let receipt = status + .receipt + .as_ref() + .ok_or(ProviderReadinessError::InvalidStatus)?; + wait_with_initial_status( + receipt, + status.clone(), + deadline, + Duration::from_millis(250), + |request| { + let mut client = client.clone(); + async move { provider_status(&mut client, request).await } + }, + ) + .await +} + +/// Validate a timeout and create a deadline shared across all selected sandboxes. +/// +/// # Errors +/// A zero timeout or a timeout over one hour is rejected before mutation. +pub fn provider_wait_deadline(timeout: Duration) -> Result { + if timeout.is_zero() || timeout > MAX_PROVIDER_WAIT { + return Err(ProviderReadinessError::InvalidTimeout); + } + Ok(Instant::now() + timeout) +} + +/// Represent saved intent before any runtime observation has been fetched. +#[must_use] +pub fn persisted_status(receipt: ProviderMutationReceipt) -> ProviderReadinessStatus { + ProviderReadinessStatus { + receipt: Some(receipt), + state: ProviderReadinessState::Persisted.into(), + reason: ProviderReadinessReason::WaitingForSupervisor.into(), + ..Default::default() + } +} + +fn validate_status(status: &ProviderReadinessStatus) -> Result<(), ProviderReadinessError> { + if status.receipt.is_none() + || matches!( + ProviderReadinessState::try_from(status.state), + Err(_) | Ok(ProviderReadinessState::Unspecified) + ) + || ProviderReadinessReason::try_from(status.reason).is_err() + { + return Err(ProviderReadinessError::InvalidStatus); + } + // Absent observation times are expected before a report arrives. Present + // times must be canonical so output cannot normalize malformed timestamps. + for timestamp in [&status.observed_time, &status.evaluated_time] + .into_iter() + .flatten() + { + openshell_core::time::validate_timestamp(timestamp) + .map_err(|_| ProviderReadinessError::InvalidStatus)?; + } + let receipt = status + .receipt + .as_ref() + .ok_or(ProviderReadinessError::InvalidStatus)?; + validate_provider_receipt(receipt).map_err(|_| ProviderReadinessError::InvalidStatus)?; + let state = ProviderReadinessState::try_from(status.state) + .map_err(|_| ProviderReadinessError::InvalidStatus)?; + if matches!( + state, + ProviderReadinessState::Ready | ProviderReadinessState::Revoked + ) { + if state != completion_state(receipt).map_err(|_| ProviderReadinessError::InvalidStatus)? { + return Err(ProviderReadinessError::InvalidStatus); + } + // A status read has the same installation contract as a wait. Enum + // labels alone must never report ready or revoked to a direct caller. + validate_completion(status)?; + } + Ok(()) +} + +fn completion_state( + receipt: &ProviderMutationReceipt, +) -> Result { + let desired = receipt + .desired + .as_ref() + .ok_or(ProviderReadinessError::InvalidReceipt)?; + let attached = !desired.provider_id.is_empty(); + match ProviderMutationKind::try_from(receipt.kind) { + Ok(ProviderMutationKind::Attach | ProviderMutationKind::Update) if attached => { + Ok(ProviderReadinessState::Ready) + } + Ok(ProviderMutationKind::Detach) if !attached => Ok(ProviderReadinessState::Revoked), + Ok(ProviderMutationKind::Observe) => Ok(if attached { + ProviderReadinessState::Ready + } else { + ProviderReadinessState::Revoked + }), + _ => Err(ProviderReadinessError::InvalidReceipt), + } +} + +/// Validate saved receipt identity without fetching a runtime observation. +/// +/// Initial attachment epochs may be empty and revision fingerprints may be zero; +/// the mutation kind must still agree with the presence of a provider identity. +/// +/// # Errors +/// Rejects incomplete receipts, invalid persistence timestamps, and inconsistent +/// mutation/provider identities. +pub fn validate_provider_receipt( + receipt: &ProviderMutationReceipt, +) -> Result<(), ProviderReadinessError> { + let desired = receipt + .desired + .as_ref() + .ok_or(ProviderReadinessError::InvalidReceipt)?; + let persisted_time = receipt + .persisted_time + .as_ref() + .ok_or(ProviderReadinessError::InvalidReceipt)?; + openshell_core::time::validate_timestamp(persisted_time) + .map_err(|_| ProviderReadinessError::InvalidReceipt)?; + if receipt.receipt_id.is_empty() + || receipt.mutation_id.is_empty() + || desired.sandbox_id.is_empty() + || desired.sandbox_name.is_empty() + || receipt.provider_name.is_empty() + || receipt.workspace.is_empty() + || matches!( + ProviderMutationKind::try_from(receipt.kind), + Err(_) | Ok(ProviderMutationKind::Unspecified) + ) + { + return Err(ProviderReadinessError::InvalidReceipt); + } + completion_state(receipt)?; + Ok(()) +} + +fn request_for_receipt( + receipt: &ProviderMutationReceipt, +) -> Result { + validate_provider_receipt(receipt)?; + let desired = receipt + .desired + .as_ref() + .ok_or(ProviderReadinessError::InvalidReceipt)?; + Ok(GetSandboxProviderStatusRequest { + sandbox_name: desired.sandbox_name.clone(), + provider_name: receipt.provider_name.clone(), + receipt_id: receipt.receipt_id.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector( + &receipt.workspace, + )), + }) +} + +fn disposition( + receipt: &ProviderMutationReceipt, + status: &mut ProviderReadinessStatus, +) -> Result, ProviderReadinessError> { + validate_status(status)?; + let observed_receipt = status + .receipt + .as_ref() + .ok_or(ProviderReadinessError::InvalidStatus)?; + // Status reconstruction creates an immutable observation receipt too. The + // full receipt must remain fixed; a later snapshot cannot move this target. + if observed_receipt.desired != receipt.desired + || observed_receipt.provider_name != receipt.provider_name + || observed_receipt.workspace != receipt.workspace + || (!receipt.receipt_id.is_empty() + && (observed_receipt.receipt_id != receipt.receipt_id + || observed_receipt.mutation_id != receipt.mutation_id + || observed_receipt.kind != receipt.kind + || observed_receipt.persisted_time != receipt.persisted_time)) + { + status.receipt = Some(receipt.clone()); + status.state = ProviderReadinessState::Superseded.into(); + status.reason = ProviderReadinessReason::DesiredStateChanged.into(); + return Ok(Some(ProviderWaitOutcome::Terminal)); + } + let state = ProviderReadinessState::try_from(status.state) + .map_err(|_| ProviderReadinessError::InvalidStatus)?; + let revoked = completion_state(receipt)? == ProviderReadinessState::Revoked; + match state { + ProviderReadinessState::Ready if !revoked => { + validate_completion(status)?; + Ok(Some(ProviderWaitOutcome::Complete)) + } + ProviderReadinessState::Revoked if revoked => { + validate_completion(status)?; + Ok(Some(ProviderWaitOutcome::Complete)) + } + ProviderReadinessState::Withheld + | ProviderReadinessState::Failed + | ProviderReadinessState::Superseded => Ok(Some(ProviderWaitOutcome::Terminal)), + ProviderReadinessState::Ready | ProviderReadinessState::Revoked => { + Err(ProviderReadinessError::InvalidStatus) + } + _ => Ok(None), + } +} + +fn validate_completion(status: &ProviderReadinessStatus) -> Result<(), ProviderReadinessError> { + let desired = status + .receipt + .as_ref() + .and_then(|receipt| receipt.desired.as_ref()) + .ok_or(ProviderReadinessError::InvalidStatus)?; + let observed = status + .observed + .as_ref() + .ok_or(ProviderReadinessError::InvalidStatus)?; + if desired.policy_hash.is_empty() + || status.network_instance_id.is_empty() + || observed.session_id.is_empty() + || observed.process_instance_id.is_empty() + || !observed.credentials_installed + || !observed.policy_active + || !observed.launch_environment_installed + || observed.reason != i32::from(ProviderReadinessReason::Unspecified) + || status.reason != i32::from(ProviderReadinessReason::Unspecified) + || observed.attachment_epoch != desired.attachment_epoch + || observed.provider_env_revision != desired.provider_env_revision + || observed.config_revision != desired.config_revision + || observed.policy_hash != desired.policy_hash + { + return Err(ProviderReadinessError::InvalidStatus); + } + Ok(()) +} + +async fn wait_with( + receipt: &ProviderMutationReceipt, + deadline: Instant, + interval: Duration, + fetch: F, +) -> Result +where + F: FnMut(GetSandboxProviderStatusRequest) -> Fut, + Fut: Future>, +{ + wait_with_initial_status( + receipt, + persisted_status(receipt.clone()), + deadline, + interval, + fetch, + ) + .await +} + +async fn wait_with_initial_status( + receipt: &ProviderMutationReceipt, + mut last: ProviderReadinessStatus, + deadline: Instant, + interval: Duration, + mut fetch: F, +) -> Result +where + F: FnMut(GetSandboxProviderStatusRequest) -> Fut, + Fut: Future>, +{ + let request = request_for_receipt(receipt)?; + if let Some(outcome) = disposition(receipt, &mut last)? { + return Ok(ProviderWaitResult { + status: last, + outcome, + }); + } + loop { + if Instant::now() >= deadline { + return Ok(ProviderWaitResult { + status: last, + outcome: ProviderWaitOutcome::TimedOut, + }); + } + // The timeout also cancels an RPC that never responds; sleeping alone + // between polls cannot enforce a bounded wait against an unavailable peer. + match tokio::time::timeout_at(deadline, fetch(request.clone())).await { + Ok(result) => last = result?, + Err(_) => { + return Ok(ProviderWaitResult { + status: last, + outcome: ProviderWaitOutcome::TimedOut, + }); + } + } + if let Some(outcome) = disposition(receipt, &mut last)? { + return Ok(ProviderWaitResult { + status: last, + outcome, + }); + } + tokio::time::sleep_until((Instant::now() + interval).min(deadline)).await; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::ProviderDesiredIdentity; + + fn receipt(kind: ProviderMutationKind) -> ProviderMutationReceipt { + ProviderMutationReceipt { + receipt_id: "receipt".into(), + mutation_id: "mutation".into(), + provider_name: "provider".into(), + workspace: "default".into(), + persisted_time: Some(openshell_core::time::timestamp_from_millis(1).unwrap()), + kind: kind.into(), + desired: Some(ProviderDesiredIdentity { + sandbox_id: "sandbox-id".into(), + sandbox_name: "sandbox".into(), + provider_id: if kind == ProviderMutationKind::Detach { + String::new() + } else { + "provider-id".into() + }, + attachment_epoch: "attachment-epoch".into(), + policy_hash: "policy-hash".into(), + provider_env_revision: u64::MAX, + ..Default::default() + }), + } + } + + fn completed_status( + receipt: &ProviderMutationReceipt, + state: ProviderReadinessState, + ) -> ProviderReadinessStatus { + let desired = receipt.desired.as_ref().unwrap(); + ProviderReadinessStatus { + receipt: Some(receipt.clone()), + state: state.into(), + network_instance_id: "network-instance".into(), + observed: Some(openshell_core::proto::ProviderReadinessObservation { + session_id: "session".into(), + process_instance_id: "process-instance".into(), + attachment_epoch: desired.attachment_epoch.clone(), + provider_env_revision: desired.provider_env_revision, + config_revision: desired.config_revision, + policy_hash: desired.policy_hash.clone(), + credentials_installed: true, + policy_active: true, + launch_environment_installed: true, + ..Default::default() + }), + ..Default::default() + } + } + + #[test] + fn receipt_requires_a_present_canonical_persistence_time() { + let mut receipt = receipt(ProviderMutationKind::Attach); + for (seconds, nanos, valid) in [ + (0, 1, true), + (0, 0, true), + (-1, 999_999_999, true), + (1, -1, false), + (1, 1_000_000_000, false), + (253_402_300_800, 0, false), + (-62_135_596_801, 0, false), + ] { + let timestamp = receipt.persisted_time.as_mut().unwrap(); + timestamp.seconds = seconds; + timestamp.nanos = nanos; + assert_eq!( + validate_provider_receipt(&receipt).is_ok(), + valid, + "seconds={seconds}, nanos={nanos}" + ); + } + receipt.persisted_time = None; + assert!(matches!( + validate_provider_receipt(&receipt), + Err(ProviderReadinessError::InvalidReceipt) + )); + } + + #[test] + fn changed_persistence_nanoseconds_supersede_the_original_receipt() { + let receipt = receipt(ProviderMutationKind::Attach); + let mut changed = receipt.clone(); + changed.persisted_time.as_mut().unwrap().nanos += 1; + let mut status = completed_status(&changed, ProviderReadinessState::Ready); + assert_eq!( + disposition(&receipt, &mut status).unwrap(), + Some(ProviderWaitOutcome::Terminal) + ); + assert_eq!(status.state, i32::from(ProviderReadinessState::Superseded)); + assert_eq!(status.receipt.as_ref(), Some(&receipt)); + } + + #[test] + fn status_rejects_malformed_observation_and_evaluation_times() { + let receipt = receipt(ProviderMutationKind::Attach); + let mut malformed = openshell_core::time::timestamp_from_millis(1).unwrap(); + malformed.nanos = -1; + for observation in [true, false] { + let mut status = completed_status(&receipt, ProviderReadinessState::Ready); + if observation { + status.observed_time = Some(malformed); + } else { + status.evaluated_time = Some(malformed); + } + assert!(matches!( + validate_status(&status), + Err(ProviderReadinessError::InvalidStatus) + )); + } + } + + #[test] + fn direct_status_accepts_receipt_only_and_explicit_provider_selectors() { + let receipt = receipt(ProviderMutationKind::Attach); + let status = completed_status(&receipt, ProviderReadinessState::Ready); + let mut request = GetSandboxProviderStatusRequest { + sandbox_name: "sandbox".into(), + receipt_id: receipt.receipt_id.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }; + assert!(validate_status_for_request(&status, &request).is_ok()); + + request.provider_name = receipt.provider_name; + assert!(validate_status_for_request(&status, &request).is_ok()); + + request.receipt_id.clear(); + assert!(validate_status_for_request(&status, &request).is_ok()); + } + + #[test] + fn direct_status_rejects_mismatched_explicit_selectors() { + let receipt = receipt(ProviderMutationKind::Attach); + let status = completed_status(&receipt, ProviderReadinessState::Ready); + let request = GetSandboxProviderStatusRequest { + sandbox_name: "sandbox".into(), + receipt_id: receipt.receipt_id, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }; + for invalid in [ + GetSandboxProviderStatusRequest { + receipt_id: String::new(), + ..request.clone() + }, + GetSandboxProviderStatusRequest { + provider_name: "other-provider".into(), + ..request.clone() + }, + GetSandboxProviderStatusRequest { + receipt_id: "other-receipt".into(), + ..request.clone() + }, + GetSandboxProviderStatusRequest { + sandbox_name: "other-sandbox".into(), + ..request.clone() + }, + GetSandboxProviderStatusRequest { + workspace_scope: Some(openshell_core::proto::workspace_selector("other-workspace")), + ..request + }, + ] { + assert!(matches!( + validate_status_for_request(&status, &invalid), + Err(ProviderReadinessError::InvalidStatus) + )); + } + } + + #[tokio::test] + async fn pending_process_waits_until_exact_receipt_is_ready() { + let receipt = receipt(ProviderMutationKind::Attach); + let mut calls = 0; + let result = wait_with( + &receipt, + Instant::now() + Duration::from_secs(1), + Duration::ZERO, + |_| { + calls += 1; + let mut status = completed_status(&receipt, ProviderReadinessState::Ready); + status.state = if calls == 1 { + ProviderReadinessState::Pending + } else { + ProviderReadinessState::Ready + } + .into(); + status.reason = if calls == 1 { + ProviderReadinessReason::WaitingForProcess + } else { + ProviderReadinessReason::Unspecified + } + .into(); + async { Ok(status) } + }, + ) + .await + .unwrap(); + assert_eq!(calls, 2); + assert_eq!(result.outcome, ProviderWaitOutcome::Complete); + } + + #[tokio::test] + async fn deadline_bounds_a_hung_status_rpc() { + let receipt = receipt(ProviderMutationKind::Update); + let result = wait_with( + &receipt, + Instant::now() + Duration::from_millis(10), + Duration::ZERO, + |_| std::future::pending(), + ) + .await + .unwrap(); + assert_eq!(result.outcome, ProviderWaitOutcome::TimedOut); + assert_eq!( + result.status.state, + i32::from(ProviderReadinessState::Persisted) + ); + } + + #[test] + fn different_authority_is_superseded_even_with_a_smaller_fingerprint() { + let receipt = receipt(ProviderMutationKind::Update); + let mut newer_receipt = receipt.clone(); + newer_receipt + .desired + .as_mut() + .unwrap() + .provider_env_revision = 1; + let mut status = completed_status(&newer_receipt, ProviderReadinessState::Ready); + assert_eq!( + disposition(&receipt, &mut status).unwrap(), + Some(ProviderWaitOutcome::Terminal) + ); + assert_eq!(status.state, i32::from(ProviderReadinessState::Superseded)); + } + + #[test] + fn detach_requires_revocation_and_installation_failure_is_terminal() { + let receipt = receipt(ProviderMutationKind::Detach); + let mut status = completed_status(&receipt, ProviderReadinessState::Ready); + assert!(disposition(&receipt, &mut status).is_err()); + status.state = ProviderReadinessState::Revoked.into(); + assert_eq!( + disposition(&receipt, &mut status).unwrap(), + Some(ProviderWaitOutcome::Complete) + ); + status.state = ProviderReadinessState::Failed.into(); + status.reason = ProviderReadinessReason::CredentialInstallFailed.into(); + assert_eq!( + disposition(&receipt, &mut status).unwrap(), + Some(ProviderWaitOutcome::Terminal) + ); + } + + #[test] + fn initial_empty_epoch_requires_a_complete_policy_identity() { + let mut receipt = receipt(ProviderMutationKind::Observe); + receipt.desired.as_mut().unwrap().attachment_epoch.clear(); + let mut status = completed_status(&receipt, ProviderReadinessState::Ready); + assert_eq!( + disposition(&receipt, &mut status).unwrap(), + Some(ProviderWaitOutcome::Complete) + ); + + receipt.desired.as_mut().unwrap().policy_hash.clear(); + let mut status = completed_status(&receipt, ProviderReadinessState::Ready); + assert!(disposition(&receipt, &mut status).is_err()); + } + + #[test] + fn direct_status_rejects_missing_installation_and_inconsistent_authority() { + let attached = receipt(ProviderMutationKind::Attach); + let mut status = completed_status(&attached, ProviderReadinessState::Ready); + status + .observed + .as_mut() + .unwrap() + .launch_environment_installed = false; + assert!(validate_status(&status).is_err()); + + let mut missing_provider = attached; + missing_provider + .desired + .as_mut() + .unwrap() + .provider_id + .clear(); + assert!( + validate_status(&completed_status( + &missing_provider, + ProviderReadinessState::Ready + )) + .is_err() + ); + + let mut detach = receipt(ProviderMutationKind::Detach); + detach.desired.as_mut().unwrap().provider_id = "still-attached".into(); + assert!( + validate_status(&completed_status(&detach, ProviderReadinessState::Revoked)).is_err() + ); + + let mut observe = receipt(ProviderMutationKind::Observe); + observe.desired.as_mut().unwrap().provider_id.clear(); + assert!( + validate_status(&completed_status(&observe, ProviderReadinessState::Revoked)).is_ok() + ); + } + + #[tokio::test] + async fn initial_completed_status_returns_without_another_rpc() { + let receipt = receipt(ProviderMutationKind::Attach); + let status = completed_status(&receipt, ProviderReadinessState::Ready); + let result = wait_with_initial_status( + &receipt, + status, + Instant::now() + Duration::from_millis(10), + Duration::ZERO, + |_| std::future::pending(), + ) + .await + .unwrap(); + assert_eq!(result.outcome, ProviderWaitOutcome::Complete); + } + + #[tokio::test] + async fn initial_pending_status_survives_a_hung_followup_rpc() { + let receipt = receipt(ProviderMutationKind::Attach); + let mut status = persisted_status(receipt.clone()); + status.state = ProviderReadinessState::Pending.into(); + status.reason = ProviderReadinessReason::WaitingForProcess.into(); + let result = wait_with_initial_status( + &receipt, + status.clone(), + Instant::now() + Duration::from_millis(10), + Duration::ZERO, + |_| std::future::pending(), + ) + .await + .unwrap(); + assert_eq!(result.outcome, ProviderWaitOutcome::TimedOut); + assert_eq!(result.status, status); + } + + #[test] + fn rejects_unbounded_waits_and_unknown_states() { + assert!(provider_wait_deadline(Duration::ZERO).is_err()); + assert!(provider_wait_deadline(MAX_PROVIDER_WAIT + Duration::from_secs(1)).is_err()); + let receipt = receipt(ProviderMutationKind::Attach); + let mut status = persisted_status(receipt.clone()); + status.state = 99; + assert!(disposition(&receipt, &mut status).is_err()); + } + + #[test] + fn claimed_ready_without_process_acknowledgment_is_invalid() { + let receipt = receipt(ProviderMutationKind::Attach); + let mut status = completed_status(&receipt, ProviderReadinessState::Ready); + status + .observed + .as_mut() + .unwrap() + .launch_environment_installed = false; + assert!(disposition(&receipt, &mut status).is_err()); + } +} diff --git a/crates/openshell-sdk/src/raw.rs b/crates/openshell-sdk/src/raw.rs index 3b1bb6605a..dd3b7b165b 100644 --- a/crates/openshell-sdk/src/raw.rs +++ b/crates/openshell-sdk/src/raw.rs @@ -23,13 +23,16 @@ pub use openshell_core::proto::open_shell_client::OpenShellClient as GrpcClient; pub use openshell_core::proto::{ CreateSandboxRequest, CreateSandboxTemplateRequest, CreateWorkspaceRequest, DeleteSandboxRequest, DeleteSandboxTemplateRequest, DeleteWorkspaceRequest, ExecSandboxRequest, - GetSandboxRequest, GetSandboxTemplateRequest, GetWorkspaceRequest, HealthRequest, - ListProvidersRequest, ListSandboxTemplatesRequest, ListSandboxesRequest, ListWorkspacesRequest, - Sandbox, SandboxPhase as ProtoSandboxPhase, SandboxResources, SandboxServiceLevel, - SandboxSpec as ProtoSandboxSpec, SandboxStartup, SandboxTemplate, SandboxTemplateResponse, - SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, - SandboxWorkloadTemplateSpec, ServiceStatus as ProtoServiceStatus, StartSandboxRequest, - StopSandboxRequest, Workspace, + GetSandboxProviderStatusRequest, GetSandboxProviderStatusResponse, GetSandboxRequest, + GetSandboxTemplateRequest, GetWorkspaceRequest, HealthRequest, ListProvidersRequest, + ListSandboxTemplatesRequest, ListSandboxesRequest, ListWorkspacesRequest, + ProviderDesiredIdentity, ProviderMutationKind, ProviderMutationReceipt, + ProviderReadinessObservation, ProviderReadinessReason, ProviderReadinessState, + ProviderReadinessStatus, Sandbox, SandboxPhase as ProtoSandboxPhase, SandboxResources, + SandboxServiceLevel, SandboxSpec as ProtoSandboxSpec, SandboxStartup, SandboxTemplate, + SandboxTemplateResponse, SandboxWorkloadConfig, SandboxWorkloadTemplate, + SandboxWorkloadTemplateProvenance, SandboxWorkloadTemplateSpec, + ServiceStatus as ProtoServiceStatus, StartSandboxRequest, StopSandboxRequest, Workspace, }; /// Type alias for the gRPC client wrapped in the SDK's auth interceptor. diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 2cbe200335..f2fc52b5ff 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -708,6 +708,24 @@ impl OpenShell for TestOpenShell { Err(Status::unimplemented("unused")) } + async fn get_sandbox_provider_status( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider readiness is not exercised by this mock", + )) + } + + async fn report_provider_readiness( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider installation reports are not exercised by this mock", + )) + } + async fn get_sandbox_provider_environment( &self, _: tonic::Request, diff --git a/crates/openshell-server/proto/storage.proto b/crates/openshell-server/proto/storage.proto index 7c1d7dce0c..28e9e9e4a1 100644 --- a/crates/openshell-server/proto/storage.proto +++ b/crates/openshell-server/proto/storage.proto @@ -9,6 +9,7 @@ package openshell.storage.v1; import "datamodel.proto"; import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; import "openshell.proto"; import "options.proto"; import "sandbox.proto"; @@ -108,6 +109,31 @@ message StoredProviderProfile { openshell.v1.ProviderProfile profile = 2; } +// Durable, non-secret progress for a sandbox-scoped desired-state mutation. +// The target_* fields let a recovery worker bind the exact effective snapshot +// revision after the desired-state transaction commits. +message StoredConfigUpdateOperation { + openshell.datamodel.v1.ObjectMeta metadata = 1; + openshell.v1.ConfigUpdateOperation operation = 2; + uint32 target_policy_version = 3; + uint64 target_settings_revision = 4; + openshell.v1.SandboxPhase initial_phase = 5; + string idempotency_key = 6; + uint32 attempt_count = 7; + reserved 8; + reserved "next_attempt_at_ms"; + google.protobuf.Timestamp next_attempt_time = 108; + uint32 response_policy_version = 9; + string response_policy_hash = 10; + uint64 response_settings_revision = 11; + bool response_deleted = 12; + map response_annotations = 13; + // Immutable provider mutation intent associated with this operation. + openshell.v1.ProviderMutationReceipt provider_receipt = 14; + // Closed reason captured when resolving the operation's provider snapshot. + openshell.v1.ProviderReadinessReason provider_snapshot_reason = 15; +} + // Stored payload for a policy revision row in the generic objects table. message PolicyRevisionPayload { // Serialized policy contents. diff --git a/crates/openshell-server/src/config_update_operation.rs b/crates/openshell-server/src/config_update_operation.rs new file mode 100644 index 0000000000..2588bdf6b4 --- /dev/null +++ b/crates/openshell-server/src/config_update_operation.rs @@ -0,0 +1,763 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Durable, exact-target configuration operations, independent of delivery transport. +//! +//! Provider receipts project the common operation resource. Live installation +//! evidence remains session-bound; an applied operation records historical +//! completion and never substitutes for a fresh provider readiness evaluation. + +#![allow(clippy::result_large_err)] // Internal operation helpers preserve gRPC error details. + +use std::collections::HashMap; + +use openshell_core::proto::{ + ConfigApplyOutcome, ConfigComponent, ConfigSnapshotRevision, ConfigUpdateOperation, + ConfigUpdateOperationState, ObjectMeta, ProviderMutationKind, ProviderMutationReceipt, + ProviderReadinessReason, ProviderReadinessState, ProviderReadinessStatus, + config_snapshot_revision, +}; +use openshell_core::rpc_error::{self, ErrorDetails, StatusExt}; +use prost::Message; +use sha2::{Digest, Sha256}; +use tonic::{Code, Status}; + +use crate::persistence::{ObjectRecord, ObjectType, PersistenceError, Store, WriteCondition}; +use crate::storage_proto::StoredConfigUpdateOperation; + +/// Object-store namespace shared by configuration completion resources. +pub const CONFIG_UPDATE_OPERATION_OBJECT_TYPE: &str = "config_update_operation"; +const MAX_TRANSITION_RETRIES: usize = 8; + +impl ObjectType for StoredConfigUpdateOperation { + fn object_type() -> &'static str { + CONFIG_UPDATE_OPERATION_OBJECT_TYPE + } +} + +/// Provider-specific view of one common configuration operation. +#[derive(Clone, Debug)] +pub struct ProviderOperation { + /// Immutable desired authority captured for this operation. + pub(crate) receipt: ProviderMutationReceipt, + /// A failed initial snapshot is never reconstructed into another target. + pub(crate) snapshot_reason: ProviderReadinessReason, + /// Durable historical outcome; callers must separately evaluate live readiness. + pub(crate) operation: ConfigUpdateOperation, +} + +fn storage_unavailable() -> Status { + // A provider mutation can already have committed when operation persistence + // fails. No retry hint is attached: repeating the mutation is not proven safe. + Status::with_error_details( + Code::Unavailable, + "configuration operation storage unavailable; the saved mutation may remain in effect", + ErrorDetails::with_error_info( + "CONFIG_OPERATION_STORAGE_UNCERTAIN", + rpc_error::ERROR_DOMAIN, + HashMap::new(), + ), + ) +} + +fn invalid_record() -> Status { + Status::with_error_details( + Code::Internal, + "configuration operation identity is inconsistent", + ErrorDetails::with_error_info( + "CONFIG_OPERATION_INVALID", + rpc_error::ERROR_DOMAIN, + HashMap::new(), + ), + ) +} + +fn persisted_time(receipt: &ProviderMutationReceipt) -> Result { + // Receipt identity includes the full canonical timestamp. Absence is not + // the Unix epoch, and reducing nanos to milliseconds would merge identities. + let timestamp = receipt.persisted_time.ok_or_else(invalid_record)?; + openshell_core::time::validate_timestamp(×tamp).map_err(|_| invalid_record())?; + Ok(timestamp) +} + +fn observation_id( + receipt: &ProviderMutationReceipt, + snapshot_reason: ProviderReadinessReason, +) -> Result { + let desired = receipt.desired.as_ref().ok_or_else(invalid_record)?; + let mut digest = Sha256::new(); + digest.update(b"openshell/provider-observation/v1\0"); + let target_bytes = desired.encode_to_vec(); + // The target contains only public identity and opaque revision fields. Its + // protobuf has no maps, so encoding is canonical. Length framing prevents + // component concatenation ambiguities across workspaces and provider names. + for component in [ + receipt.workspace.as_bytes(), + receipt.provider_name.as_bytes(), + target_bytes.as_slice(), + ] { + let length = u64::try_from(component.len()).map_err(|_| invalid_record())?; + digest.update(length.to_be_bytes()); + digest.update(component); + } + // A failed capture and its later successful repair are different targets; + // the original failed operation must remain immutable. + digest.update((snapshot_reason as i32).to_be_bytes()); + let mut bytes = [0_u8; 16]; + for (byte, hashed) in bytes.iter_mut().zip(digest.finalize()) { + *byte = hashed; + } + Ok(uuid::Builder::from_custom_bytes(bytes) + .into_uuid() + .to_string()) +} + +/// Record an exact provider target in the shared configuration-operation store. +/// +/// The caller captures the snapshot only after its provider mutation finishes. +/// This write does not roll back a preceding mutation on failure. An incomplete +/// snapshot is persisted as failed, retaining its original non-secret reason. +/// Observation-only requests reuse the original receipt for the same complete +/// target; source mutations retain their distinct caller-created receipt IDs. +pub async fn record_provider_operation( + store: &Store, + mut receipt: ProviderMutationReceipt, + snapshot_reason: ProviderReadinessReason, +) -> Result { + let observation = receipt.kind == ProviderMutationKind::Observe as i32; + if observation { + receipt.receipt_id = observation_id(&receipt, snapshot_reason)?; + } + let desired = receipt.desired.as_ref().ok_or_else(invalid_record)?; + if receipt.receipt_id.is_empty() + || receipt.workspace.is_empty() + || desired.sandbox_id.is_empty() + { + return Err(invalid_record()); + } + let persisted_time = persisted_time(&receipt)?; + let failed = snapshot_reason != ProviderReadinessReason::Unspecified; + let operation = ConfigUpdateOperation { + operation_id: receipt.receipt_id.clone(), + sandbox_id: desired.sandbox_id.clone(), + component: ConfigComponent::ProviderEnvironment.into(), + target_revision: Some(ConfigSnapshotRevision { + component: Some(config_snapshot_revision::Component::ProviderTarget( + desired.clone(), + )), + }), + state: if failed { + ConfigUpdateOperationState::Failed.into() + } else { + ConfigUpdateOperationState::Pending.into() + }, + outcome: if failed { + ConfigApplyOutcome::FailedClosed.into() + } else { + ConfigApplyOutcome::Unspecified.into() + }, + sanitized_error: if failed { + snapshot_reason.as_str_name().to_string() + } else { + String::new() + }, + created_time: Some(persisted_time), + updated_time: Some(persisted_time), + completed_time: failed.then_some(persisted_time), + }; + let stored = StoredConfigUpdateOperation { + metadata: Some(ObjectMeta { + id: receipt.receipt_id.clone(), + name: receipt.receipt_id.clone(), + workspace: receipt.workspace.clone(), + created_time: Some(persisted_time), + ..Default::default() + }), + operation: Some(operation), + provider_receipt: Some(receipt.clone()), + provider_snapshot_reason: snapshot_reason.into(), + ..Default::default() + }; + let result = store + .put_if( + CONFIG_UPDATE_OPERATION_OBJECT_TYPE, + &receipt.receipt_id, + &receipt.receipt_id, + &receipt.workspace, + &stored.encode_to_vec(), + None, + WriteCondition::MustCreate, + ) + .await; + match result { + Ok(_) => Ok(receipt), + Err(PersistenceError::UniqueViolation { .. }) if observation => { + // Concurrent observers race only on the insert. A conflict never + // updates the winner's timestamp, mutation identity, or outcome. + // Exact comparison also fails closed on an ID collision/corruption. + let existing = + get_provider_operation(store, &receipt.receipt_id, &receipt.workspace).await?; + if existing.receipt.kind != receipt.kind + || existing.receipt.provider_name != receipt.provider_name + || existing.receipt.desired != receipt.desired + || existing.snapshot_reason != snapshot_reason + { + return Err(invalid_record()); + } + Ok(existing.receipt) + } + Err(_) => Err(storage_unavailable()), + } +} + +// The record ID, receipt ID, and operation ID deliberately name the same +// durable identity; their distinct schema field names must compare equal. +#[allow(clippy::suspicious_operation_groupings)] +fn decode_provider_operation( + record: &ObjectRecord, +) -> Result<(StoredConfigUpdateOperation, ProviderOperation), Status> { + let stored = StoredConfigUpdateOperation::decode(record.payload.as_slice()) + .map_err(|_| invalid_record())?; + let receipt = stored + .provider_receipt + .as_ref() + .ok_or_else(invalid_record)?; + let operation = stored.operation.as_ref().ok_or_else(invalid_record)?; + let metadata = stored.metadata.as_ref().ok_or_else(invalid_record)?; + let desired = receipt.desired.as_ref().ok_or_else(invalid_record)?; + let persisted_time = persisted_time(receipt)?; + let snapshot_reason = ProviderReadinessReason::try_from(stored.provider_snapshot_reason) + .map_err(|_| invalid_record())?; + if record.id != receipt.receipt_id + || record.workspace != receipt.workspace + || metadata.id != record.id + || metadata.workspace != record.workspace + || operation.operation_id != record.id + || operation.sandbox_id != desired.sandbox_id + || operation.created_time != Some(persisted_time) + || metadata.created_time != Some(persisted_time) + || operation.component != ConfigComponent::ProviderEnvironment as i32 + || operation + .target_revision + .as_ref() + .and_then(|revision| revision.component.as_ref()) + != Some(&config_snapshot_revision::Component::ProviderTarget( + desired.clone(), + )) + || ConfigUpdateOperationState::try_from(operation.state).is_err() + { + return Err(invalid_record()); + } + let provider = ProviderOperation { + receipt: receipt.clone(), + snapshot_reason, + operation: operation.clone(), + }; + Ok((stored, provider)) +} + +async fn load_provider_operation( + store: &Store, + operation_id: &str, + workspace: &str, +) -> Result<(ObjectRecord, StoredConfigUpdateOperation, ProviderOperation), Status> { + let record = store + .get(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, operation_id) + .await + .map_err(|_| storage_unavailable())? + .filter(|record| record.workspace == workspace) + .ok_or_else(|| Status::not_found("provider operation not found"))?; + let (stored, provider) = decode_provider_operation(&record)?; + Ok((record, stored, provider)) +} + +/// Read a provider projection after the RPC has authorized the workspace. +/// +/// Looking up an operation from a different workspace returns the same result +/// as a missing operation and never reveals its receipt or desired target. +pub async fn get_provider_operation( + store: &Store, + operation_id: &str, + workspace: &str, +) -> Result { + let (_, _, provider) = load_provider_operation(store, operation_id, workspace).await?; + Ok(provider) +} + +fn terminal(state: ConfigUpdateOperationState) -> bool { + matches!( + state, + ConfigUpdateOperationState::Applied + | ConfigUpdateOperationState::Inactive + | ConfigUpdateOperationState::Failed + | ConfigUpdateOperationState::Superseded + | ConfigUpdateOperationState::Cancelled + ) +} + +fn completion( + status: &ProviderReadinessStatus, +) -> Result, Status> { + match ProviderReadinessState::try_from(status.state).map_err(|_| invalid_record())? { + ProviderReadinessState::Ready | ProviderReadinessState::Revoked => { + let desired = status + .receipt + .as_ref() + .and_then(|receipt| receipt.desired.as_ref()) + .ok_or_else(invalid_record)?; + let observed = status.observed.as_ref().ok_or_else(invalid_record)?; + // The RPC validates current session ownership and freshness. Check + // the complete target again before converting its result into a + // durable terminal transition; a partial install is never applied. + if status.reason != ProviderReadinessReason::Unspecified as i32 + || observed.reason != ProviderReadinessReason::Unspecified as i32 + || observed.attachment_epoch != desired.attachment_epoch + || observed.provider_env_revision != desired.provider_env_revision + || observed.config_revision != desired.config_revision + || observed.policy_hash != desired.policy_hash + || !observed.credentials_installed + || !observed.policy_active + || !observed.launch_environment_installed + || observed.process_instance_id.is_empty() + || observed.session_id.is_empty() + || status.network_instance_id.is_empty() + || (status.state == ProviderReadinessState::Revoked as i32) + != desired.provider_id.is_empty() + { + return Err(invalid_record()); + } + Ok(Some(( + ConfigUpdateOperationState::Applied, + ConfigApplyOutcome::Applied, + ))) + } + ProviderReadinessState::Superseded => Ok(Some(( + ConfigUpdateOperationState::Superseded, + ConfigApplyOutcome::IgnoredStale, + ))), + // Live installation failures can recover without changing the desired + // revision. They remain visible in the provider projection but do not + // terminate the operation or authorize a retry of the source mutation. + _ => Ok(None), + } +} + +/// Persist exact completion by CAS and attach its historical resource to a view. +/// +/// Call only after evaluating authenticated current-session evidence. The live +/// status is never changed by this function: expired or superseded evidence +/// cannot become ready because an earlier observation was durably applied. +pub async fn observe_provider_status( + store: &Store, + status: &mut ProviderReadinessStatus, +) -> Result<(), Status> { + let receipt = status.receipt.as_ref().ok_or_else(invalid_record)?.clone(); + let completion = completion(status)?; + for _ in 0..MAX_TRANSITION_RETRIES { + let (record, mut stored, provider) = + load_provider_operation(store, &receipt.receipt_id, &receipt.workspace).await?; + if provider.receipt != receipt { + return Err(invalid_record()); + } + let state = ConfigUpdateOperationState::try_from(provider.operation.state) + .map_err(|_| invalid_record())?; + let Some((terminal_state, outcome)) = completion.filter(|_| !terminal(state)) else { + status.operation = Some(provider.operation); + return Ok(()); + }; + // Capturing the desired snapshot failed permanently for this operation. + // A later read must not fabricate a different, successful target. + if provider.snapshot_reason != ProviderReadinessReason::Unspecified { + return Err(invalid_record()); + } + let operation = stored.operation.as_mut().ok_or_else(invalid_record)?; + operation.state = terminal_state.into(); + operation.outcome = outcome.into(); + operation.sanitized_error = if terminal_state == ConfigUpdateOperationState::Superseded { + ProviderReadinessReason::DesiredStateChanged + .as_str_name() + .to_string() + } else { + String::new() + }; + let completed_time = + openshell_core::time::timestamp_from_system_time(std::time::SystemTime::now()) + .map_err(|error| { + Status::internal(format!("create operation completion timestamp: {error}")) + })?; + operation.updated_time = Some(completed_time); + operation.completed_time = Some(completed_time); + let result = store + .put_if( + CONFIG_UPDATE_OPERATION_OBJECT_TYPE, + &record.id, + &record.name, + &record.workspace, + &stored.encode_to_vec(), + record.labels.as_deref(), + WriteCondition::MatchResourceVersion(record.resource_version), + ) + .await; + match result { + Ok(_) => { + status.operation = stored.operation; + return Ok(()); + } + // A competing observer may have completed this operation. Reload + // the authoritative row; a terminal outcome is immutable. + Err(PersistenceError::Conflict { .. }) => {} + Err(_) => return Err(storage_unavailable()), + } + } + Err(rpc_error::resource_version_conflict( + "configuration operation changed concurrently; query its status again", + None, + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::proto::{ + ProviderDesiredIdentity, ProviderMutationKind, ProviderReadinessObservation, + }; + use uuid::Uuid; + + fn receipt() -> ProviderMutationReceipt { + ProviderMutationReceipt { + receipt_id: Uuid::new_v4().to_string(), + mutation_id: Uuid::new_v4().to_string(), + provider_name: "provider".to_string(), + workspace: "default".to_string(), + kind: ProviderMutationKind::Update.into(), + desired: Some(ProviderDesiredIdentity { + sandbox_id: Uuid::new_v4().to_string(), + sandbox_name: "sandbox".to_string(), + attachment_epoch: Uuid::new_v4().to_string(), + provider_id: Uuid::new_v4().to_string(), + provider_resource_version: 3, + provider_env_revision: 5, + config_revision: 7, + policy_hash: "policy".to_string(), + }), + persisted_time: Some(prost_types::Timestamp { + seconds: 1_700_000_000, + nanos: 123_456_789, + }), + } + } + + fn ready(receipt: &ProviderMutationReceipt) -> ProviderReadinessStatus { + let desired = receipt.desired.as_ref().unwrap(); + ProviderReadinessStatus { + receipt: Some(receipt.clone()), + state: ProviderReadinessState::Ready.into(), + network_instance_id: Uuid::new_v4().to_string(), + observed: Some(ProviderReadinessObservation { + session_id: Uuid::new_v4().to_string(), + sequence: 1, + attachment_epoch: desired.attachment_epoch.clone(), + provider_env_revision: desired.provider_env_revision, + config_revision: desired.config_revision, + policy_hash: desired.policy_hash.clone(), + credentials_installed: true, + policy_active: true, + launch_environment_installed: true, + process_instance_id: Uuid::new_v4().to_string(), + reason: ProviderReadinessReason::Unspecified.into(), + }), + ..Default::default() + } + } + + #[tokio::test] + async fn provider_receipt_uses_the_common_operation_namespace_and_exact_target() { + let store = crate::persistence::test_store().await; + let receipt = receipt(); + record_provider_operation( + &store, + receipt.clone(), + ProviderReadinessReason::Unspecified, + ) + .await + .unwrap(); + let operation = get_provider_operation(&store, &receipt.receipt_id, "default") + .await + .unwrap(); + assert_eq!(operation.receipt, receipt); + assert_eq!(operation.operation.operation_id, receipt.receipt_id); + assert_eq!(operation.operation.created_time, receipt.persisted_time); + assert_eq!(operation.operation.updated_time, receipt.persisted_time); + assert!(operation.operation.completed_time.is_none()); + assert_eq!( + operation.operation.state, + ConfigUpdateOperationState::Pending as i32 + ); + assert!( + store + .get("provider_mutation_receipt", &receipt.receipt_id) + .await + .unwrap() + .is_none() + ); + assert_eq!( + get_provider_operation(&store, &receipt.receipt_id, "other") + .await + .unwrap_err() + .code(), + Code::NotFound + ); + } + + #[tokio::test] + async fn incomplete_provider_target_stays_failed_after_later_installation() { + let store = crate::persistence::test_store().await; + let receipt = receipt(); + record_provider_operation( + &store, + receipt.clone(), + ProviderReadinessReason::SnapshotMismatch, + ) + .await + .unwrap(); + let mut status = ready(&receipt); + observe_provider_status(&store, &mut status).await.unwrap(); + let operation = status.operation.unwrap(); + assert_eq!(operation.state, ConfigUpdateOperationState::Failed as i32); + assert_eq!(operation.completed_time, receipt.persisted_time); + } + + #[tokio::test] + async fn receipt_timestamp_requires_presence_and_canonical_nanos() { + let store = crate::persistence::test_store().await; + for invalid_time in [ + None, + Some(prost_types::Timestamp { + seconds: 0, + nanos: -1, + }), + Some(prost_types::Timestamp { + seconds: openshell_core::time::MAX_TIMESTAMP_SECONDS + 1, + nanos: 0, + }), + ] { + let mut receipt = receipt(); + receipt.persisted_time = invalid_time; + let error = + record_provider_operation(&store, receipt, ProviderReadinessReason::Unspecified) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Internal); + } + assert_eq!( + store + .count_in_workspace(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, "default") + .await + .unwrap(), + 0 + ); + + // The Unix epoch is a valid explicit timestamp, not missing data. + let mut epoch = receipt(); + epoch.persisted_time = Some(prost_types::Timestamp::default()); + let recorded = + record_provider_operation(&store, epoch.clone(), ProviderReadinessReason::Unspecified) + .await + .unwrap(); + assert_eq!(recorded, epoch); + assert_eq!( + get_provider_operation(&store, &epoch.receipt_id, "default") + .await + .unwrap() + .receipt, + epoch + ); + } + + #[tokio::test] + async fn receipt_timestamp_nanos_are_part_of_exact_completion_identity() { + let store = crate::persistence::test_store().await; + let receipt = receipt(); + record_provider_operation( + &store, + receipt.clone(), + ProviderReadinessReason::Unspecified, + ) + .await + .unwrap(); + let mut changed = ready(&receipt); + changed + .receipt + .as_mut() + .unwrap() + .persisted_time + .as_mut() + .unwrap() + .nanos += 1; + assert_eq!( + observe_provider_status(&store, &mut changed) + .await + .unwrap_err() + .code(), + Code::Internal + ); + let stored = get_provider_operation(&store, &receipt.receipt_id, "default") + .await + .unwrap(); + assert_eq!(stored.receipt, receipt); + assert_eq!( + stored.operation.state, + ConfigUpdateOperationState::Pending as i32 + ); + assert!(stored.operation.completed_time.is_none()); + + let mut exact = ready(&receipt); + observe_provider_status(&store, &mut exact).await.unwrap(); + let completed = exact.operation.unwrap(); + assert_eq!(completed.created_time, receipt.persisted_time); + assert!(completed.completed_time.is_some()); + assert_eq!(completed.updated_time, completed.completed_time); + openshell_core::time::validate_timestamp(completed.completed_time.as_ref().unwrap()) + .unwrap(); + } + + #[tokio::test] + async fn stale_or_partial_provider_evidence_cannot_complete_an_operation() { + let store = crate::persistence::test_store().await; + let receipt = receipt(); + record_provider_operation( + &store, + receipt.clone(), + ProviderReadinessReason::Unspecified, + ) + .await + .unwrap(); + let mut stale = ready(&receipt); + stale.observed.as_mut().unwrap().config_revision += 1; + assert!(observe_provider_status(&store, &mut stale).await.is_err()); + let mut partial = ready(&receipt); + partial + .observed + .as_mut() + .unwrap() + .launch_environment_installed = false; + assert!(observe_provider_status(&store, &mut partial).await.is_err()); + assert_eq!( + get_provider_operation(&store, &receipt.receipt_id, "default") + .await + .unwrap() + .operation + .state, + ConfigUpdateOperationState::Pending as i32 + ); + } + + #[tokio::test] + async fn applied_history_never_upgrades_an_expired_live_view() { + let store = crate::persistence::test_store().await; + let receipt = receipt(); + record_provider_operation( + &store, + receipt.clone(), + ProviderReadinessReason::Unspecified, + ) + .await + .unwrap(); + let mut status = ready(&receipt); + observe_provider_status(&store, &mut status).await.unwrap(); + let before = store + .get(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, &receipt.receipt_id) + .await + .unwrap() + .unwrap(); + status.state = ProviderReadinessState::Pending.into(); + status.reason = ProviderReadinessReason::SupervisorLeaseExpired.into(); + observe_provider_status(&store, &mut status).await.unwrap(); + assert_eq!(status.state, ProviderReadinessState::Pending as i32); + assert_eq!( + status.operation.unwrap().state, + ConfigUpdateOperationState::Applied as i32 + ); + let after = store + .get(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, &receipt.receipt_id) + .await + .unwrap() + .unwrap(); + assert_eq!(before.resource_version, after.resource_version); + } + + #[tokio::test] + async fn competing_terminal_observers_preserve_the_first_committed_outcome() { + let store = crate::persistence::test_store().await; + let receipt = receipt(); + record_provider_operation( + &store, + receipt.clone(), + ProviderReadinessReason::Unspecified, + ) + .await + .unwrap(); + let mut applied = ready(&receipt); + let mut superseded = applied.clone(); + superseded.state = ProviderReadinessState::Superseded.into(); + superseded.reason = ProviderReadinessReason::DesiredStateChanged.into(); + let (first, second) = tokio::join!( + observe_provider_status(&store, &mut applied), + observe_provider_status(&store, &mut superseded), + ); + first.unwrap(); + second.unwrap(); + assert_eq!(applied.operation, superseded.operation); + let stored = get_provider_operation(&store, &receipt.receipt_id, "default") + .await + .unwrap(); + assert!(matches!( + ConfigUpdateOperationState::try_from(stored.operation.state).unwrap(), + ConfigUpdateOperationState::Applied | ConfigUpdateOperationState::Superseded + )); + } + + #[tokio::test] + async fn failed_observation_and_recovered_snapshot_have_distinct_immutable_receipts() { + let store = crate::persistence::test_store().await; + let mut observed = receipt(); + observed.kind = ProviderMutationKind::Observe.into(); + let failed = record_provider_operation( + &store, + observed.clone(), + ProviderReadinessReason::CredentialsWithheld, + ) + .await + .unwrap(); + observed.mutation_id = Uuid::new_v4().to_string(); + observed.persisted_time.as_mut().unwrap().nanos += 1; + let repeated = record_provider_operation( + &store, + observed.clone(), + ProviderReadinessReason::CredentialsWithheld, + ) + .await + .unwrap(); + assert_eq!(repeated, failed); + let repaired = + record_provider_operation(&store, observed, ProviderReadinessReason::Unspecified) + .await + .unwrap(); + assert_ne!(repaired.receipt_id, failed.receipt_id); + assert_eq!( + get_provider_operation(&store, &failed.receipt_id, "default") + .await + .unwrap() + .operation + .state, + ConfigUpdateOperationState::Failed as i32 + ); + assert_eq!( + store + .count_in_workspace(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, "default") + .await + .unwrap(), + 2 + ); + } +} diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index f66a0a011a..7c089c04bf 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -4,8 +4,10 @@ //! gRPC service implementation. mod auth_rpc; +pub mod mutation_replay; pub mod policy; pub mod provider; +pub mod provider_readiness; mod sandbox; pub use sandbox::mint_persisted_authentication; mod service; @@ -36,7 +38,8 @@ use openshell_core::proto::{ GetProviderRefreshStatusResponse, GetProviderRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxLogsRequest, GetSandboxLogsResponse, GetSandboxPolicyStatusRequest, GetSandboxPolicyStatusResponse, - GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, GetSandboxRequest, + GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, + GetSandboxProviderStatusRequest, GetSandboxProviderStatusResponse, GetSandboxRequest, GetSandboxTemplateRequest, GetServiceRequest, GetWorkspaceRequest, GetWorkspaceResponse, GpuResourceCapabilities, HealthRequest, HealthResponse, ImportProviderProfilesRequest, ImportProviderProfilesResponse, IssueSandboxTokenRequest, IssueSandboxTokenResponse, @@ -51,12 +54,13 @@ use openshell_core::proto::{ RefreshSandboxTokenResponse, RejectDraftChunkRequest, RejectDraftChunkResponse, RelayFrame, RemoveWorkspaceMemberRequest, RemoveWorkspaceMemberResponse, ReportEndpointStatusRequest, ReportEndpointStatusResponse, ReportMainProcessExitRequest, ReportMainProcessExitResponse, - ReportPolicyStatusRequest, ReportPolicyStatusResponse, ResourceCapabilities, - RevokeSshSessionRequest, RevokeSshSessionResponse, RotateProviderCredentialRequest, - RotateProviderCredentialResponse, SandboxResponse, SandboxTemplateResponse, - ServiceEndpointResponse, ServiceStatus, StartSandboxRequest, StopSandboxRequest, - SubmitPolicyAnalysisRequest, SubmitPolicyAnalysisResponse, SupervisorMessage, TcpForwardFrame, - UndoDraftChunkRequest, UndoDraftChunkResponse, UpdateConfigRequest, UpdateConfigResponse, + ReportPolicyStatusRequest, ReportPolicyStatusResponse, ReportProviderReadinessRequest, + ReportProviderReadinessResponse, ResourceCapabilities, RevokeSshSessionRequest, + RevokeSshSessionResponse, RotateProviderCredentialRequest, RotateProviderCredentialResponse, + SandboxResponse, SandboxTemplateResponse, ServiceEndpointResponse, ServiceStatus, + StartSandboxRequest, StopSandboxRequest, SubmitPolicyAnalysisRequest, + SubmitPolicyAnalysisResponse, SupervisorMessage, TcpForwardFrame, UndoDraftChunkRequest, + UndoDraftChunkResponse, UpdateConfigRequest, UpdateConfigResponse, UpdateProviderProfilesRequest, UpdateProviderProfilesResponse, UpdateProviderRequest, WatchSandboxRequest, open_shell_server::OpenShell, }; @@ -266,7 +270,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - sandbox::handle_create_sandbox(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn begin_rootfs_tar_staging( @@ -303,7 +307,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - sandbox::handle_create_sandbox_template(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn get_sandbox_template( @@ -324,7 +328,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - sandbox::handle_delete_sandbox_template(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn list_sandbox_providers( @@ -338,35 +342,49 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - sandbox::handle_attach_sandbox_provider(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn detach_sandbox_provider( &self, request: Request, ) -> Result, Status> { - sandbox::handle_detach_sandbox_provider(&self.state, request).await + mutation_replay::run(&self.state, request).await + } + + async fn get_sandbox_provider_status( + &self, + request: Request, + ) -> Result, Status> { + provider_readiness::handle_get_sandbox_provider_status(&self.state, request).await + } + + async fn report_provider_readiness( + &self, + request: Request, + ) -> Result, Status> { + provider_readiness::handle_report_provider_readiness(&self.state, request).await } async fn delete_sandbox( &self, request: Request, ) -> Result, Status> { - sandbox::handle_delete_sandbox(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn stop_sandbox( &self, request: Request, ) -> Result, Status> { - sandbox::handle_stop_sandbox(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn start_sandbox( &self, request: Request, ) -> Result, Status> { - sandbox::handle_start_sandbox(&self.state, request).await + mutation_replay::run(&self.state, request).await } // --- Exec --- @@ -412,7 +430,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - service::handle_expose_service(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn get_service( @@ -433,7 +451,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - service::handle_delete_service(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn revoke_ssh_session( @@ -449,7 +467,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - provider::handle_create_provider(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn get_provider( @@ -484,14 +502,14 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - provider::handle_import_provider_profiles(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn update_provider_profiles( &self, request: Request, ) -> Result, Status> { - provider::handle_update_provider_profiles(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn lint_provider_profiles( @@ -505,7 +523,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - provider::handle_update_provider(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn get_provider_refresh_status( @@ -519,35 +537,35 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - provider::handle_configure_provider_refresh(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn rotate_provider_credential( &self, request: Request, ) -> Result, Status> { - provider::handle_rotate_provider_credential(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn delete_provider_refresh( &self, request: Request, ) -> Result, Status> { - provider::handle_delete_provider_refresh(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn delete_provider( &self, request: Request, ) -> Result, Status> { - provider::handle_delete_provider(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn delete_provider_profile( &self, request: Request, ) -> Result, Status> { - provider::handle_delete_provider_profile(&self.state, request).await + mutation_replay::run(&self.state, request).await } // --- Config / Policy --- @@ -584,7 +602,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - policy::handle_update_config(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn get_sandbox_policy_status( @@ -651,42 +669,42 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - policy::handle_approve_draft_chunk(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn reject_draft_chunk( &self, request: Request, ) -> Result, Status> { - policy::handle_reject_draft_chunk(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn approve_all_draft_chunks( &self, request: Request, ) -> Result, Status> { - policy::handle_approve_all_draft_chunks(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn edit_draft_chunk( &self, request: Request, ) -> Result, Status> { - policy::handle_edit_draft_chunk(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn undo_draft_chunk( &self, request: Request, ) -> Result, Status> { - policy::handle_undo_draft_chunk(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn clear_draft_chunks( &self, request: Request, ) -> Result, Status> { - policy::handle_clear_draft_chunks(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn get_draft_history( @@ -754,7 +772,7 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - workspace::handle_create_workspace(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn get_workspace( @@ -775,21 +793,21 @@ impl OpenShell for OpenShellService { &self, request: Request, ) -> Result, Status> { - workspace::handle_delete_workspace(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn add_workspace_member( &self, request: Request, ) -> Result, Status> { - workspace::handle_add_workspace_member(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn remove_workspace_member( &self, request: Request, ) -> Result, Status> { - workspace::handle_remove_workspace_member(&self.state, request).await + mutation_replay::run(&self.state, request).await } async fn list_workspace_members( diff --git a/crates/openshell-server/src/grpc/mutation_replay.rs b/crates/openshell-server/src/grpc/mutation_replay.rs new file mode 100644 index 0000000000..34153a9ad8 --- /dev/null +++ b/crates/openshell-server/src/grpc/mutation_replay.rs @@ -0,0 +1,708 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Explicitly opted-in unary mutations. This is an admission fence, not a lease: +//! an owner that cannot persist success leaves an unresolved claim forever. +//! Each adapter explicitly approves its authorization and replay representation. + +#![allow(clippy::result_large_err)] + +use std::collections::BTreeMap; +use std::sync::{Arc, LazyLock}; + +use hmac::{Hmac, Mac}; +use openshell_core::proto::{ + AddWorkspaceMemberRequest, AddWorkspaceMemberResponse, CreateSandboxTemplateRequest, + CreateWorkspaceRequest, CreateWorkspaceResponse, DeleteSandboxTemplateRequest, + DeleteSandboxTemplateResponse, DeleteWorkspaceRequest, DeleteWorkspaceResponse, + RemoveWorkspaceMemberRequest, RemoveWorkspaceMemberResponse, SandboxTemplateResponse, + Workspace, WorkspaceSelector, +}; +use openshell_core::{GetResourceVersion, ObjectId, rpc_error}; +use prost::Message; +use prost_reflect::{DescriptorPool, DynamicMessage}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tokio::sync::Semaphore; +use tonic::{Request, Response, Status}; + +use super::{sandbox, workspace}; +use crate::ServerState; +use crate::auth::identity::IdentityProvider; +use crate::auth::principal::Principal; +use crate::auth::workspace_authz::{ + MinWorkspaceRole, authorize_workspace, authorize_workspace_selector, require_platform_admin, +}; +use crate::persistence::{ + ObjectType, PersistenceError, SetResourceVersion, Store, WriteCondition, current_time_ms, +}; + +const OBJECT_TYPE: &str = "mutation_admission_v1"; +const SUCCESS_TTL_MS: i64 = 24 * 60 * 60 * 1000; +const MAX_ADMISSIONS_PER_CALLER: u32 = 1000; +// Bound work detached from request cancellation across all service instances. +static EXECUTORS: LazyLock> = LazyLock::new(|| Arc::new(Semaphore::new(64))); +static DESCRIPTORS: LazyLock = LazyLock::new(|| { + DescriptorPool::decode(openshell_core::FILE_DESCRIPTOR_SET) + .expect("compiled protobuf descriptor set") +}); + +#[derive(Serialize, Deserialize)] +struct Admission { + // Version the canonicalization separately from the namespace. A future + // change must reject incompatible records, not admit the old key again. + format_version: u32, + payload_hash: String, + #[serde(default)] + protection: Option, + workspace_id: Option, + success: Option, + completed_at_ms: Option, +} + +#[derive(Serialize, Deserialize, PartialEq)] +struct Protection { + key_id: String, + effective_payload_hash: String, + effective_workspace_id: Option, +} + +/// Gateway-owned, in-memory input before hydration and interceptor modification. +/// Never populated from HTTP metadata and never written to the admission store. +#[derive(Clone)] +pub struct OriginalMutation(pub(crate) Vec); + +/// Deliberately no serialized requests, responses, tokens, or error messages. +#[derive(Serialize, Deserialize)] +pub(super) enum Success { + Resource { id: String, version: u64 }, + Deletion { outcome: i32 }, + Ordinary(ordinary::Outcome), +} + +pub(super) struct Scope { + name: String, + workspace_id: Option, +} + +#[tonic::async_trait] +pub(super) trait Mutation: Message + Default + Send + Sync + 'static { + type Output: Message + Default + Send + 'static; + const METHOD: &'static str; + const PROTECTED: bool = false; + fn request_id(&self) -> &str; + async fn authorize(&self, state: &ServerState, principal: &Principal) -> Result; + async fn execute( + state: &Arc, + request: Request, + ) -> Result, Status>; + fn capture(response: &Response) -> Result; + async fn restore(store: &Store, success: Success) -> Result; +} + +/// Empty IDs preserve the existing RPC contract, including cancellation. +pub(super) async fn run( + state: &Arc, + request: Request, +) -> Result, Status> { + let original = request + .extensions() + .get::() + .map(|original| M::decode(original.0.as_slice())) + .transpose() + .map_err(|_| Status::internal("decode original mutation request"))?; + let original = original.as_ref().unwrap_or_else(|| request.get_ref()); + if original.request_id() != request.get_ref().request_id() { + return Err(rpc_error::invalid_argument( + "request_id", + "interceptors must preserve the original request_id", + )); + } + if original.request_id().is_empty() { + return M::execute(state, request).await; + } + if request.get_ref().encoded_len() > 4 * 1024 * 1024 { + return Err(Status::resource_exhausted("mutation request exceeds 4 MiB")); + } + let request_id = validate_request_id(request.get_ref().request_id())?; + let principal = super::extract_principal(&request)?; + let Principal::User(user) = &principal else { + return Err(Status::permission_denied( + "request admission requires a user principal", + )); + }; + let scope = original.authorize(state, &principal).await?; + let effective_scope = request.get_ref().authorize(state, &principal).await?; + let (payload_hash, protection) = if M::PROTECTED { + let key = fingerprint_key(state).await?; + ( + key.fingerprint(original)?, + Some(Protection { + key_id: key.id(), + effective_payload_hash: key.fingerprint(request.get_ref())?, + effective_workspace_id: effective_scope.workspace_id, + }), + ) + } else { + (fingerprint(original)?, None) + }; + let (provider, issuer) = match user.identity.provider { + IdentityProvider::Oidc => ( + "oidc", + state + .config + .oidc + .as_ref() + .map_or("", |config| config.issuer.as_str()), + ), + IdentityProvider::Mtls => ("mtls", ""), + IdentityProvider::CloudflareAccess => ("cloudflare_access", ""), + IdentityProvider::LocalDev => ("local_dev", ""), + }; + let caller = hash_json(&serde_json::json!([ + provider, + issuer, + user.identity.subject, + ]))?; + // Not a valid user workspace name; ordinary workspace cleanup cannot touch + // these records. The bucket supports an atomic per-caller storage quota. + let bucket = format!("_mutation/{caller}"); + let key = hash_json(&serde_json::json!([ + caller, + M::METHOD, + scope.name, + request_id + ]))?; + let permit = EXECUTORS.clone().try_acquire_owned().map_err(|_| { + Status::resource_exhausted( + "mutation admission workers are busy; no work was started by this call", + ) + })?; + let state = Arc::clone(state); + // Spawn BEFORE attempting MustCreate. Cancellation during the database write + // must not drop the owner between durable admission and execution. + tokio::spawn(async move { + let _permit = permit; + execute_owned( + &state, + request, + &key, + &bucket, + payload_hash, + protection, + scope, + ) + .await + }) + .await + .map_err(|_| uncertain())? +} + +async fn execute_owned( + state: &Arc, + mut request: Request, + key: &str, + bucket: &str, + payload_hash: String, + protection: Option, + scope: Scope, +) -> Result, Status> { + let mut admission = Admission { + format_version: 1, + payload_hash, + protection, + workspace_id: scope.workspace_id, + success: None, + completed_at_ms: None, + }; + // Contention is bounded. Losing a race never authorizes execution. + for _ in 0..8 { + if let Some(row) = state + .store + .get_by_name(OBJECT_TYPE, bucket, key) + .await + .map_err(storage_error)? + { + let previous: Admission = serde_json::from_slice(&row.payload) + .map_err(|_| Status::internal("invalid durable mutation admission"))?; + if previous.format_version != 1 { + return Err(replay_unavailable()); + } + if previous.success.is_some() + && previous.completed_at_ms.is_some_and(|completed| { + current_time_ms() >= completed.saturating_add(SUCCESS_TTL_MS) + }) + { + match state + .store + .delete_if(OBJECT_TYPE, &row.id, row.resource_version) + .await + { + Ok(_) | Err(PersistenceError::Conflict { .. }) => continue, + Err(error) => return Err(storage_error(error)), + } + } + // A rotated/unavailable protection key must never turn the old ID + // into a new admission, or report a misleading payload mismatch. + if previous.protection.as_ref().map(|p| &p.key_id) + != admission.protection.as_ref().map(|p| &p.key_id) + { + return Err(replay_unavailable()); + } + if previous.payload_hash != admission.payload_hash { + return Err(rpc_error::failed_precondition( + "REQUEST_ID_PAYLOAD_MISMATCH", + "request_id was already used with a different payload", + )); + } + if previous.workspace_id != admission.workspace_id + || previous.protection != admission.protection + { + return Err(replay_unavailable()); + } + let success = previous.success.ok_or_else(uncertain)?; + let mut response = Response::new(M::restore(&state.store, success).await?); + response.metadata_mut().insert( + "openshell-replayed", + "true".parse().expect("static metadata"), + ); + return Ok(response); + } + let payload = serde_json::to_vec(&admission) + .map_err(|_| Status::internal("encode mutation admission"))?; + // A new incarnation needs a new row ID. Versions reset after deletion; + // an expiry cleaner holding an old snapshot must not delete a new claim. + let claim_id = uuid::Uuid::new_v4().to_string(); + let write = state + .store + .create_if_workspace_count_below( + OBJECT_TYPE, + &claim_id, + key, + bucket, + &payload, + None, + u64::from(MAX_ADMISSIONS_PER_CALLER), + ) + .await; + let version = match write { + Ok(Some(write)) => write.resource_version, + Ok(None) => { + if prune_expired(&state.store, bucket).await? { + continue; + } + return Err(Status::resource_exhausted( + "caller has reached the durable mutation admission limit; unresolved requests require reconciliation", + )); + } + Err(PersistenceError::UniqueViolation { .. } | PersistenceError::Conflict { .. }) => { + continue; + } + Err(error) => return Err(storage_error(error)), + }; + // Any error or panic from here leaves the claim unresolved. Status codes + // do not establish that a handler performed no effects. + let facts = ordinary::Facts::default(); + request.extensions_mut().insert(facts.clone()); + let mut response = M::execute(state, request).await?; + response.extensions_mut().insert(facts); + admission.success = Some(M::capture(&response)?); + admission.completed_at_ms = Some(current_time_ms()); + let payload = serde_json::to_vec(&admission).map_err(|_| uncertain())?; + if payload.len() > 64 * 1024 { + return Err(uncertain()); + } + state + .store + .put_if( + OBJECT_TYPE, + &claim_id, + key, + bucket, + &payload, + None, + WriteCondition::MatchResourceVersion(version), + ) + .await + .map_err(|_| uncertain())?; + return Ok(response); + } + Err(uncertain()) +} + +async fn prune_expired(store: &Store, bucket: &str) -> Result { + // The bucket is atomically bounded, so this scan cannot grow without limit. + let rows = store + .list(OBJECT_TYPE, bucket, MAX_ADMISSIONS_PER_CALLER, 0) + .await + .map_err(storage_error)?; + let mut removed = false; + for row in rows { + let Ok(admission) = serde_json::from_slice::(&row.payload) else { + continue; + }; + if admission.format_version == 1 + && admission.success.is_some() + && admission.completed_at_ms.is_some_and(|completed| { + current_time_ms() >= completed.saturating_add(SUCCESS_TTL_MS) + }) + { + match store + .delete_if(OBJECT_TYPE, &row.id, row.resource_version) + .await + { + Ok(deleted) => removed |= deleted, + Err(PersistenceError::Conflict { .. }) => {} + Err(error) => return Err(storage_error(error)), + } + } + } + Ok(removed) +} + +fn validate_request_id(value: &str) -> Result { + let invalid = || { + rpc_error::invalid_argument( + "request_id", + "must be a nonzero hyphenated UUID (36 characters)", + ) + }; + if value.len() != 36 { + return Err(invalid()); + } + let id = uuid::Uuid::parse_str(value).map_err(|_| invalid())?; + if id.is_nil() || !value.eq_ignore_ascii_case(&id.hyphenated().to_string()) { + return Err(invalid()); + } + Ok(id.hyphenated().to_string()) +} + +fn fingerprint(request: &M) -> Result { + let descriptor = DESCRIPTORS + .get_message_by_name(&format!("openshell.v1.{}Request", M::METHOD)) + .ok_or_else(|| Status::internal("mutation request descriptor missing"))?; + let mut message = DynamicMessage::decode(descriptor, request.encode_to_vec().as_slice()) + .map_err(|_| Status::internal("decode mutation request"))?; + message.clear_field_by_name("request_id"); + let value = serde_json::to_value(message) + .map_err(|_| Status::internal("canonicalize mutation request"))?; + hash_json(&value) +} + +struct FingerprintKey([u8; 32]); + +impl FingerprintKey { + fn id(&self) -> String { + format!("{:x}", Sha256::digest(self.0)) + } + + fn fingerprint(&self, request: &M) -> Result { + let mut mac = Hmac::::new_from_slice(&self.0) + .map_err(|_| Status::internal("initialize mutation fingerprint"))?; + mac.update(fingerprint(request)?.as_bytes()); + Ok(format!("{:x}", mac.finalize().into_bytes())) + } +} + +// New adapters can contain credentials or arbitrary sandbox environment values. +// A plain database hash would permit offline guesses. Reuse existing private +// gateway material without introducing a database-stored key or new deployment +// configuration. HA replicas must share that material; rotation fails closed. +async fn fingerprint_key(state: &ServerState) -> Result { + let path = state + .config + .gateway_jwt + .as_ref() + .map(|jwt| &jwt.signing_key_path) + .or_else(|| state.config.tls.as_ref().map(|tls| &tls.key_path)); + let unavailable = || { + rpc_error::failed_precondition( + "REQUEST_REPLAY_UNAVAILABLE", + "request_id on this method requires readable, stable gateway JWT or TLS private key material; no work was started by this call", + ) + }; + let bytes = tokio::fs::read(path.ok_or_else(unavailable)?) + .await + .map_err(|_| unavailable())?; + if bytes.is_empty() { + return Err(unavailable()); + } + let mut hash = Sha256::new(); + hash.update(b"openshell/mutation-fingerprint/v1\0"); + hash.update(bytes); + Ok(FingerprintKey(hash.finalize().into())) +} + +// Sort every map explicitly; do not depend on serde_json's preserve_order feature. +fn hash_json(value: &serde_json::Value) -> Result { + struct Canonical<'a>(&'a serde_json::Value); + impl Serialize for Canonical<'_> { + fn serialize(&self, serializer: S) -> Result { + match self.0 { + serde_json::Value::Object(map) => map + .iter() + .map(|(key, value)| (key, Canonical(value))) + .collect::>() + .serialize(serializer), + serde_json::Value::Array(values) => values + .iter() + .map(Canonical) + .collect::>() + .serialize(serializer), + value => value.serialize(serializer), + } + } + } + let bytes = serde_json::to_vec(&Canonical(value)) + .map_err(|_| Status::internal("canonicalize mutation payload"))?; + Ok(format!("{:x}", Sha256::digest(bytes))) +} + +fn uncertain() -> Status { + rpc_error::failed_precondition( + "REQUEST_OUTCOME_UNCERTAIN", + "request is admitted but has no confirmed replayable success; reconcile effects before starting a new request", + ) +} + +fn replay_unavailable() -> Status { + rpc_error::failed_precondition( + "REQUEST_REPLAY_UNAVAILABLE", + "the original scope, protected payload, or result is no longer replayable; this request was not executed again", + ) +} + +fn storage_error(error: PersistenceError) -> Status { + tracing::warn!(%error, "mutation admission storage failed"); + Status::internal("mutation admission storage failed") +} + +async fn named_scope(state: &ServerState, name: &str) -> Result { + let name = if name.is_empty() { + workspace::DEFAULT_WORKSPACE_NAME + } else { + name + }; + let resource: Workspace = state + .store + .get_message_by_name("", name) + .await + .map_err(storage_error)? + .ok_or_else(|| Status::not_found("workspace not found"))?; + Ok(Scope { + name: name.into(), + workspace_id: Some(resource.object_id().into()), + }) +} + +fn global_scope(state: &ServerState, principal: &Principal) -> Result { + require_platform_admin(&state.admin_role, principal)?; + Ok(Scope { + name: String::new(), + workspace_id: None, + }) +} + +async fn template_scope( + state: &ServerState, + principal: &Principal, + selector: Option<&WorkspaceSelector>, +) -> Result { + let authz = authorize_workspace_selector( + &state.store, + &state.admin_role, + principal, + selector, + MinWorkspaceRole::Admin, + ) + .await?; + named_scope(state, &authz.workspace).await +} + +async fn member_scope( + state: &ServerState, + principal: &Principal, + name: &str, + role: Option, +) -> Result { + let authz = authorize_workspace( + &state.store, + &state.admin_role, + principal, + name, + MinWorkspaceRole::Admin, + ) + .await?; + if let Some(role) = role { + workspace::authorize_member_role(role, authz.grant)?; + } + named_scope(state, &authz.workspace).await +} + +fn resource_success( + resource: Option<&T>, +) -> Result { + let resource = resource.ok_or_else(uncertain)?; + Ok(Success::Resource { + id: resource.object_id().into(), + version: resource.get_resource_version(), + }) +} + +async fn restore_resource< + T: Message + Default + ObjectType + SetResourceVersion + GetResourceVersion, +>( + store: &Store, + success: Success, +) -> Result { + let Success::Resource { id, version } = success else { + return Err(replay_unavailable()); + }; + let resource: T = store + .get_message(&id) + .await + .map_err(storage_error)? + .ok_or_else(replay_unavailable)?; + if resource.get_resource_version() != version { + return Err(replay_unavailable()); + } + Ok(resource) +} + +macro_rules! resource_mutation { + ($req:ty, $resp:ident, $method:literal, $handler:path, $field:ident, $auth:expr) => { + #[tonic::async_trait] + impl Mutation for $req { + type Output = $resp; + const METHOD: &'static str = $method; + fn request_id(&self) -> &str { + &self.request_id + } + async fn authorize( + &self, + state: &ServerState, + principal: &Principal, + ) -> Result { + ($auth)(self, state, principal).await + } + async fn execute( + state: &Arc, + request: Request, + ) -> Result, Status> { + $handler(state, request).await + } + fn capture(response: &Response) -> Result { + resource_success(response.get_ref().$field.as_ref()) + } + async fn restore(store: &Store, success: Success) -> Result { + Ok($resp { + $field: Some(restore_resource(store, success).await?), + }) + } + } + }; +} + +macro_rules! deletion_mutation { + ($req:ty, $resp:ident, $method:literal, $handler:path, $auth:expr) => { + #[tonic::async_trait] + impl Mutation for $req { + type Output = $resp; + const METHOD: &'static str = $method; + fn request_id(&self) -> &str { + &self.request_id + } + async fn authorize( + &self, + state: &ServerState, + principal: &Principal, + ) -> Result { + ($auth)(self, state, principal).await + } + async fn execute( + state: &Arc, + request: Request, + ) -> Result, Status> { + $handler(state, request).await + } + fn capture(response: &Response) -> Result { + Ok(Success::Deletion { + outcome: response.get_ref().outcome, + }) + } + async fn restore(_store: &Store, success: Success) -> Result { + let Success::Deletion { outcome } = success else { + return Err(replay_unavailable()); + }; + Ok($resp { outcome }) + } + } + }; +} + +resource_mutation!( + CreateWorkspaceRequest, + CreateWorkspaceResponse, + "CreateWorkspace", + workspace::handle_create_workspace, + workspace, + async |req: &CreateWorkspaceRequest, state: &ServerState, principal: &Principal| { + let mut scope = global_scope(state, principal)?; + scope.name.clone_from(&req.name); + Ok(scope) + } +); +deletion_mutation!( + DeleteWorkspaceRequest, + DeleteWorkspaceResponse, + "DeleteWorkspace", + workspace::handle_delete_workspace, + async |req: &DeleteWorkspaceRequest, state: &ServerState, principal: &Principal| { + let mut scope = global_scope(state, principal)?; + scope.name.clone_from(&req.name); + Ok(scope) + } +); +resource_mutation!( + CreateSandboxTemplateRequest, + SandboxTemplateResponse, + "CreateSandboxTemplate", + sandbox::handle_create_sandbox_template, + template, + async |req: &CreateSandboxTemplateRequest, state: &ServerState, principal: &Principal| { + template_scope(state, principal, req.workspace_scope.as_ref()).await + } +); +deletion_mutation!( + DeleteSandboxTemplateRequest, + DeleteSandboxTemplateResponse, + "DeleteSandboxTemplate", + sandbox::handle_delete_sandbox_template, + async |req: &DeleteSandboxTemplateRequest, state: &ServerState, principal: &Principal| { + template_scope(state, principal, req.workspace_scope.as_ref()).await + } +); +resource_mutation!( + AddWorkspaceMemberRequest, + AddWorkspaceMemberResponse, + "AddWorkspaceMember", + workspace::handle_add_workspace_member, + member, + async |req: &AddWorkspaceMemberRequest, state: &ServerState, principal: &Principal| { + member_scope(state, principal, &req.workspace, Some(req.role)).await + } +); +deletion_mutation!( + RemoveWorkspaceMemberRequest, + RemoveWorkspaceMemberResponse, + "RemoveWorkspaceMember", + workspace::handle_remove_workspace_member, + async |req: &RemoveWorkspaceMemberRequest, state: &ServerState, principal: &Principal| { + member_scope(state, principal, &req.workspace, None).await + } +); + +#[cfg(test)] +mod tests; + +pub(super) mod ordinary; diff --git a/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs b/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs new file mode 100644 index 0000000000..3bfef58be1 --- /dev/null +++ b/crates/openshell-server/src/grpc/mutation_replay/ordinary.rs @@ -0,0 +1,980 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Explicit replay recipes. Never serialize a whole public request or response: +//! sandbox specs, provider credentials and refresh material can contain secrets. + +#[cfg(test)] +pub(super) mod tests; + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use openshell_core::proto::{ + ApproveAllDraftChunksRequest, ApproveAllDraftChunksResponse, ApproveDraftChunkRequest, + ApproveDraftChunkResponse, AttachSandboxProviderRequest, AttachSandboxProviderResponse, + ClearDraftChunksRequest, ClearDraftChunksResponse, ConfigureProviderRefreshRequest, + ConfigureProviderRefreshResponse, CreateProviderRequest, CreateSandboxRequest, + DeleteProviderProfileRequest, DeleteProviderProfileResponse, DeleteProviderRefreshRequest, + DeleteProviderRefreshResponse, DeleteProviderRequest, DeleteProviderResponse, + DeleteSandboxRequest, DeleteSandboxResponse, DeleteServiceRequest, DeleteServiceResponse, + DetachSandboxProviderRequest, DetachSandboxProviderResponse, EditDraftChunkRequest, + EditDraftChunkResponse, ExposeServiceRequest, ImportProviderProfilesRequest, + ImportProviderProfilesResponse, Provider, ProviderMutationReceipt, ProviderProfile, + ProviderProfileDiagnostic, ProviderResponse, RejectDraftChunkRequest, RejectDraftChunkResponse, + RotateProviderCredentialRequest, RotateProviderCredentialResponse, Sandbox, SandboxResponse, + ServiceEndpointResponse, StartSandboxRequest, StopSandboxRequest, UndoDraftChunkRequest, + UndoDraftChunkResponse, UpdateConfigRequest, UpdateConfigResponse, + UpdateProviderProfilesRequest, UpdateProviderProfilesResponse, UpdateProviderRequest, + WorkspaceSelector, +}; +use openshell_core::{GetResourceVersion, ObjectId}; +use prost::Message; +use serde::{Deserialize, Serialize}; +use tonic::{Request, Response, Status}; + +use super::{ + Mutation, Scope, Success, global_scope, named_scope, replay_unavailable, restore_resource, + storage_error, uncertain, +}; +use crate::auth::principal::Principal; +use crate::auth::workspace_authz::{ + MinWorkspaceRole, authorize_workspace, authorize_workspace_selector, +}; +use crate::grpc::{policy, provider, sandbox, service}; +use crate::persistence::{ObjectType, SetResourceVersion, Store}; +use crate::storage_proto::{ + StoredProviderCredentialRefreshStateV2 as StoredProviderCredentialRefreshState, + StoredProviderProfile, +}; +use crate::{ServerState, config_update_operation}; + +#[derive(Clone, Serialize, Deserialize)] +pub(in crate::grpc) struct Reference { + id: String, + version: u64, +} + +impl Reference { + fn new(resource: &(impl ObjectId + GetResourceVersion)) -> Self { + Self { + id: resource.object_id().into(), + version: resource.get_resource_version(), + } + } + + async fn restore< + T: Message + Default + ObjectType + SetResourceVersion + GetResourceVersion, + >( + &self, + store: &Store, + ) -> Result { + restore_resource( + store, + Success::Resource { + id: self.id.clone(), + version: self.version, + }, + ) + .await + } +} + +/// Facts come from the handler's actual resource/write, never a later lookup by +/// mutable name. The collector only exists in the owner task and is not metadata. +#[derive(Clone, Default)] +pub struct Facts(Arc>); + +#[derive(Clone, Default)] +struct WriteFacts { + references: Vec, + refresh: Option, + global: bool, +} + +impl Facts { + pub(crate) fn global(&self) -> Result<(), Status> { + self.0.lock().map_err(|_| uncertain())?.global = true; + Ok(()) + } + pub(crate) fn from_request(request: &Request) -> Self { + request + .extensions() + .get::() + .cloned() + .unwrap_or_default() + } + + pub(crate) fn resource( + &self, + resource: &(impl ObjectId + GetResourceVersion), + ) -> Result<(), Status> { + self.0 + .lock() + .map_err(|_| uncertain())? + .references + .push(Reference::new(resource)); + Ok(()) + } + + pub(crate) fn refresh( + &self, + state: &StoredProviderCredentialRefreshState, + ) -> Result<(), Status> { + self.0.lock().map_err(|_| uncertain())?.refresh = Some(Refresh { + id: state.object_id().into(), + provider_id: state.provider_id.clone(), + epoch: crate::provider_refresh::effective_authorization_epoch(state)?.into(), + }); + Ok(()) + } +} + +fn facts(response: &Response) -> Result { + Ok(response + .extensions() + .get::() + .ok_or_else(uncertain)? + .0 + .lock() + .map_err(|_| uncertain())? + .clone()) +} + +fn parent(response: &Response) -> Result { + let facts = facts(response)?; + if facts.references.len() != 1 { + return Err(uncertain()); + } + Ok(facts.references[0].id.clone()) +} + +#[derive(Serialize, Deserialize)] +pub(in crate::grpc) enum Outcome { + Sandbox { + id: String, + changed: bool, + }, + SandboxDeletion { + id: String, + outcome: i32, + }, + Attachment { + id: String, + changed: bool, + receipt: ProviderReceiptReference, + }, + Provider { + reference: Reference, + mutation_id: String, + target_receipts: Vec, + }, + Service { + reference: Reference, + sandbox_id: String, + url: String, + }, + Profiles { + references: Vec, + diagnostics: Vec, + changed: bool, + }, + Config { + sandbox_id: Option, + version: u32, + policy_hash: String, + settings_revision: u64, + deleted: bool, + annotations: HashMap, + }, + Policy { + sandbox_id: String, + version: u32, + hash: String, + approved: u32, + skipped: u32, + cleared: u32, + }, + Refresh(Refresh), +} + +/// Replay retains immutable operation identities, never a fresh target snapshot +/// or a serialized provider response that could carry credential material. +#[derive(Serialize, Deserialize)] +pub(in crate::grpc) struct ProviderReceiptReference { + id: String, + workspace: String, +} + +impl ProviderReceiptReference { + fn new(receipt: &ProviderMutationReceipt) -> Self { + Self { + id: receipt.receipt_id.clone(), + workspace: receipt.workspace.clone(), + } + } + + async fn restore(self, store: &Store) -> Result { + // The original operation is authoritative even after readiness changes. + // A missing operation cannot authorize replaying the mutation itself. + config_update_operation::get_provider_operation(store, &self.id, &self.workspace) + .await + .map(|operation| operation.receipt) + .map_err(|_| replay_unavailable()) + } +} + +/// Public profile declarations and diagnostics have a nonsecret contract. These +/// fields may echo declaration text; they are not arbitrary sanitized payloads. +#[derive(Serialize, Deserialize)] +pub(in crate::grpc) struct Diagnostic { + source: String, + profile_id: String, + field: String, + message: String, + severity: String, +} + +impl From<&ProviderProfileDiagnostic> for Diagnostic { + fn from(value: &ProviderProfileDiagnostic) -> Self { + Self { + source: value.source.clone(), + profile_id: value.profile_id.clone(), + field: value.field.clone(), + message: value.message.clone(), + severity: value.severity.clone(), + } + } +} +impl From for ProviderProfileDiagnostic { + fn from(value: Diagnostic) -> Self { + Self { + source: value.source, + profile_id: value.profile_id, + field: value.field, + message: value.message, + severity: value.severity, + } + } +} + +#[derive(Clone, Serialize, Deserialize)] +pub(in crate::grpc) struct Refresh { + id: String, + provider_id: String, + epoch: String, +} + +fn outcome(success: Success) -> Result { + match success { + Success::Ordinary(value) => Ok(value), + _ => Err(replay_unavailable()), + } +} + +async fn live( + store: &Store, + id: &str, +) -> Result { + store + .get_message(id) + .await + .map_err(storage_error)? + .ok_or_else(replay_unavailable) +} + +async fn selected_scope( + state: &ServerState, + principal: &Principal, + selector: Option<&WorkspaceSelector>, + role: MinWorkspaceRole, +) -> Result { + let authz = + authorize_workspace_selector(&state.store, &state.admin_role, principal, selector, role) + .await?; + named_scope(state, &authz.workspace).await +} + +async fn profile_scope( + state: &ServerState, + principal: &Principal, + workspace: &str, +) -> Result { + if workspace.is_empty() { + return global_scope(state, principal); + } + let authz = authorize_workspace( + &state.store, + &state.admin_role, + principal, + workspace, + MinWorkspaceRole::Admin, + ) + .await?; + named_scope(state, &authz.workspace).await +} + +macro_rules! mutation { + ($req:ty, $resp:ty, $method:literal, $handler:path, $auth:expr, $capture:expr, $restore:expr) => { + #[tonic::async_trait] + impl Mutation for $req { + type Output = $resp; + const METHOD: &'static str = $method; + const PROTECTED: bool = true; + fn request_id(&self) -> &str { + &self.request_id + } + async fn authorize( + &self, + state: &ServerState, + principal: &Principal, + ) -> Result { + ($auth)(self, state, principal).await + } + async fn execute( + state: &Arc, + request: Request, + ) -> Result, Status> { + $handler(state, request).await + } + fn capture(response: &Response) -> Result { + ($capture)(response).map(Success::Ordinary) + } + async fn restore(store: &Store, success: Success) -> Result { + ($restore)(store, outcome(success)?).await + } + } + }; +} + +macro_rules! scoped_mutation { + ($req:ty, $resp:ty, $method:literal, $handler:path, $role:ident, $capture:expr, $restore:expr) => { + mutation!( + $req, + $resp, + $method, + $handler, + async |req: &$req, state: &ServerState, principal: &Principal| { + selected_scope( + state, + principal, + req.workspace_scope.as_ref(), + MinWorkspaceRole::$role, + ) + .await + }, + $capture, + $restore + ); + }; +} + +fn sandbox_receipt(sandbox: Option<&Sandbox>, changed: bool) -> Result { + Ok(Outcome::Sandbox { + id: sandbox.ok_or_else(uncertain)?.object_id().into(), + changed, + }) +} + +macro_rules! sandbox_mutation { + ($req:ty, $method:literal, $handler:path) => { + scoped_mutation!( + $req, + SandboxResponse, + $method, + $handler, + User, + |response: &Response| sandbox_receipt( + response.get_ref().sandbox.as_ref(), + false + ), + async |store: &Store, outcome: Outcome| { + let Outcome::Sandbox { id, .. } = outcome else { + return Err(replay_unavailable()); + }; + Ok(SandboxResponse { + sandbox: Some(live(store, &id).await?), + }) + } + ); + }; +} +sandbox_mutation!( + CreateSandboxRequest, + "CreateSandbox", + sandbox::handle_create_sandbox +); +sandbox_mutation!( + StartSandboxRequest, + "StartSandbox", + sandbox::handle_start_sandbox +); +sandbox_mutation!( + StopSandboxRequest, + "StopSandbox", + sandbox::handle_stop_sandbox +); + +macro_rules! attachment_mutation { + ($req:ty, $resp:ident, $method:literal, $handler:path, $field:ident) => { + scoped_mutation!( + $req, + $resp, + $method, + $handler, + User, + |response: &Response<$resp>| { + let response = response.get_ref(); + Ok(Outcome::Attachment { + id: response + .sandbox + .as_ref() + .ok_or_else(uncertain)? + .object_id() + .into(), + changed: response.$field, + receipt: ProviderReceiptReference::new( + response.receipt.as_ref().ok_or_else(uncertain)?, + ), + }) + }, + async |store: &Store, outcome: Outcome| { + let Outcome::Attachment { + id, + changed, + receipt, + } = outcome + else { + return Err(replay_unavailable()); + }; + Ok($resp { + sandbox: Some(live(store, &id).await?), + $field: changed, + receipt: Some(receipt.restore(store).await?), + }) + } + ); + }; +} +attachment_mutation!( + AttachSandboxProviderRequest, + AttachSandboxProviderResponse, + "AttachSandboxProvider", + sandbox::handle_attach_sandbox_provider, + attached +); +attachment_mutation!( + DetachSandboxProviderRequest, + DetachSandboxProviderResponse, + "DetachSandboxProvider", + sandbox::handle_detach_sandbox_provider, + detached +); + +scoped_mutation!( + DeleteSandboxRequest, + DeleteSandboxResponse, + "DeleteSandbox", + sandbox::handle_delete_sandbox, + User, + |response: &Response| Ok(Outcome::SandboxDeletion { + id: response.get_ref().sandbox_id.clone(), + outcome: response.get_ref().outcome + }), + async |_store: &Store, value: Outcome| { + let Outcome::SandboxDeletion { id, outcome } = value else { + return Err(replay_unavailable()); + }; + Ok(DeleteSandboxResponse { + sandbox_id: id, + outcome, + }) + } +); + +scoped_mutation!( + ExposeServiceRequest, + ServiceEndpointResponse, + "ExposeService", + service::handle_expose_service, + User, + |response: &Response| { + let value = response.get_ref(); + let endpoint = value.endpoint.as_ref().ok_or_else(uncertain)?; + Ok(Outcome::Service { + reference: Reference::new(endpoint), + sandbox_id: endpoint.sandbox_id.clone(), + url: value.url.clone(), + }) + }, + async |store: &Store, outcome: Outcome| { + let Outcome::Service { + reference, + sandbox_id, + url, + } = outcome + else { + return Err(replay_unavailable()); + }; + let _: Sandbox = live(store, &sandbox_id).await?; + Ok(ServiceEndpointResponse { + endpoint: Some(reference.restore(store).await?), + url, + }) + } +); + +macro_rules! provider_mutation { + ($req:ty, $method:literal, $handler:path) => { + scoped_mutation!( + $req, + ProviderResponse, + $method, + $handler, + Admin, + |response: &Response| { + let response = response.get_ref(); + Ok(Outcome::Provider { + reference: Reference::new(response.provider.as_ref().ok_or_else(uncertain)?), + mutation_id: response.mutation_id.clone(), + target_receipts: response + .target_receipts + .iter() + .map(ProviderReceiptReference::new) + .collect(), + }) + }, + async |store: &Store, outcome: Outcome| { + let Outcome::Provider { + reference, + mutation_id, + target_receipts, + } = outcome + else { + return Err(replay_unavailable()); + }; + let mut receipts = Vec::with_capacity(target_receipts.len()); + for receipt in target_receipts { + receipts.push(receipt.restore(store).await?); + } + Ok(ProviderResponse { + provider: Some(provider::redact_provider_credentials( + reference.restore(store).await?, + )), + mutation_id, + target_receipts: receipts, + }) + } + ); + }; +} +provider_mutation!( + CreateProviderRequest, + "CreateProvider", + provider::handle_create_provider +); +provider_mutation!( + UpdateProviderRequest, + "UpdateProvider", + provider::handle_update_provider +); + +// Terminal receipts deliberately do not resolve a deleted parent or replacement. +macro_rules! ordinary_deletion { + ($req:ty, $resp:ident, $method:literal, $handler:path, $auth:expr) => { + #[tonic::async_trait] + impl Mutation for $req { + type Output = $resp; + const METHOD: &'static str = $method; + const PROTECTED: bool = true; + fn request_id(&self) -> &str { + &self.request_id + } + async fn authorize( + &self, + state: &ServerState, + principal: &Principal, + ) -> Result { + ($auth)(self, state, principal).await + } + async fn execute( + state: &Arc, + request: Request, + ) -> Result, Status> { + $handler(state, request).await + } + fn capture(response: &Response) -> Result { + Ok(Success::Deletion { + outcome: response.get_ref().outcome, + }) + } + async fn restore(_store: &Store, success: Success) -> Result { + let Success::Deletion { outcome } = success else { + return Err(replay_unavailable()); + }; + Ok($resp { outcome }) + } + } + }; +} +ordinary_deletion!( + DeleteServiceRequest, + DeleteServiceResponse, + "DeleteService", + service::handle_delete_service, + async |req: &DeleteServiceRequest, state: &ServerState, principal: &Principal| { + selected_scope( + state, + principal, + req.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await + } +); +ordinary_deletion!( + DeleteProviderRequest, + DeleteProviderResponse, + "DeleteProvider", + provider::handle_delete_provider, + async |req: &DeleteProviderRequest, state: &ServerState, principal: &Principal| { + selected_scope( + state, + principal, + req.workspace_scope.as_ref(), + MinWorkspaceRole::Admin, + ) + .await + } +); +ordinary_deletion!( + DeleteProviderRefreshRequest, + DeleteProviderRefreshResponse, + "DeleteProviderRefresh", + provider::handle_delete_provider_refresh, + async |req: &DeleteProviderRefreshRequest, state: &ServerState, principal: &Principal| { + selected_scope( + state, + principal, + req.workspace_scope.as_ref(), + MinWorkspaceRole::Admin, + ) + .await + } +); +ordinary_deletion!( + DeleteProviderProfileRequest, + DeleteProviderProfileResponse, + "DeleteProviderProfile", + provider::handle_delete_provider_profile, + async |req: &DeleteProviderProfileRequest, state: &ServerState, principal: &Principal| { + profile_scope(state, principal, &req.workspace).await + } +); + +async fn restore_profiles( + store: &Store, + references: Vec, +) -> Result, Status> { + let mut profiles = Vec::with_capacity(references.len()); + for reference in references { + let stored: StoredProviderProfile = reference.restore(store).await?; + profiles.push(crate::provider_profile_sources::profile_response_payload( + stored.profile.ok_or_else(replay_unavailable)?, + reference.version, + )); + } + Ok(profiles) +} + +mutation!( + ImportProviderProfilesRequest, + ImportProviderProfilesResponse, + "ImportProviderProfiles", + provider::handle_import_provider_profiles, + async |req: &ImportProviderProfilesRequest, state: &ServerState, principal: &Principal| { + profile_scope(state, principal, &req.workspace).await + }, + |response: &Response| { + let value = response.get_ref(); + let references = facts(response)?.references; + if references.len() != value.profiles.len() { + return Err(uncertain()); + } + Ok(Outcome::Profiles { + references, + diagnostics: value.diagnostics.iter().map(Diagnostic::from).collect(), + changed: value.imported, + }) + }, + async |store: &Store, outcome: Outcome| { + let Outcome::Profiles { + references, + diagnostics, + changed, + } = outcome + else { + return Err(replay_unavailable()); + }; + Ok(ImportProviderProfilesResponse { + profiles: restore_profiles(store, references).await?, + diagnostics: diagnostics.into_iter().map(Into::into).collect(), + imported: changed, + }) + } +); + +mutation!( + UpdateProviderProfilesRequest, + UpdateProviderProfilesResponse, + "UpdateProviderProfiles", + provider::handle_update_provider_profiles, + async |req: &UpdateProviderProfilesRequest, state: &ServerState, principal: &Principal| { + profile_scope(state, principal, &req.workspace).await + }, + |response: &Response| { + let value = response.get_ref(); + let references = facts(response)?.references; + if references.len() != usize::from(value.profile.is_some()) { + return Err(uncertain()); + } + Ok(Outcome::Profiles { + references, + diagnostics: value.diagnostics.iter().map(Diagnostic::from).collect(), + changed: value.updated, + }) + }, + async |store: &Store, outcome: Outcome| { + let Outcome::Profiles { + references, + diagnostics, + changed, + } = outcome + else { + return Err(replay_unavailable()); + }; + let mut profiles = restore_profiles(store, references).await?; + Ok(UpdateProviderProfilesResponse { + profile: profiles.pop(), + diagnostics: diagnostics.into_iter().map(Into::into).collect(), + updated: changed, + }) + } +); + +macro_rules! refresh_mutation { + ($req:ty, $resp:ident, $method:literal, $handler:path) => { + scoped_mutation!( + $req, + $resp, + $method, + $handler, + Admin, + |response: &Response<$resp>| Ok(Outcome::Refresh( + facts(response)?.refresh.ok_or_else(uncertain)? + )), + async |store: &Store, outcome: Outcome| { + let Outcome::Refresh(reference) = outcome else { + return Err(replay_unavailable()); + }; + let state: StoredProviderCredentialRefreshState = + live(store, &reference.id).await?; + let _: Provider = live(store, &reference.provider_id).await?; + if state + .metadata + .as_ref() + .is_some_and(|metadata| metadata.deletion_time.is_some()) + || state.provider_id != reference.provider_id + || crate::provider_refresh::effective_authorization_epoch(&state)? + != reference.epoch + { + return Err(replay_unavailable()); + } + Ok($resp { + status: Some(crate::provider_refresh::refresh_status_from_state(&state)), + }) + } + ); + }; +} +refresh_mutation!( + ConfigureProviderRefreshRequest, + ConfigureProviderRefreshResponse, + "ConfigureProviderRefresh", + provider::handle_configure_provider_refresh +); +refresh_mutation!( + RotateProviderCredentialRequest, + RotateProviderCredentialResponse, + "RotateProviderCredential", + provider::handle_rotate_provider_credential +); + +mutation!( + UpdateConfigRequest, + UpdateConfigResponse, + "UpdateConfig", + policy::handle_update_config, + async |req: &UpdateConfigRequest, state: &ServerState, principal: &Principal| { + if req.global { + if req.workspace_scope.is_some() { + return Err(Status::invalid_argument( + "workspace_scope must be omitted when global is true", + )); + } + global_scope(state, principal) + } else { + selected_scope( + state, + principal, + req.workspace_scope.as_ref(), + MinWorkspaceRole::Admin, + ) + .await + } + }, + |response: &Response| { + let value = response.get_ref(); + let facts = facts(response)?; + let references = facts.references; + if references.len() != usize::from(!facts.global) { + return Err(uncertain()); + } + Ok(Outcome::Config { + sandbox_id: references.first().map(|r| r.id.clone()), + version: value.version, + policy_hash: value.policy_hash.clone(), + settings_revision: value.settings_revision, + deleted: value.deleted, + annotations: value.annotations.clone(), + }) + }, + async |store: &Store, outcome: Outcome| { + let Outcome::Config { + sandbox_id, + version, + policy_hash, + settings_revision, + deleted, + annotations, + } = outcome + else { + return Err(replay_unavailable()); + }; + if let Some(id) = sandbox_id { + let _: Sandbox = live(store, &id).await?; + } + Ok(UpdateConfigResponse { + version, + policy_hash, + settings_revision, + deleted, + annotations, + }) + } +); + +macro_rules! policy_mutation { + ($req:ty, $resp:ty, $method:literal, $handler:path, $values:expr, $restore:expr) => { + scoped_mutation!( + $req, + $resp, + $method, + $handler, + Admin, + |response: &Response<$resp>| { + let (version, hash, approved, skipped, cleared) = ($values)(response.get_ref()); + Ok(Outcome::Policy { + sandbox_id: parent(response)?, + version, + hash, + approved, + skipped, + cleared, + }) + }, + async |store: &Store, outcome: Outcome| { + let Outcome::Policy { + sandbox_id, + version, + hash, + approved, + skipped, + cleared, + } = outcome + else { + return Err(replay_unavailable()); + }; + let _: Sandbox = live(store, &sandbox_id).await?; + Ok(($restore)(version, hash, approved, skipped, cleared)) + } + ); + }; +} +policy_mutation!( + ApproveDraftChunkRequest, + ApproveDraftChunkResponse, + "ApproveDraftChunk", + policy::handle_approve_draft_chunk, + |v: &ApproveDraftChunkResponse| (v.policy_version, v.policy_hash.clone(), 0, 0, 0), + |version, hash, _, _, _| ApproveDraftChunkResponse { + policy_version: version, + policy_hash: hash + } +); +policy_mutation!( + UndoDraftChunkRequest, + UndoDraftChunkResponse, + "UndoDraftChunk", + policy::handle_undo_draft_chunk, + |v: &UndoDraftChunkResponse| (v.policy_version, v.policy_hash.clone(), 0, 0, 0), + |version, hash, _, _, _| UndoDraftChunkResponse { + policy_version: version, + policy_hash: hash + } +); +policy_mutation!( + ApproveAllDraftChunksRequest, + ApproveAllDraftChunksResponse, + "ApproveAllDraftChunks", + policy::handle_approve_all_draft_chunks, + |v: &ApproveAllDraftChunksResponse| ( + v.policy_version, + v.policy_hash.clone(), + v.chunks_approved, + v.chunks_skipped, + 0 + ), + |version, hash, approved, skipped, _| ApproveAllDraftChunksResponse { + policy_version: version, + policy_hash: hash, + chunks_approved: approved, + chunks_skipped: skipped + } +); +policy_mutation!( + ClearDraftChunksRequest, + ClearDraftChunksResponse, + "ClearDraftChunks", + policy::handle_clear_draft_chunks, + |v: &ClearDraftChunksResponse| (0, String::new(), 0, 0, v.chunks_cleared), + |_, _, _, _, cleared| ClearDraftChunksResponse { + chunks_cleared: cleared + } +); +policy_mutation!( + RejectDraftChunkRequest, + RejectDraftChunkResponse, + "RejectDraftChunk", + policy::handle_reject_draft_chunk, + |_: &RejectDraftChunkResponse| (0, String::new(), 0, 0, 0), + |_, _, _, _, _| RejectDraftChunkResponse {} +); +policy_mutation!( + EditDraftChunkRequest, + EditDraftChunkResponse, + "EditDraftChunk", + policy::handle_edit_draft_chunk, + |_: &EditDraftChunkResponse| (0, String::new(), 0, 0, 0), + |_, _, _, _, _| EditDraftChunkResponse {} +); diff --git a/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs b/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs new file mode 100644 index 0000000000..55675f057f --- /dev/null +++ b/crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs @@ -0,0 +1,1069 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::grpc::mutation_replay::tests::reason; +use crate::grpc::mutation_replay::{Admission, OBJECT_TYPE, OriginalMutation, fingerprint, run}; +use crate::grpc::test_support::{authed_request, test_server_state}; +use openshell_core::proto::datamodel::v1::ObjectMeta; +use openshell_core::proto::{ + DeletionOutcome, DraftChunkApproval, GetDraftPolicyRequest, NetworkBinary, NetworkEndpoint, + NetworkPolicyRule, PolicyChunk, ProviderCredentialRefresh, ProviderCredentialRefreshMaterial, + ProviderCredentialRefreshStrategy, ProviderProfileCategory, ProviderProfileCredential, + ProviderProfileImportItem, SandboxPhase, SandboxPolicy, SandboxSpec, ServiceEndpoint, + SettingValue, SubmitPolicyAnalysisRequest, WorkspaceMember, WorkspaceRole, setting_value, + workspace_selector, +}; +use tonic::Code; + +async fn protected_state() -> (tempfile::TempDir, Arc) { + let directory = tempfile::tempdir().unwrap(); + let mut state = test_server_state().await; + configure_key(&mut state, &directory); + (directory, state) +} + +fn configure_key(state: &mut Arc, directory: &tempfile::TempDir) { + let key = directory.path().join("private-key"); + std::fs::write(&key, b"test-only stable private fingerprint material").unwrap(); + Arc::get_mut(state).unwrap().config.gateway_jwt = + Some(openshell_core::config::GatewayJwtConfig { + signing_key_path: key, + public_key_path: directory.path().join("public"), + kid_path: directory.path().join("kid"), + gateway_id: "test".into(), + ttl_secs: None, + }); +} + +pub(in crate::grpc::mutation_replay) async fn exercise_protected_backend(url: &str) { + use crate::grpc::mutation_replay::tests::state_for; + let directory = tempfile::tempdir().unwrap(); + let mut first = state_for(Store::connect(url).await.unwrap()).await; + let mut second = state_for(Store::connect(url).await.unwrap()).await; + configure_key(&mut first, &directory); + configure_key(&mut second, &directory); + let req = DeleteSandboxRequest { + name: "keyed-restart".into(), + workspace_scope: Some(scope()), + allow_missing: true, + request_id: id(), + }; + let mut tasks = Vec::new(); + for index in 0..16 { + let state = if index % 2 == 0 { + first.clone() + } else { + second.clone() + }; + let req = req.clone(); + tasks.push(tokio::spawn(async move { + run(&state, authed_request(req)).await + })); + } + for task in tasks { + if let Err(status) = task.await.unwrap() { + assert_eq!(reason(&status), "REQUEST_OUTCOME_UNCERTAIN"); + } + } + drop(first); + drop(second); + let mut restarted = state_for(Store::connect(url).await.unwrap()).await; + configure_key(&mut restarted, &directory); + let replacement = Sandbox { + metadata: Some(meta(&req.name)), + ..Default::default() + }; + restarted.store.put_message(&replacement).await.unwrap(); + assert_eq!( + replay(&restarted, req).await.outcome, + i32::from(DeletionOutcome::AlreadyAbsent) + ); + assert!( + restarted + .store + .get_message::(replacement.object_id()) + .await + .unwrap() + .is_some() + ); +} + +#[tokio::test] +async fn ordinary_replay_reauthorizes_workspace_role() { + let (_directory, mut state) = protected_state().await; + Arc::get_mut(&mut state).unwrap().admin_role = "openshell-admin".into(); + let req = DeleteProviderRequest { + name: "missing".into(), + workspace_scope: Some(scope()), + allow_missing: true, + request_id: id(), + }; + run(&state, authed_request(req.clone())).await.unwrap(); + let member = WorkspaceMember { + metadata: Some(meta("dev-user")), + principal_subject: "dev-user".into(), + role: WorkspaceRole::User.into(), + }; + state.store.put_message(&member).await.unwrap(); + let mut request = authed_request(req); + let principal = request.extensions_mut().get_mut::().unwrap(); + if let Principal::User(user) = principal { + user.identity.roles.clear(); + } + let principal = principal.clone(); + assert!( + CreateSandboxRequest { + workspace_scope: Some(scope()), + ..Default::default() + } + .authorize(&state, &principal) + .await + .is_ok() + ); + assert_eq!( + run(&state, request).await.unwrap_err().code(), + Code::PermissionDenied + ); + for global in [false, true] { + let req = UpdateConfigRequest { + global, + workspace_scope: if global { None } else { Some(scope()) }, + ..Default::default() + }; + assert!(req.authorize(&state, &principal).await.is_err()); + } + assert!( + ImportProviderProfilesRequest::default() + .authorize(&state, &principal) + .await + .is_err() + ); +} + +#[tokio::test] +async fn oversized_public_diagnostics_leave_a_bounded_unresolved_claim() { + let (_directory, state) = protected_state().await; + let request = ImportProviderProfilesRequest { + request_id: id(), + profiles: (0..80) + .map(|_| ProviderProfileImportItem { + profile: None, + source: "public-source".repeat(100), + }) + .collect(), + ..Default::default() + }; + for _ in 0..2 { + assert_eq!( + reason( + &run(&state, authed_request(request.clone())) + .await + .unwrap_err() + ), + "REQUEST_OUTCOME_UNCERTAIN" + ); + } + let rows = state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap(); + assert_eq!(rows.len(), 1); + assert!(rows[0].payload.len() < 1024); + assert!( + serde_json::from_slice::(&rows[0].payload) + .unwrap() + .success + .is_none() + ); +} + +fn scope() -> WorkspaceSelector { + workspace_selector("default") +} +fn id() -> String { + uuid::Uuid::new_v4().to_string() +} +fn meta(name: &str) -> ObjectMeta { + ObjectMeta { + id: id(), + name: name.into(), + workspace: "default".into(), + ..Default::default() + } +} + +fn create_sandbox(name: &str) -> CreateSandboxRequest { + CreateSandboxRequest { + name: name.into(), + request_id: id(), + workspace_scope: Some(scope()), + spec: Some(SandboxSpec { + environment: HashMap::from([("PRIVATE_VALUE".into(), "low-entropy-secret".into())]), + ..Default::default() + }), + ..Default::default() + } +} + +async fn replay(state: &Arc, req: M) -> M::Output { + let response = run(state, authed_request(req)).await.unwrap(); + assert_eq!( + response.metadata().get("openshell-replayed").unwrap(), + "true" + ); + response.into_inner() +} + +#[tokio::test] +async fn sandbox_replay_survives_status_churn_but_never_selects_replacement() { + let (_directory, state) = protected_state().await; + let req = create_sandbox("original"); + let created = run(&state, authed_request(req.clone())) + .await + .unwrap() + .into_inner() + .sandbox + .unwrap(); + state + .store + .update_message_cas::( + created.object_id(), + created.get_resource_version(), + |sandbox| { + sandbox.status.as_mut().unwrap().phase = SandboxPhase::Ready.into(); + }, + ) + .await + .unwrap(); + let returned = replay(&state, req.clone()).await.sandbox.unwrap(); + assert_eq!(returned.object_id(), created.object_id()); + assert!(returned.get_resource_version() > created.get_resource_version()); + let rows = state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap(); + let receipt = String::from_utf8(rows[0].payload.clone()).unwrap(); + assert!(!receipt.contains("low-entropy-secret")); + assert!(!receipt.contains("PRIVATE_VALUE")); + assert!(!receipt.contains(&fingerprint(&req).unwrap())); + state + .store + .delete(Sandbox::object_type(), created.object_id()) + .await + .unwrap(); + let replacement = Sandbox { + metadata: Some(meta("original")), + ..Default::default() + }; + state.store.put_message(&replacement).await.unwrap(); + assert_eq!( + reason(&run(&state, authed_request(req)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); + assert!( + state + .store + .get_message::(replacement.object_id()) + .await + .unwrap() + .is_some() + ); +} + +#[tokio::test] +async fn keyed_fingerprints_fail_closed_on_missing_or_rotated_keys() { + let missing = test_server_state().await; + let req = DeleteSandboxRequest { + name: "missing".into(), + workspace_scope: Some(scope()), + allow_missing: true, + request_id: id(), + }; + assert_eq!( + reason( + &run(&missing, authed_request(req.clone())) + .await + .unwrap_err() + ), + "REQUEST_REPLAY_UNAVAILABLE" + ); + assert!( + missing + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap() + .is_empty() + ); + let (directory, state) = protected_state().await; + run(&state, authed_request(req.clone())).await.unwrap(); + std::fs::write( + directory.path().join("private-key"), + b"rotated-private-material", + ) + .unwrap(); + assert_eq!( + reason(&run(&state, authed_request(req)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); + assert_eq!( + state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap() + .len(), + 1 + ); +} + +#[tokio::test] +async fn original_payload_is_identity_and_current_transformation_is_a_replay_guard() { + let (_directory, state) = protected_state().await; + let original = DeleteSandboxRequest { + name: "original".into(), + workspace_scope: Some(scope()), + allow_missing: true, + request_id: id(), + }; + let mut effective = original.clone(); + effective.name = "transformed".into(); + let intercepted = |original: &DeleteSandboxRequest, effective: DeleteSandboxRequest| { + let mut request = authed_request(effective); + request + .extensions_mut() + .insert(OriginalMutation(original.encode_to_vec())); + request + }; + run(&state, intercepted(&original, effective.clone())) + .await + .unwrap(); + assert!( + run(&state, intercepted(&original, effective.clone())) + .await + .unwrap() + .metadata() + .contains_key("openshell-replayed") + ); + let mut changed = original.clone(); + changed.name = "different-original".into(); + assert_eq!( + reason( + &run(&state, intercepted(&changed, effective.clone())) + .await + .unwrap_err() + ), + "REQUEST_ID_PAYLOAD_MISMATCH" + ); + effective.name = "changed-transformation".into(); + assert_eq!( + reason( + &run(&state, intercepted(&original, effective)) + .await + .unwrap_err() + ), + "REQUEST_REPLAY_UNAVAILABLE" + ); +} + +#[tokio::test] +async fn interceptors_cannot_enable_disable_or_replace_request_ids() { + let state = test_server_state().await; + for (original_id, effective_id) in [(String::new(), id()), (id(), String::new()), (id(), id())] + { + let original = CreateSandboxRequest { + request_id: original_id, + ..Default::default() + }; + let mut req = authed_request(CreateSandboxRequest { + request_id: effective_id, + ..Default::default() + }); + req.extensions_mut() + .insert(OriginalMutation(original.encode_to_vec())); + assert_eq!( + run(&state, req).await.unwrap_err().code(), + Code::InvalidArgument + ); + } + assert!( + state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap() + .is_empty() + ); +} + +#[tokio::test] +async fn service_deletion_replays_without_parent_and_does_not_delete_replacement() { + let (_directory, state) = protected_state().await; + let sandbox = Sandbox { + metadata: Some(meta("service-parent")), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + let expose = ExposeServiceRequest { + sandbox: "service-parent".into(), + service: "web".into(), + target_port: 8080, + workspace_scope: Some(scope()), + request_id: id(), + ..Default::default() + }; + let endpoint = run(&state, authed_request(expose.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, expose.clone()).await, endpoint); + let delete = DeleteServiceRequest { + sandbox: "service-parent".into(), + service: "web".into(), + workspace_scope: Some(scope()), + request_id: id(), + ..Default::default() + }; + let deleted = run(&state, authed_request(delete.clone())) + .await + .unwrap() + .into_inner(); + let mut fresh = expose; + fresh.request_id = id(); + let replacement = run(&state, authed_request(fresh)) + .await + .unwrap() + .into_inner() + .endpoint + .unwrap(); + state + .store + .delete(Sandbox::object_type(), sandbox.object_id()) + .await + .unwrap(); + assert_eq!(replay(&state, delete).await, deleted); + assert!( + state + .store + .get_message::(replacement.object_id()) + .await + .unwrap() + .is_some() + ); +} + +#[tokio::test] +async fn provider_replay_preserves_receipts_after_attachment_changes() { + let (_directory, state) = protected_state().await; + let created = run( + &state, + authed_request(CreateProviderRequest { + provider: Some(Provider { + metadata: Some(meta("receipt-provider")), + r#type: "openai".into(), + credentials: HashMap::from([("OPENAI_API_KEY".into(), "private-value".into())]), + ..Default::default() + }), + workspace_scope: Some(scope()), + request_id: id(), + }), + ) + .await + .unwrap() + .into_inner(); + let sandbox = Sandbox { + metadata: Some(meta("receipt-sandbox")), + spec: Some(SandboxSpec::default()), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + let attach = AttachSandboxProviderRequest { + sandbox_name: "receipt-sandbox".into(), + provider_name: "receipt-provider".into(), + workspace_scope: Some(scope()), + request_id: id(), + ..Default::default() + }; + let attached = run(&state, authed_request(attach.clone())) + .await + .unwrap() + .into_inner(); + assert!(attached.attached); + assert!(attached.receipt.is_some()); + assert_eq!(replay(&state, attach.clone()).await, attached); + + let mut provider = created.provider.unwrap(); + provider.credentials = HashMap::from([("OPENAI_API_KEY".into(), "replacement-value".into())]); + let update = UpdateProviderRequest { + provider: Some(provider), + workspace_scope: Some(scope()), + request_id: id(), + ..Default::default() + }; + let updated = run(&state, authed_request(update.clone())) + .await + .unwrap() + .into_inner(); + assert!(!updated.mutation_id.is_empty()); + assert_eq!(updated.target_receipts.len(), 1); + assert_eq!(updated.target_receipts[0].mutation_id, updated.mutation_id); + + let detach = DetachSandboxProviderRequest { + sandbox_name: "receipt-sandbox".into(), + provider_name: "receipt-provider".into(), + workspace_scope: Some(scope()), + request_id: id(), + ..Default::default() + }; + let detached = run(&state, authed_request(detach.clone())) + .await + .unwrap() + .into_inner(); + assert!(detached.detached); + assert!(detached.receipt.is_some()); + assert_eq!(replay(&state, detach.clone()).await, detached); + + // Replay returns the original target and epoch even though it is detached + // now. It neither selects new targets nor executes the stale attach again. + assert_eq!(replay(&state, update.clone()).await, updated); + let replayed_attach = replay(&state, attach).await; + assert_eq!(replayed_attach.receipt, attached.receipt); + assert!(replayed_attach.attached); + assert_eq!(replayed_attach.sandbox, detached.sandbox); + let operations = state + .store + .count_in_workspace( + config_update_operation::CONFIG_UPDATE_OPERATION_OBJECT_TYPE, + "default", + ) + .await + .unwrap(); + assert_eq!(operations, 3); + + // Lost operation evidence makes replay unavailable. It must not rotate + // credentials or produce a replacement receipt to repair that evidence. + state + .store + .delete( + config_update_operation::CONFIG_UPDATE_OPERATION_OBJECT_TYPE, + &updated.target_receipts[0].receipt_id, + ) + .await + .unwrap(); + assert_eq!( + reason(&run(&state, authed_request(update)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); + assert_eq!(replay(&state, detach).await, detached); + let current: Provider = state + .store + .get_message(updated.provider.as_ref().unwrap().object_id()) + .await + .unwrap() + .unwrap(); + assert_eq!( + current.get_resource_version(), + updated.provider.unwrap().get_resource_version() + ); +} + +#[tokio::test] +async fn provider_replay_is_redacted_and_update_does_not_recheck_stale_version() { + let (_directory, state) = protected_state().await; + let create = CreateProviderRequest { + provider: Some(Provider { + metadata: Some(meta("replay-provider")), + r#type: "openai".into(), + credentials: HashMap::from([("OPENAI_API_KEY".into(), "provider-secret".into())]), + ..Default::default() + }), + workspace_scope: Some(scope()), + request_id: id(), + }; + let first = run(&state, authed_request(create.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, create).await, first); + let mut provider = first.provider.unwrap(); + provider.credentials = HashMap::from([("OPENAI_API_KEY".into(), "updated-secret".into())]); + let update = UpdateProviderRequest { + provider: Some(provider), + workspace_scope: Some(scope()), + request_id: id(), + ..Default::default() + }; + let updated = run(&state, authed_request(update.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, update).await, updated); + let provider = updated.provider.unwrap(); + assert!(provider.credential_handles.is_empty()); + assert!( + provider + .credentials + .values() + .all(|value| value == "REDACTED") + ); + for row in state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap() + { + let receipt = String::from_utf8(row.payload).unwrap(); + assert!(!receipt.contains("provider-secret")); + assert!(!receipt.contains("updated-secret")); + } +} + +#[tokio::test] +async fn profile_receipts_use_private_identity_and_preserve_diagnostics() { + let (_directory, state) = protected_state().await; + let profile = ProviderProfile { + id: "replay-profile".into(), + display_name: "Replay".into(), + category: ProviderProfileCategory::Other.into(), + ..Default::default() + }; + let create = ImportProviderProfilesRequest { + profiles: vec![ProviderProfileImportItem { + profile: Some(profile), + source: "test.yaml".into(), + }], + workspace: "default".into(), + request_id: id(), + }; + let first = run(&state, authed_request(create.clone())) + .await + .unwrap() + .into_inner(); + assert!(first.imported, "{:?}", first.diagnostics); + assert_eq!(replay(&state, create.clone()).await, first); + let mut profile = first.profiles[0].clone(); + profile.display_name = "Updated".into(); + let update = UpdateProviderProfilesRequest { + id: profile.id.clone(), + profile: Some(ProviderProfileImportItem { + profile: Some(profile), + source: "update.yaml".into(), + }), + workspace: "default".into(), + request_id: id(), + ..Default::default() + }; + let updated = run(&state, authed_request(update.clone())) + .await + .unwrap() + .into_inner(); + assert!(updated.updated); + assert_eq!(replay(&state, update).await, updated); + assert_eq!( + reason(&run(&state, authed_request(create)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); + let invalid = ImportProviderProfilesRequest { + request_id: id(), + ..Default::default() + }; + let diagnostics = run(&state, authed_request(invalid.clone())) + .await + .unwrap() + .into_inner(); + assert!(!diagnostics.imported); + assert!(!diagnostics.diagnostics.is_empty()); + assert_eq!(replay(&state, invalid).await, diagnostics); +} + +#[tokio::test] +async fn config_and_clear_receipts_preserve_revision_and_parent_lifetime() { + let (_directory, state) = protected_state().await; + let sandbox = Sandbox { + metadata: Some(meta("policy-parent")), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + for global in [false, true] { + let update = UpdateConfigRequest { + name: if global { + String::new() + } else { + "policy-parent".into() + }, + global, + setting_key: "ocsf_json_enabled".into(), + setting_value: Some(SettingValue { + value: Some(setting_value::Value::BoolValue(true)), + }), + workspace_scope: if global { None } else { Some(scope()) }, + request_id: id(), + ..Default::default() + }; + let first = run(&state, authed_request(update.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, update).await, first); + } + let clear = ClearDraftChunksRequest { + name: "policy-parent".into(), + workspace_scope: Some(scope()), + request_id: id(), + }; + let first = run(&state, authed_request(clear.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, clear.clone()).await, first); + state + .store + .delete(Sandbox::object_type(), sandbox.object_id()) + .await + .unwrap(); + assert_eq!( + reason(&run(&state, authed_request(clear)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); +} + +#[tokio::test] +async fn refresh_receipts_never_replay_a_new_grant_epoch() { + let state = test_server_state().await; + let provider = Provider { + metadata: Some(meta("refresh-parent")), + ..Default::default() + }; + state.store.put_message(&provider).await.unwrap(); + let mut refresh = StoredProviderCredentialRefreshState { + metadata: Some(meta("refresh-record")), + provider_id: provider.object_id().into(), + authorization_epoch: id(), + ..Default::default() + }; + state.store.put_message(&refresh).await.unwrap(); + let receipt = || { + Success::Ordinary(Outcome::Refresh(Refresh { + id: refresh.object_id().into(), + provider_id: provider.object_id().into(), + epoch: refresh.authorization_epoch.clone(), + })) + }; + ConfigureProviderRefreshRequest::restore(&state.store, receipt()) + .await + .unwrap(); + let original = receipt(); + refresh.authorization_epoch = id(); + state.store.put_message(&refresh).await.unwrap(); + assert_eq!( + reason( + &ConfigureProviderRefreshRequest::restore(&state.store, original) + .await + .unwrap_err() + ), + "REQUEST_REPLAY_UNAVAILABLE" + ); +} + +#[tokio::test] +async fn refresh_receipts_reject_epoch_deletion_timestamps() { + let state = test_server_state().await; + let provider = Provider { + metadata: Some(meta("deleted-refresh-parent")), + ..Default::default() + }; + state.store.put_message(&provider).await.unwrap(); + let refresh = StoredProviderCredentialRefreshState { + metadata: Some(ObjectMeta { + deletion_time: Some(prost_types::Timestamp::default()), + ..meta("deleted-refresh-record") + }), + provider_id: provider.object_id().into(), + authorization_epoch: id(), + ..Default::default() + }; + state.store.put_message(&refresh).await.unwrap(); + let receipt = || { + Success::Ordinary(Outcome::Refresh(Refresh { + id: refresh.object_id().into(), + provider_id: provider.object_id().into(), + epoch: refresh.authorization_epoch.clone(), + })) + }; + for error in [ + ConfigureProviderRefreshRequest::restore(&state.store, receipt()) + .await + .unwrap_err(), + RotateProviderCredentialRequest::restore(&state.store, receipt()) + .await + .unwrap_err(), + ] { + assert_eq!(reason(&error), "REQUEST_REPLAY_UNAVAILABLE"); + } +} + +#[tokio::test] +async fn configure_and_rotate_capture_actual_grant_without_repeating_token_exchange() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + let (_directory, state) = protected_state().await; + let server = MockServer::start().await; + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "access_token": "minted-secret", "token_type": "Bearer", "expires_in": 3600, + }))) + .expect(1) + .mount(&server) + .await; + let strategy = ProviderCredentialRefreshStrategy::Oauth2ClientCredentials; + let profile = ProviderProfile { + id: "refresh-profile".into(), + display_name: "Refresh".into(), + category: ProviderProfileCategory::Other.into(), + credentials: vec![ProviderProfileCredential { + name: "access_token".into(), + env_vars: vec!["ACCESS_TOKEN".into()], + auth_style: "bearer".into(), + header_name: "Authorization".into(), + refresh: Some(ProviderCredentialRefresh { + strategy: strategy.into(), + token_url: server.uri(), + material: vec![ + ProviderCredentialRefreshMaterial { + name: "client_id".into(), + required: true, + ..Default::default() + }, + ProviderCredentialRefreshMaterial { + name: "client_secret".into(), + secret: true, + required: true, + ..Default::default() + }, + ], + ..Default::default() + }), + ..Default::default() + }], + ..Default::default() + }; + let imported = run( + &state, + authed_request(ImportProviderProfilesRequest { + workspace: "default".into(), + profiles: vec![ProviderProfileImportItem { + profile: Some(profile), + source: "refresh.yaml".into(), + }], + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert!(imported.imported, "{:?}", imported.diagnostics); + run( + &state, + authed_request(CreateProviderRequest { + workspace_scope: Some(scope()), + provider: Some(Provider { + metadata: Some(meta("refresh-provider")), + r#type: "refresh-profile".into(), + profile_workspace: "default".into(), + credentials: HashMap::from([("ACCESS_TOKEN".into(), "initial-secret".into())]), + ..Default::default() + }), + ..Default::default() + }), + ) + .await + .unwrap(); + let configure = ConfigureProviderRefreshRequest { + provider: "refresh-provider".into(), + credential_key: "ACCESS_TOKEN".into(), + strategy: strategy.into(), + workspace_scope: Some(scope()), + request_id: id(), + material: HashMap::from([ + ("client_id".into(), "client".into()), + ("client_secret".into(), "configured-secret".into()), + ]), + ..Default::default() + }; + let configured = run(&state, authed_request(configure.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, configure.clone()).await, configured); + let rotate = RotateProviderCredentialRequest { + provider: "refresh-provider".into(), + credential_key: "ACCESS_TOKEN".into(), + workspace_scope: Some(scope()), + request_id: id(), + }; + let rotated = run(&state, authed_request(rotate.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, rotate).await, rotated); + assert_eq!(replay(&state, configure).await.status, rotated.status); + for row in state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap() + { + let receipt = String::from_utf8(row.payload).unwrap(); + for secret in ["initial-secret", "configured-secret", "minted-secret"] { + assert!(!receipt.contains(secret)); + } + } + server.verify().await; +} + +#[tokio::test] +async fn draft_receipts_replay_after_chunk_state_and_review_tokens_change() { + let (_directory, state) = protected_state().await; + let name = "draft-parent"; + let sandbox = Sandbox { + metadata: Some(meta(name)), + spec: Some(SandboxSpec { + policy: Some(SandboxPolicy::default()), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + let rule = |name: &str| NetworkPolicyRule { + name: name.into(), + endpoints: vec![NetworkEndpoint { + host: format!("{name}.example.com"), + port: 443, + ..Default::default() + }], + binaries: vec![NetworkBinary { + path: "/usr/bin/curl".into(), + }], + }; + let submitted = policy::handle_submit_policy_analysis( + &state, + authed_request(SubmitPolicyAnalysisRequest { + name: name.into(), + analysis_mode: "agent_authored".into(), + proposed_chunks: ["alpha", "beta", "gamma"] + .into_iter() + .map(|name| PolicyChunk { + rule_name: name.into(), + proposed_rule: Some(rule(name)), + ..Default::default() + }) + .collect(), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!( + submitted.accepted_chunk_ids.len(), + 3, + "{:?}", + submitted.rejection_reasons + ); + let edit = EditDraftChunkRequest { + name: name.into(), + chunk_id: submitted.accepted_chunk_ids[0].clone(), + proposed_rule: Some(rule("edited")), + workspace_scope: Some(scope()), + request_id: id(), + }; + run(&state, authed_request(edit.clone())).await.unwrap(); + let draft = policy::handle_get_draft_policy( + &state, + authed_request(GetDraftPolicyRequest { + name: name.into(), + workspace_scope: Some(scope()), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + let token = |id: &str| { + draft + .chunks + .iter() + .find(|chunk| chunk.id == id) + .unwrap() + .review_token + .clone() + }; + let approve = ApproveDraftChunkRequest { + name: name.into(), + chunk_id: edit.chunk_id.clone(), + review_token: token(&edit.chunk_id), + workspace_scope: Some(scope()), + request_id: id(), + }; + let approved = run(&state, authed_request(approve.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, approve.clone()).await, approved); + replay(&state, edit).await; + let undo = UndoDraftChunkRequest { + name: name.into(), + chunk_id: approve.chunk_id.clone(), + workspace_scope: Some(scope()), + request_id: id(), + }; + let undone = run(&state, authed_request(undo.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(replay(&state, undo).await, undone); + assert_eq!(replay(&state, approve).await, approved); + let reject = RejectDraftChunkRequest { + name: name.into(), + chunk_id: submitted.accepted_chunk_ids[1].clone(), + reason: "not needed".into(), + workspace_scope: Some(scope()), + request_id: id(), + }; + run(&state, authed_request(reject.clone())).await.unwrap(); + replay(&state, reject).await; + let draft = policy::handle_get_draft_policy( + &state, + authed_request(GetDraftPolicyRequest { + name: name.into(), + workspace_scope: Some(scope()), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + let chunk = draft + .chunks + .iter() + .find(|chunk| chunk.id == submitted.accepted_chunk_ids[2]) + .unwrap(); + let all = ApproveAllDraftChunksRequest { + name: name.into(), + approvals: vec![DraftChunkApproval { + chunk_id: chunk.id.clone(), + review_token: chunk.review_token.clone(), + }], + workspace_scope: Some(scope()), + request_id: id(), + ..Default::default() + }; + let approved = run(&state, authed_request(all.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!(approved.chunks_approved, 1); + assert_eq!(replay(&state, all).await, approved); +} diff --git a/crates/openshell-server/src/grpc/mutation_replay/tests.rs b/crates/openshell-server/src/grpc/mutation_replay/tests.rs new file mode 100644 index 0000000000..47b3e90a33 --- /dev/null +++ b/crates/openshell-server/src/grpc/mutation_replay/tests.rs @@ -0,0 +1,966 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::grpc::test_support::{authed_request, test_server_state}; +use openshell_core::proto::datamodel::v1::ObjectMeta; +use openshell_core::proto::open_shell_server::OpenShell; +use openshell_core::proto::{ + SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateSpec, WorkspaceMember, + WorkspaceRole, workspace_selector, +}; +use openshell_core::rpc_error::StatusExt; +use std::collections::HashMap; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; +use tonic::Code; + +fn create(name: &str) -> CreateWorkspaceRequest { + CreateWorkspaceRequest { + name: name.into(), + request_id: uuid::Uuid::new_v4().to_string(), + ..Default::default() + } +} + +pub(super) fn reason(status: &Status) -> String { + assert!(status.get_error_details().retry_info().is_none()); + status + .get_error_details() + .error_info() + .unwrap_or_else(|| panic!("missing structured reason: {status:?}")) + .reason + .clone() +} + +pub(super) async fn state_for(store: Store) -> Arc { + let store = Arc::new(store); + crate::ensure_default_workspace(&store).await.unwrap(); + let compute = crate::compute::new_test_runtime(store.clone()).await; + Arc::new(ServerState::new( + openshell_core::Config::new(None).with_credential_drivers(["test-static"]), + store, + compute, + crate::sandbox_index::SandboxIndex::new(), + crate::sandbox_watch::SandboxWatchBus::new(), + crate::tracing_bus::TracingLogBus::new(), + Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), + None, + )) +} + +#[test] +fn validates_bounded_nonzero_uuid_and_normalizes_case() { + for value in [ + "", + "not-a-uuid", + "00000000-0000-0000-0000-000000000000", + "550e8400e29b41d4a716446655440000", + "urn:uuid:550e8400-e29b-41d4-a716-446655440000", + ] { + let status = validate_request_id(value).unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); + assert_eq!( + status + .get_error_details() + .bad_request() + .unwrap() + .field_violations[0] + .field, + "request_id" + ); + } + assert_eq!( + validate_request_id("550E8400-E29B-41D4-A716-446655440000").unwrap(), + "550e8400-e29b-41d4-a716-446655440000" + ); +} + +#[test] +fn canonical_payload_ignores_map_order_and_id_but_preserves_presence() { + let mut first = create("canonical"); + first.labels = HashMap::from([("a".into(), "1".into()), ("b".into(), "2".into())]); + let mut second = create("canonical"); + second.labels = HashMap::from([("b".into(), "2".into()), ("a".into(), "1".into())]); + assert_eq!(fingerprint(&first).unwrap(), fingerprint(&second).unwrap()); + second.labels.insert("b".into(), "3".into()); + assert_ne!(fingerprint(&first).unwrap(), fingerprint(&second).unwrap()); + let mut template = CreateSandboxTemplateRequest::default(); + let absent = fingerprint(&template).unwrap(); + template.template = Some(SandboxWorkloadTemplate::default()); + assert_ne!(absent, fingerprint(&template).unwrap()); +} + +async fn exercise_backend(url: &str) { + let first = state_for(Store::connect(url).await.unwrap()).await; + let second = state_for(Store::connect(url).await.unwrap()).await; + let req = create(&format!( + "replay-{}", + &uuid::Uuid::new_v4().simple().to_string()[..12] + )); + let mut tasks = Vec::new(); + for i in 0..24 { + let state = if i % 2 == 0 { + first.clone() + } else { + second.clone() + }; + let req = req.clone(); + tasks.push(tokio::spawn(async move { + run(&state, authed_request(req)).await + })); + } + let mut successes = 0; + for task in tasks { + match task.await.unwrap() { + Ok(_) => successes += 1, + Err(status) => assert_eq!(reason(&status), "REQUEST_OUTCOME_UNCERTAIN"), + } + } + assert!(successes > 0); + let original = run(&first, authed_request(req.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!( + first + .store + .count_in_workspace(Workspace::object_type(), "") + .await + .unwrap(), + 2 + ); + drop(first); + drop(second); + let restarted = state_for(Store::connect(url).await.unwrap()).await; + let replay = run(&restarted, authed_request(req.clone())).await.unwrap(); + assert_eq!(replay.metadata().get("openshell-replayed").unwrap(), "true"); + assert_eq!(original, replay.into_inner()); + let mut mismatch = req.clone(); + mismatch.labels.insert("changed".into(), "payload".into()); + assert_eq!( + reason(&run(&restarted, authed_request(mismatch)).await.unwrap_err()), + "REQUEST_ID_PAYLOAD_MISMATCH" + ); + + // An old deletion replay must not delete a same-name replacement. + let deletion = DeleteWorkspaceRequest { + name: req.name.clone(), + request_id: uuid::Uuid::new_v4().to_string(), + ..Default::default() + }; + run(&restarted, authed_request(deletion.clone())) + .await + .unwrap(); + let replacement = run(&restarted, authed_request(create(&req.name))) + .await + .unwrap() + .into_inner(); + run(&restarted, authed_request(deletion)).await.unwrap(); + assert_eq!( + restarted + .store + .get_message::(replacement.workspace.as_ref().unwrap().object_id()) + .await + .unwrap(), + replacement.workspace + ); + assert_eq!( + reason(&run(&restarted, authed_request(req)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); + exercise_expiry_and_uncertainty(&restarted).await; + ordinary::tests::exercise_protected_backend(url).await; +} + +#[tokio::test] +async fn sqlite_concurrency_restart_name_reuse_expiry_and_uncertainty() { + let dir = tempfile::tempdir().unwrap(); + exercise_backend(&format!( + "sqlite://{}?mode=rwc", + dir.path().join("replay.db").display() + )) + .await; +} + +#[tokio::test] +async fn workspace_create_request_id_is_scoped_to_each_target() { + let state = test_server_state().await; + let service = crate::grpc::OpenShellService::new(state.clone()); + let first = create("scope-a"); + let second = CreateWorkspaceRequest { + name: "scope-b".into(), + ..first.clone() + }; + let mut originals = Vec::new(); + for req in [&first, &second] { + let response = service + .create_workspace(authed_request(req.clone())) + .await + .unwrap(); + assert!(response.metadata().get("openshell-replayed").is_none()); + let original = response.into_inner(); + assert_eq!( + original + .workspace + .as_ref() + .unwrap() + .metadata + .as_ref() + .unwrap() + .name, + req.name + ); + assert_eq!( + state + .store + .get_message_by_name::("", &req.name) + .await + .unwrap(), + original.workspace + ); + originals.push(original); + } + assert_ne!( + originals[0].workspace.as_ref().unwrap().object_id(), + originals[1].workspace.as_ref().unwrap().object_id() + ); + for (req, original) in [&first, &second].into_iter().zip(originals) { + let replay = service + .create_workspace(authed_request(req.clone())) + .await + .unwrap(); + assert_eq!(replay.metadata().get("openshell-replayed").unwrap(), "true"); + assert_eq!(replay.into_inner(), original); + let mut mismatch = req.clone(); + mismatch.labels.insert("changed".into(), "payload".into()); + assert_eq!( + reason( + &service + .create_workspace(authed_request(mismatch)) + .await + .unwrap_err() + ), + "REQUEST_ID_PAYLOAD_MISMATCH" + ); + } + let rows = state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap(); + assert_eq!(rows.len(), 2); + for row in rows { + let admission: Admission = serde_json::from_slice(&row.payload).unwrap(); + assert!(admission.workspace_id.is_none()); + } +} + +#[tokio::test] +async fn workspace_delete_request_id_is_scoped_to_each_target() { + let state = test_server_state().await; + let service = crate::grpc::OpenShellService::new(state.clone()); + let request_id = uuid::Uuid::new_v4().to_string(); + let mut requests = Vec::new(); + for name in ["scope-a", "scope-b"] { + service + .create_workspace(authed_request(CreateWorkspaceRequest { + name: name.into(), + ..Default::default() + })) + .await + .unwrap(); + requests.push(DeleteWorkspaceRequest { + name: name.into(), + request_id: request_id.clone(), + ..Default::default() + }); + } + for req in &requests { + let response = service + .delete_workspace(authed_request(req.clone())) + .await + .unwrap(); + assert!(response.metadata().get("openshell-replayed").is_none()); + assert_eq!( + response.get_ref().outcome, + openshell_core::proto::DeletionOutcome::Completed as i32 + ); + assert!( + state + .store + .get_message_by_name::("", &req.name) + .await + .unwrap() + .is_none() + ); + } + for req in requests { + // The target no longer exists; deletion replay must not require its UUID. + let replay = service.delete_workspace(authed_request(req)).await.unwrap(); + assert_eq!(replay.metadata().get("openshell-replayed").unwrap(), "true"); + assert_eq!( + replay.get_ref().outcome, + openshell_core::proto::DeletionOutcome::Completed as i32 + ); + } + let rows = state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap(); + assert_eq!(rows.len(), 2); + for row in rows { + let admission: Admission = serde_json::from_slice(&row.payload).unwrap(); + assert!(admission.workspace_id.is_none()); + } +} + +#[tokio::test] +#[ignore = "requires a disposable PostgreSQL database in OPENSHELL_REPLAY_TEST_DATABASE_URL"] +async fn postgres_concurrency_restart_name_reuse_expiry_and_uncertainty() { + let url = std::env::var("OPENSHELL_REPLAY_TEST_DATABASE_URL") + .expect("disposable PostgreSQL database URL"); + assert!(url.starts_with("postgres")); + let schema = format!("replay_{}", uuid::Uuid::new_v4().simple()); + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + sqlx::query(sqlx::AssertSqlSafe(format!("CREATE SCHEMA {schema}"))) + .execute(&pool) + .await + .unwrap(); + let mut scoped = url::Url::parse(&url).unwrap(); + scoped + .query_pairs_mut() + .append_pair("options", &format!("-csearch_path={schema}")); + exercise_backend(scoped.as_str()).await; + // Only the randomly named schema owned by this test is removed. + sqlx::query(sqlx::AssertSqlSafe(format!("DROP SCHEMA {schema} CASCADE"))) + .execute(&pool) + .await + .unwrap(); +} + +async fn exercise_expiry_and_uncertainty(state: &Arc) { + let req = create("expired-result"); + run(state, authed_request(req.clone())).await.unwrap(); + let hash = fingerprint(&req).unwrap(); + let rows = state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap(); + let row = rows + .into_iter() + .find(|row| { + serde_json::from_slice::(&row.payload) + .unwrap() + .payload_hash + == hash + }) + .unwrap(); + let mut expired: Admission = serde_json::from_slice(&row.payload).unwrap(); + expired.completed_at_ms = Some(current_time_ms() - SUCCESS_TTL_MS); + state + .store + .put_if( + OBJECT_TYPE, + &row.id, + &row.name, + &row.workspace, + &serde_json::to_vec(&expired).unwrap(), + None, + WriteCondition::MatchResourceVersion(row.resource_version), + ) + .await + .unwrap(); + let expired_row = state + .store + .get(OBJECT_TYPE, &row.id) + .await + .unwrap() + .unwrap(); + // Expiry admits a fresh attempt, which sees the existing resource. The + // resulting error remains unresolved even if the original resource is removed. + assert_eq!( + run(state, authed_request(req.clone())) + .await + .unwrap_err() + .code(), + Code::AlreadyExists + ); + assert!( + !state + .store + .delete_if(OBJECT_TYPE, &expired_row.id, expired_row.resource_version) + .await + .unwrap() + ); + let pending = state + .store + .get_by_name(OBJECT_TYPE, &row.workspace, &row.name) + .await + .unwrap() + .unwrap(); + assert_ne!(pending.id, expired_row.id); + let mut admission: Admission = serde_json::from_slice(&pending.payload).unwrap(); + admission.completed_at_ms = Some(0); // Even an old timestamp cannot expire an unresolved record. + state + .store + .put_if( + OBJECT_TYPE, + &pending.id, + &pending.name, + &pending.workspace, + &serde_json::to_vec(&admission).unwrap(), + None, + WriteCondition::MatchResourceVersion(pending.resource_version), + ) + .await + .unwrap(); + state + .store + .delete_by_name(Workspace::object_type(), "", &req.name) + .await + .unwrap(); + assert_eq!( + reason(&run(state, authed_request(req)).await.unwrap_err()), + "REQUEST_OUTCOME_UNCERTAIN" + ); + assert!(!prune_expired(&state.store, &row.workspace).await.unwrap()); +} + +#[tokio::test] +async fn replays_reauthorize_membership_and_admin_grants() { + let mut state = test_server_state().await; + Arc::get_mut(&mut state).unwrap().admin_role = "openshell-admin".into(); + let req = AddWorkspaceMemberRequest { + workspace: "default".into(), + principal_subject: "member".into(), + role: WorkspaceRole::Admin.into(), + request_id: uuid::Uuid::new_v4().to_string(), + }; + run(&state, authed_request(req.clone())).await.unwrap(); + let mut downgraded = authed_request(req.clone()); + let Principal::User(user) = downgraded.extensions_mut().get_mut::().unwrap() else { + unreachable!() + }; + user.identity.roles.clear(); + let caller = WorkspaceMember { + metadata: Some(ObjectMeta { + id: "caller".into(), + name: "dev-user".into(), + workspace: "default".into(), + ..Default::default() + }), + principal_subject: "dev-user".into(), + role: WorkspaceRole::Admin.into(), + }; + state.store.put_message(&caller).await.unwrap(); + assert_eq!( + run(&state, downgraded).await.unwrap_err().code(), + Code::PermissionDenied + ); + let remove = RemoveWorkspaceMemberRequest { + workspace: "default".into(), + principal_subject: "missing".into(), + allow_missing: true, + request_id: uuid::Uuid::new_v4().to_string(), + }; + let member_request = |req| { + let mut request = authed_request(req); + if let Principal::User(user) = request.extensions_mut().get_mut::().unwrap() { + user.identity.roles.clear(); + } + request + }; + run(&state, member_request(remove.clone())).await.unwrap(); + state + .store + .delete(WorkspaceMember::object_type(), "caller") + .await + .unwrap(); + assert_eq!( + run(&state, member_request(remove)) + .await + .unwrap_err() + .code(), + Code::PermissionDenied + ); +} + +#[tokio::test] +async fn template_replay_stores_only_reference_and_checks_original_version() { + let state = test_server_state().await; + // Delete is also routed through the public dispatch adapter. + let req = DeleteSandboxTemplateRequest { + name: "missing".into(), + workspace_scope: Some(workspace_selector("default")), + allow_missing: true, + request_id: uuid::Uuid::new_v4().to_string(), + }; + let service = crate::grpc::OpenShellService::new(state.clone()); + service + .delete_sandbox_template(authed_request(req.clone())) + .await + .unwrap(); + assert_eq!( + service + .delete_sandbox_template(authed_request(req)) + .await + .unwrap() + .metadata() + .get("openshell-replayed") + .unwrap(), + "true" + ); + let req = CreateSandboxTemplateRequest { + template: Some(SandboxWorkloadTemplate { + metadata: Some(ObjectMeta { + name: "template".into(), + annotations: HashMap::from([("private".into(), "sensitive-template-value".into())]), + ..Default::default() + }), + spec: Some(SandboxWorkloadTemplateSpec { + workload: Some(SandboxWorkloadConfig { + image: "registry.example.com/agent:latest".into(), + ..Default::default() + }), + ..Default::default() + }), + }), + workspace_scope: Some(workspace_selector("default")), + request_id: uuid::Uuid::new_v4().to_string(), + }; + let created = run(&state, authed_request(req.clone())) + .await + .unwrap() + .into_inner(); + assert_eq!( + created, + run(&state, authed_request(req.clone())) + .await + .unwrap() + .into_inner() + ); + for row in state + .store + .list_by_type_after(OBJECT_TYPE, None, 100) + .await + .unwrap() + { + assert!( + !String::from_utf8(row.payload) + .unwrap() + .contains("sensitive-template-value") + ); + } + let original = created.template.unwrap(); + state + .store + .update_message_cas::( + original.object_id(), + original.get_resource_version(), + |changed| { + changed.metadata.as_mut().unwrap().annotations.clear(); + }, + ) + .await + .unwrap(); + assert_eq!( + reason(&run(&state, authed_request(req)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); +} + +#[derive(Clone, PartialEq, Message)] +struct ControlledCreate { + #[prost(string, tag = "1")] + name: String, + #[prost(string, tag = "3")] + request_id: String, +} + +#[derive(Default)] +struct Control { + started: tokio::sync::Notify, + proceed: tokio::sync::Notify, + calls: AtomicUsize, + fail_after_effect: bool, +} + +#[tonic::async_trait] +impl Mutation for ControlledCreate { + type Output = CreateWorkspaceResponse; + const METHOD: &'static str = "CreateWorkspace"; + fn request_id(&self) -> &str { + &self.request_id + } + async fn authorize(&self, state: &ServerState, principal: &Principal) -> Result { + // Fault-injected execution must use the real adapter's admission key. + CreateWorkspaceRequest { + name: self.name.clone(), + ..Default::default() + } + .authorize(state, principal) + .await + } + async fn execute( + state: &Arc, + request: Request, + ) -> Result, Status> { + let control = request.extensions().get::>().unwrap().clone(); + control.calls.fetch_add(1, Ordering::SeqCst); + control.started.notify_one(); + control.proceed.notified().await; + let req = request.into_inner(); + let response = workspace::handle_create_workspace( + state, + Request::new(CreateWorkspaceRequest { + name: req.name, + request_id: req.request_id, + ..Default::default() + }), + ) + .await?; + if control.fail_after_effect { + return Err(Status::internal("simulated interruption after effect")); + } + Ok(response) + } + fn capture(response: &Response) -> Result { + resource_success(response.get_ref().workspace.as_ref()) + } + async fn restore(store: &Store, success: Success) -> Result { + Ok(CreateWorkspaceResponse { + workspace: Some(restore_resource(store, success).await?), + }) + } +} + +#[tokio::test] +async fn cancellation_keeps_owned_work_and_duplicate_cannot_take_over() { + let state = test_server_state().await; + let control = Arc::new(Control::default()); + let req = create("cancelled-client"); + let mut request = authed_request(ControlledCreate { + name: req.name.clone(), + request_id: req.request_id.clone(), + }); + request.extensions_mut().insert(control.clone()); + let worker_state = state.clone(); + let caller = tokio::spawn(async move { run(&worker_state, request).await }); + tokio::time::timeout(Duration::from_secs(5), control.started.notified()) + .await + .unwrap(); + caller.abort(); + assert_eq!( + reason(&run(&state, authed_request(req.clone())).await.unwrap_err()), + "REQUEST_OUTCOME_UNCERTAIN" + ); + control.proceed.notify_one(); + tokio::time::timeout(Duration::from_secs(5), async { + loop { + if run(&state, authed_request(req.clone())).await.is_ok() { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!(control.calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn quota_fails_closed_but_replays_and_expired_success_cleanup_still_work() { + let state = test_server_state().await; + let req = create("quota-replay"); + run(&state, authed_request(req.clone())).await.unwrap(); + let original = state + .store + .list_by_type_after(OBJECT_TYPE, None, 1) + .await + .unwrap() + .remove(0); + let pending = Admission { + protection: None, + format_version: 1, + payload_hash: "unused".into(), + workspace_id: None, + success: None, + completed_at_ms: None, + }; + let payload = serde_json::to_vec(&pending).unwrap(); + for i in 1..MAX_ADMISSIONS_PER_CALLER - 1 { + let id = format!("quota-{i}"); + state + .store + .create_if_workspace_count_below( + OBJECT_TYPE, + &id, + &id, + &original.workspace, + &payload, + None, + u64::from(MAX_ADMISSIONS_PER_CALLER), + ) + .await + .unwrap() + .unwrap(); + } + let (left, right) = tokio::join!( + run(&state, authed_request(create("quota-race-a"))), + run(&state, authed_request(create("quota-race-b"))) + ); + assert_eq!(usize::from(left.is_ok()) + usize::from(right.is_ok()), 1); + assert_eq!( + left.err().or_else(|| right.err()).unwrap().code(), + Code::ResourceExhausted + ); + let new_req = create("quota-new"); + assert_eq!( + run(&state, authed_request(new_req.clone())) + .await + .unwrap_err() + .code(), + Code::ResourceExhausted + ); + assert!( + state + .store + .get_message_by_name::("", &new_req.name) + .await + .unwrap() + .is_none() + ); + run(&state, authed_request(req)).await.unwrap(); + let mut expired: Admission = serde_json::from_slice(&original.payload).unwrap(); + expired.completed_at_ms = Some(0); + state + .store + .put_if( + OBJECT_TYPE, + &original.id, + &original.name, + &original.workspace, + &serde_json::to_vec(&expired).unwrap(), + None, + WriteCondition::MatchResourceVersion(original.resource_version), + ) + .await + .unwrap(); + run(&state, authed_request(new_req)).await.unwrap(); + assert_eq!( + state + .store + .count_in_workspace(OBJECT_TYPE, &original.workspace) + .await + .unwrap(), + u64::from(MAX_ADMISSIONS_PER_CALLER) + ); + assert!( + state + .store + .get(OBJECT_TYPE, "quota-1") + .await + .unwrap() + .is_some() + ); +} + +#[tokio::test] +async fn workspace_replacement_blocks_replay_without_reexecuting_member_removal() { + let state = test_server_state().await; + let workspace_req = create("workspace-reuse"); + run(&state, authed_request(workspace_req.clone())) + .await + .unwrap(); + let member = AddWorkspaceMemberRequest { + workspace: workspace_req.name.clone(), + principal_subject: "member".into(), + role: WorkspaceRole::User.into(), + ..Default::default() + }; + run(&state, authed_request(member.clone())).await.unwrap(); + let remove = RemoveWorkspaceMemberRequest { + workspace: workspace_req.name.clone(), + principal_subject: "member".into(), + request_id: uuid::Uuid::new_v4().to_string(), + ..Default::default() + }; + run(&state, authed_request(remove.clone())).await.unwrap(); + run( + &state, + authed_request(DeleteWorkspaceRequest { + name: workspace_req.name.clone(), + ..Default::default() + }), + ) + .await + .unwrap(); + run(&state, authed_request(create(&workspace_req.name))) + .await + .unwrap(); + let replacement = run(&state, authed_request(member)) + .await + .unwrap() + .into_inner() + .member + .unwrap(); + assert_eq!( + reason(&run(&state, authed_request(remove)).await.unwrap_err()), + "REQUEST_REPLAY_UNAVAILABLE" + ); + assert!( + state + .store + .get_message::(replacement.object_id()) + .await + .unwrap() + .is_some() + ); +} + +#[test] +fn replay_allowlist_remains_outside_interception_and_ids_have_reviewed_wire_tags() { + for (method, tag) in [ + ("CreateWorkspace", 3), + ("DeleteWorkspace", 3), + ("AddWorkspaceMember", 4), + ("RemoveWorkspaceMember", 4), + ("CreateSandboxTemplate", 4), + ("DeleteSandboxTemplate", 5), + ] { + assert!(!openshell_gateway_interceptors::routes::INTERCEPTABLE_METHODS.contains(&method)); + let descriptor = DESCRIPTORS + .get_message_by_name(&format!("openshell.v1.{method}Request")) + .unwrap(); + let field = descriptor.get_field_by_name("request_id").unwrap(); + assert_eq!(field.number(), tag); + assert_eq!(field.kind(), prost_reflect::Kind::String); + } +} + +#[tokio::test] +async fn unrelated_oidc_configuration_does_not_reset_mtls_admission_identity() { + let mut state = test_server_state().await; + let req = DeleteSandboxTemplateRequest { + name: "mtls-template".into(), + workspace_scope: Some(workspace_selector("default")), + allow_missing: true, + request_id: "550e8400-e29b-41d4-a716-446655440000".into(), + }; + let mtls_request = |req| { + let mut request = authed_request(req); + if let Principal::User(user) = request.extensions_mut().get_mut::().unwrap() { + user.identity.provider = IdentityProvider::Mtls; + } + request + }; + run(&state, mtls_request(req.clone())).await.unwrap(); + let row = state + .store + .list_by_type_after(OBJECT_TYPE, None, 1) + .await + .unwrap() + .remove(0); + assert_eq!( + row.workspace, + "_mutation/63247cf7f072797edfb9ca3c4290683b41ccaaae23712042f315de35a54067ce" + ); + assert_eq!( + row.name, + "ecfb83c89c4be0bd1b67aee42c7049243af89db2df01d762b880e155694ca028" + ); + let template = SandboxWorkloadTemplate { + metadata: Some(ObjectMeta { + id: "mtls-replacement".into(), + name: req.name.clone(), + workspace: "default".into(), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&template).await.unwrap(); + Arc::get_mut(&mut state).unwrap().config.oidc = Some(openshell_core::OidcConfig { + issuer: "https://new.example.com".into(), + dangerously_allow_insecure_http: false, + jwks_allowed_origins: Vec::new(), + audience: "openshell-cli".into(), + jwks_ttl_secs: 300, + roles_claim: String::new(), + admin_role: String::new(), + user_role: String::new(), + scopes_claim: String::new(), + }); + run(&state, mtls_request(req.clone())).await.unwrap(); + assert!( + state + .store + .get_message::(template.object_id()) + .await + .unwrap() + .is_some() + ); + // Same textual subject/UUID from a different provider is a separate caller. + run(&state, authed_request(req)).await.unwrap(); + assert!( + state + .store + .get_message::(template.object_id()) + .await + .unwrap() + .is_none() + ); +} + +#[tokio::test] +async fn restart_after_effect_without_success_persistence_never_reexecutes() { + let dir = tempfile::tempdir().unwrap(); + let url = format!( + "sqlite://{}?mode=rwc", + dir.path().join("interrupted.db").display() + ); + let state = state_for(Store::connect(&url).await.unwrap()).await; + let req = create("interrupted-effect"); + let control = Arc::new(Control { + fail_after_effect: true, + ..Default::default() + }); + control.proceed.notify_one(); + let mut request = authed_request(ControlledCreate { + name: req.name.clone(), + request_id: req.request_id.clone(), + }); + request.extensions_mut().insert(control.clone()); + assert_eq!( + run(&state, request).await.unwrap_err().code(), + Code::Internal + ); + let original: Workspace = state + .store + .get_message_by_name("", &req.name) + .await + .unwrap() + .unwrap(); + drop(state); + let restarted = state_for(Store::connect(&url).await.unwrap()).await; + assert_eq!( + reason( + &run(&restarted, authed_request(req.clone())) + .await + .unwrap_err() + ), + "REQUEST_OUTCOME_UNCERTAIN" + ); + assert_eq!(control.calls.load(Ordering::SeqCst), 1); + assert_eq!( + restarted + .store + .get_message_by_name::("", &req.name) + .await + .unwrap() + .unwrap(), + original + ); +} diff --git a/crates/openshell-server/src/grpc/mutation_tests.rs b/crates/openshell-server/src/grpc/mutation_tests.rs index 7cb14db25c..d1b135dccc 100644 --- a/crates/openshell-server/src/grpc/mutation_tests.rs +++ b/crates/openshell-server/src/grpc/mutation_tests.rs @@ -157,6 +157,7 @@ async fn allow_missing_does_not_hide_missing_parents_or_invalid_requests() { let err = provider::handle_delete_provider_refresh( &state, authed_request(DeleteProviderRefreshRequest { + request_id: String::new(), provider: "missing-parent".into(), credential_key: "API_KEY".into(), allow_missing: true, @@ -169,6 +170,7 @@ async fn allow_missing_does_not_hide_missing_parents_or_invalid_requests() { let err = workspace::handle_remove_workspace_member( &state, authed_request(RemoveWorkspaceMemberRequest { + request_id: String::new(), workspace: "missing-parent".into(), principal_subject: "missing".into(), allow_missing: true, diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index d986c5cba9..36afaf7aa6 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -51,11 +51,11 @@ use openshell_core::proto::{ GetSandboxPolicyStatusRequest, GetSandboxPolicyStatusResponse, GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, ListSandboxPoliciesRequest, ListSandboxPoliciesResponse, PolicyChunk, PolicyMergeOperation, - PolicySource, PolicyStatus, PushSandboxLogsRequest, PushSandboxLogsResponse, - RejectDraftChunkRequest, RejectDraftChunkResponse, ReportPolicyStatusRequest, - ReportPolicyStatusResponse, SandboxLogLine, SandboxPolicyRevision, SettingScope, SettingValue, - SubmitPolicyAnalysisRequest, SubmitPolicyAnalysisResponse, UndoDraftChunkRequest, - UndoDraftChunkResponse, UpdateConfigRequest, UpdateConfigResponse, + PolicySource, PolicyStatus, ProviderReadinessReason, PushSandboxLogsRequest, + PushSandboxLogsResponse, RejectDraftChunkRequest, RejectDraftChunkResponse, + ReportPolicyStatusRequest, ReportPolicyStatusResponse, SandboxLogLine, SandboxPolicyRevision, + SettingScope, SettingValue, SubmitPolicyAnalysisRequest, SubmitPolicyAnalysisResponse, + UndoDraftChunkRequest, UndoDraftChunkResponse, UpdateConfigRequest, UpdateConfigResponse, }; use openshell_core::proto::{ L7DenyRule, L7Rule, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, Provider, Sandbox, @@ -2499,6 +2499,16 @@ pub(super) async fn handle_get_sandbox_config( let sandbox = super::sandbox::fetch_and_authorize_sandbox(state, &principal, &sandbox_id).await?; + Ok(Response::new(load_sandbox_config(state, &sandbox).await?)) +} + +/// Resolve the same effective configuration for authenticated RPCs and trusted +/// readiness snapshots. Callers must authorize external access before entering. +pub(super) async fn load_sandbox_config( + state: &Arc, + sandbox: &Sandbox, +) -> Result { + let sandbox_id = sandbox.object_id().to_string(); let workspace = sandbox.object_workspace().to_string(); let sandbox_provider_names = sandbox .spec @@ -2710,7 +2720,7 @@ pub(super) async fn handle_get_sandbox_config( ) .await?; - Ok(Response::new(GetSandboxConfigResponse { + Ok(GetSandboxConfigResponse { policy, version, policy_hash, @@ -2727,7 +2737,12 @@ pub(super) async fn handle_get_sandbox_config( .as_str() .to_string(), extension_authentication_enabled: state.sandbox_jwt_issuer.is_some(), - })) + provider_attachment_epoch: sandbox + .spec + .as_ref() + .map(|spec| spec.provider_attachment_epoch.clone()) + .unwrap_or_default(), + }) } #[cfg(test)] @@ -3245,6 +3260,20 @@ pub(super) async fn handle_get_sandbox_provider_environment( .await .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; + Ok(Response::new( + load_sandbox_provider_environment(state, &sandbox, supports_static_credential_bindings) + .await?, + )) +} + +/// Materialize a privileged provider snapshot after the caller has authorized +/// access. Omission reasons remain separate from a legitimately empty snapshot. +pub(super) async fn load_sandbox_provider_environment( + state: &Arc, + sandbox: &Sandbox, + supports_static_credential_bindings: bool, +) -> Result { + let sandbox_id = sandbox.object_id().to_string(); let workspace = sandbox.object_workspace().to_string(); let spec = sandbox @@ -3267,7 +3296,7 @@ pub(super) async fn handle_get_sandbox_provider_environment( state.as_ref(), &provider_profile_catalog, &workspace, - &sandbox, + sandbox, &sandbox_id, ) .await?; @@ -3295,6 +3324,8 @@ pub(super) async fn handle_get_sandbox_provider_environment( ) .await?; + let mut readiness_reason = provider_environment.readiness_reason; + if supports_static_credential_bindings { let unbound_static_keys = provider_environment .static_credential_keys @@ -3306,6 +3337,9 @@ pub(super) async fn handle_get_sandbox_provider_environment( }) .cloned() .collect::>(); + if !unbound_static_keys.is_empty() { + readiness_reason = ProviderReadinessReason::CredentialsWithheld; + } for key in unbound_static_keys { warn!( sandbox_id = %sandbox_id, @@ -3319,6 +3353,9 @@ pub(super) async fn handle_get_sandbox_provider_environment( provider_environment.static_credential_keys.remove(&key); } } else { + if !provider_environment.static_credential_keys.is_empty() { + readiness_reason = ProviderReadinessReason::UnsupportedSupervisor; + } for key in &provider_environment.static_credential_keys { provider_environment.environment.remove(key); provider_environment.credential_expiration_times.remove(key); @@ -3351,14 +3388,17 @@ pub(super) async fn handle_get_sandbox_provider_environment( .map(|timestamp| (key, timestamp)) }) .collect(); - Ok(Response::new(GetSandboxProviderEnvironmentResponse { + Ok(GetSandboxProviderEnvironmentResponse { environment: provider_environment.environment, provider_env_revision, credential_expiration_times, dynamic_credentials: provider_environment.dynamic_credentials, static_credential_bindings: provider_environment.static_credential_bindings, non_secret_environment_keys, - })) + provider_attachment_epoch: spec.provider_attachment_epoch.clone(), + policy_hash: deterministic_policy_hash(&effective_policy), + readiness_reason: readiness_reason.into(), + }) } // --------------------------------------------------------------------------- @@ -3393,6 +3433,7 @@ async fn handle_update_config_inner( principal: &Principal, sandbox_caller: bool, ) -> Result, Status> { + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let req = request.into_inner(); validate_annotations(&req.annotations, "annotations")?; let workspace = if req.global { @@ -3402,6 +3443,7 @@ async fn handle_update_config_inner( )); } require_platform_admin(&state.admin_role, principal)?; + replay_facts.global()?; String::new() } else { let min_role = if sandbox_caller { @@ -3659,6 +3701,7 @@ async fn handle_update_config_inner( .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; let sandbox_id = sandbox.object_id().to_string(); + replay_facts.resource(&sandbox)?; let mut response_annotations = sandbox_metadata_annotations(&sandbox); if has_setting { @@ -5040,6 +5083,7 @@ async fn handle_approve_draft_chunk_inner( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let req = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -5068,6 +5112,7 @@ async fn handle_approve_draft_chunk_inner( .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; let sandbox_id = sandbox.object_id().to_string(); + replay_facts.resource(&sandbox)?; let chunk = state .store @@ -5195,6 +5240,7 @@ async fn handle_reject_draft_chunk_inner( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let req = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -5221,6 +5267,7 @@ async fn handle_reject_draft_chunk_inner( .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; let sandbox_id = sandbox.object_id().to_string(); + replay_facts.resource(&sandbox)?; let chunk = state .store @@ -5305,6 +5352,7 @@ async fn handle_approve_all_draft_chunks_inner( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let req = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -5330,6 +5378,7 @@ async fn handle_approve_all_draft_chunks_inner( .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; let sandbox_id = sandbox.object_id().to_string(); + replay_facts.resource(&sandbox)?; let pending_chunks = state .store @@ -5613,6 +5662,7 @@ pub(super) async fn handle_edit_draft_chunk( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let req = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -5642,6 +5692,7 @@ pub(super) async fn handle_edit_draft_chunk( .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; let sandbox_id = sandbox.object_id().to_string(); + replay_facts.resource(&sandbox)?; let chunk = state .store @@ -5694,6 +5745,7 @@ async fn handle_undo_draft_chunk_inner( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let req = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -5720,6 +5772,7 @@ async fn handle_undo_draft_chunk_inner( .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; let sandbox_id = sandbox.object_id().to_string(); + replay_facts.resource(&sandbox)?; let chunk = state .store @@ -5791,6 +5844,7 @@ pub(super) async fn handle_clear_draft_chunks( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let req = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -5814,6 +5868,7 @@ pub(super) async fn handle_clear_draft_chunks( .map_err(|e| Status::internal(format!("fetch sandbox failed: {e}")))? .ok_or_else(|| Status::not_found("sandbox not found"))?; let sandbox_id = sandbox.object_id().to_string(); + replay_facts.resource(&sandbox)?; let deleted = state .store @@ -9184,6 +9239,7 @@ mod tests { let error = handle_update_config( &state, with_user(Request::new(UpdateConfigRequest { + request_id: String::new(), global: true, setting_key: "log_level".to_string(), delete_setting: true, @@ -9278,6 +9334,7 @@ mod tests { let error = handle_update_config( &state, Request::new(UpdateConfigRequest { + request_id: String::new(), global: true, setting_key: "log_level".to_string(), delete_setting: true, @@ -11225,6 +11282,7 @@ mod tests { let error = super::super::sandbox::handle_attach_sandbox_provider( &state, authed_request(openshell_core::proto::AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "provider-ambiguity".to_string(), provider_name: "candidate-provider".to_string(), expected_resource_version: 0, @@ -11490,6 +11548,7 @@ mod tests { let response = handle_update_provider_profiles( &state, with_user(Request::new(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(updated_profile), source: "custom-policy.yaml".to_string(), @@ -11648,6 +11707,63 @@ mod tests { assert_eq!(v2_env.get("GITHUB_TOKEN"), Some(&"ghp-test".to_string())); } + #[tokio::test] + async fn provider_readiness_snapshot_uses_baseline_static_binding_contract() { + let state = test_server_state().await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + let mut sandbox = test_sandbox( + "sb-static-ready", + "static-ready", + test_policy_with_rule("sandbox_only", "sandbox.example.com"), + vec!["work-github".to_string()], + ); + let attachment_epoch = uuid::Uuid::new_v4().to_string(); + sandbox.spec.as_mut().unwrap().provider_attachment_epoch = attachment_epoch.clone(); + state.store.put_message(&sandbox).await.unwrap(); + + // Static binding support is sufficient to install this snapshot. The + // environment and policy must describe the same attachment authority. + let response = handle_get_sandbox_provider_environment( + &state, + with_user(Request::new(GetSandboxProviderEnvironmentRequest { + sandbox_id: "sb-static-ready".to_string(), + supports_static_credential_bindings: true, + })), + ) + .await + .unwrap() + .into_inner(); + let config = load_sandbox_config(&state, &sandbox).await.unwrap(); + + assert_eq!( + response.readiness_reason, + ProviderReadinessReason::Unspecified as i32 + ); + assert_eq!(response.provider_attachment_epoch, attachment_epoch); + assert_eq!( + response.provider_attachment_epoch, + config.provider_attachment_epoch + ); + assert_eq!(response.provider_env_revision, config.provider_env_revision); + assert_eq!(response.policy_hash, config.policy_hash); + assert!(response.environment.contains_key("GITHUB_TOKEN")); + assert!( + response + .static_credential_bindings + .contains_key("GITHUB_TOKEN") + ); + assert!( + !response + .non_secret_environment_keys + .iter() + .any(|key| key == "GITHUB_TOKEN") + ); + } + #[tokio::test] async fn provider_environment_withholds_static_credentials_from_legacy_supervisors() { use openshell_core::proto::GetSandboxProviderEnvironmentRequest; @@ -11682,6 +11798,10 @@ mod tests { assert!(!response.environment.contains_key("GITHUB_TOKEN")); assert!(response.static_credential_bindings.is_empty()); + assert_eq!( + response.readiness_reason, + ProviderReadinessReason::UnsupportedSupervisor as i32 + ); } #[tokio::test] @@ -11721,6 +11841,10 @@ mod tests { .into_inner(); assert!(!response.environment.contains_key("OPENAI_API_KEY")); + assert_eq!( + response.readiness_reason, + ProviderReadinessReason::CredentialsWithheld as i32 + ); assert!( !response .static_credential_bindings @@ -12542,6 +12666,7 @@ mod tests { handle_update_provider_profiles( &state, with_user(Request::new(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(rotated_profile), source: "custom-token.yaml".to_string(), @@ -12701,6 +12826,7 @@ mod tests { handle_attach_sandbox_provider( &state, with_user(Request::new(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "attach-lifecycle".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, @@ -12741,6 +12867,7 @@ mod tests { handle_detach_sandbox_provider( &state, authed_request(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "attach-lifecycle".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, @@ -12793,6 +12920,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { source: "custom-api.yaml".to_string(), profile: Some(ProviderProfile { @@ -12873,6 +13001,7 @@ mod tests { handle_attach_sandbox_provider( &state, with_user(Request::new(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "attach-lifecycle".to_string(), provider_name: "work-custom".to_string(), expected_resource_version: 0, @@ -12916,6 +13045,7 @@ mod tests { handle_detach_sandbox_provider( &state, authed_request(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "attach-lifecycle".to_string(), provider_name: "work-custom".to_string(), expected_resource_version: 0, @@ -13564,6 +13694,7 @@ mod tests { let skipped = handle_approve_all_draft_chunks( &state, with_user(Request::new(ApproveAllDraftChunksRequest { + request_id: String::new(), name: sandbox_name.to_string(), include_security_flagged: false, workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -13594,6 +13725,7 @@ mod tests { let approved = handle_approve_all_draft_chunks( &state, with_user(Request::new(ApproveAllDraftChunksRequest { + request_id: String::new(), name: sandbox_name.to_string(), include_security_flagged: true, workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -13672,6 +13804,7 @@ mod tests { handle_edit_draft_chunk( &state, with_user(Request::new(EditDraftChunkRequest { + request_id: String::new(), name: sandbox_name.to_string(), chunk_id: chunk_id.clone(), proposed_rule: Some(private_rule), @@ -13965,6 +14098,7 @@ mod tests { handle_edit_draft_chunk( &state, with_user(Request::new(EditDraftChunkRequest { + request_id: String::new(), name: sandbox_name.to_string(), chunk_id: chunk_id.clone(), proposed_rule: Some(finding_rule), @@ -14122,6 +14256,7 @@ mod tests { let approve = handle_approve_draft_chunk( &state, authed_request(ApproveDraftChunkRequest { + request_id: String::new(), name: sandbox_name.clone(), chunk_id: chunk_id.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -14174,6 +14309,7 @@ mod tests { let undo = handle_undo_draft_chunk( &state, authed_request(UndoDraftChunkRequest { + request_id: String::new(), name: sandbox_name.clone(), chunk_id: chunk_id.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -14240,6 +14376,7 @@ mod tests { let cleared = handle_clear_draft_chunks( &state, authed_request(ClearDraftChunksRequest { + request_id: String::new(), name: sandbox_name.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -14345,6 +14482,7 @@ mod tests { handle_reject_draft_chunk( &state, authed_request(RejectDraftChunkRequest { + request_id: String::new(), name: sandbox_name.clone(), chunk_id: chunk_id.clone(), reason: guidance.to_string(), @@ -15144,6 +15282,7 @@ mod tests { let error = handle_approve_draft_chunk( &state, with_user(Request::new(ApproveDraftChunkRequest { + request_id: String::new(), name: sandbox_name, chunk_id: chunk_id.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -16551,6 +16690,7 @@ mod tests { handle_approve_draft_chunk( &state, authed_request(ApproveDraftChunkRequest { + request_id: String::new(), name: sandbox_name, chunk_id, workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -16914,6 +17054,7 @@ mod tests { handle_reject_draft_chunk( &state, authed_request(RejectDraftChunkRequest { + request_id: String::new(), name: sandbox_name, chunk_id: second.accepted_chunk_ids[0].clone(), reason: "redraft test".to_string(), @@ -17383,6 +17524,7 @@ mod tests { handle_reject_draft_chunk( &state, authed_request(RejectDraftChunkRequest { + request_id: String::new(), name: sandbox_name.clone(), chunk_id: chunk_id.clone(), reason: "scope too broad".to_string(), @@ -17397,6 +17539,7 @@ mod tests { handle_approve_draft_chunk( &state, authed_request(ApproveDraftChunkRequest { + request_id: String::new(), name: sandbox_name.clone(), chunk_id: chunk_id.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -17411,6 +17554,7 @@ mod tests { handle_undo_draft_chunk( &state, authed_request(UndoDraftChunkRequest { + request_id: String::new(), name: sandbox_name.clone(), chunk_id: chunk_id.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -17554,6 +17698,7 @@ mod tests { let approve_err = handle_approve_draft_chunk( &state, authed_request(ApproveDraftChunkRequest { + request_id: String::new(), name: other_name.clone(), chunk_id: chunk_id.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -17569,6 +17714,7 @@ mod tests { let reject_err = handle_reject_draft_chunk( &state, authed_request(RejectDraftChunkRequest { + request_id: String::new(), name: other_name.clone(), chunk_id: chunk_id.clone(), reason: "wrong sandbox".to_string(), @@ -17584,6 +17730,7 @@ mod tests { let edit_err = handle_edit_draft_chunk( &state, authed_request(EditDraftChunkRequest { + request_id: String::new(), name: other_name.clone(), chunk_id: chunk_id.clone(), proposed_rule: Some(proposed_rule.clone()), @@ -17599,6 +17746,7 @@ mod tests { handle_approve_draft_chunk( &state, authed_request(ApproveDraftChunkRequest { + request_id: String::new(), name: sandbox_a.object_name().to_string(), chunk_id: chunk_id.clone(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -17613,6 +17761,7 @@ mod tests { let undo_err = handle_undo_draft_chunk( &state, authed_request(UndoDraftChunkRequest { + request_id: String::new(), name: other_name, chunk_id, workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -19705,6 +19854,7 @@ mod tests { let response = handle_update_config( &state, authed_request(UpdateConfigRequest { + request_id: String::new(), name: "test-sandbox".to_string(), policy: Some(new_policy), setting_key: String::new(), @@ -19803,6 +19953,7 @@ mod tests { let response = handle_update_config( &state, authed_request(UpdateConfigRequest { + request_id: String::new(), name: "annotated-backfill".to_string(), policy: Some(ProtoSandboxPolicy::default()), setting_key: String::new(), @@ -20835,6 +20986,7 @@ mod tests { let err = handle_update_config( &state, authed_request(UpdateConfigRequest { + request_id: String::new(), name: "test-sandbox".to_string(), policy: Some(new_policy), setting_key: String::new(), @@ -20936,6 +21088,7 @@ mod tests { handle_update_config( &state_clone, authed_request(UpdateConfigRequest { + request_id: String::new(), name: "test-sandbox".to_string(), policy: Some(new_policy), setting_key: String::new(), diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 21e2b3c18c..5936bc31a6 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -50,7 +50,7 @@ const GATEWAY_SPIFFE_WORKLOAD_API_SOCKET: &str = "OPENSHELL_GATEWAY_SPIFFE_WORKL /// response. Key names are preserved so callers can display credential counts /// and key listings. Internal server paths (sandbox env /// injection) read credentials from the store directly and are unaffected. -fn redact_provider_credentials(mut provider: Provider) -> Provider { +pub(super) fn redact_provider_credentials(mut provider: Provider) -> Provider { for value in provider.credentials.values_mut() { *value = "REDACTED".to_string(); } @@ -66,6 +66,9 @@ fn redact_provider_credentials(mut provider: Provider) -> Provider { #[derive(Debug, Clone, Default, PartialEq)] pub(super) struct ProviderEnvironment { + /// A closed reason for omitted injectable material. An empty environment + /// alone cannot distinguish successful revocation from withheld authority. + pub readiness_reason: openshell_core::proto::ProviderReadinessReason, pub environment: HashMap, pub credential_expiration_times: HashMap, pub dynamic_credentials: HashMap, @@ -455,7 +458,6 @@ async fn update_provider_record_validating( candidate.object_name(), candidate.object_workspace(), candidate.object_id(), - &removed_credential_handles, &updated_credential_values, &existing_handles, ) @@ -464,9 +466,6 @@ async fn update_provider_record_validating( candidate.credential_handles.remove(key); candidate.credentials.remove(key); } - for key in credential_update.deferred_store_values.keys() { - candidate.credentials.remove(key); - } if credentials.is_some_and(crate::credentials::CredentialRuntime::stores_provider_credentials) { for key in updated_credential_values.keys() { candidate.credentials.remove(key); @@ -533,16 +532,25 @@ async fn update_provider_record_validating( } }; - finish_provider_credential_update( + // The provider CAS already excludes these handles. Keep the committed + // result and its receipts available if retirement fails; the unused + // backend objects still require cleanup. + if let Err(err) = finish_provider_credential_update( credentials, candidate.object_name(), candidate.object_workspace(), candidate.object_id(), credential_update, &removed_credential_handles, - &existing_handles, ) - .await?; + .await + { + warn!( + provider_name = %candidate.object_name(), + code = ?err.code(), + "failed to retire unused provider credentials after publication" + ); + } // Update resource_version from successful write if let Some(metadata) = candidate.metadata.as_mut() { @@ -784,16 +792,17 @@ fn credential_handles_removed_by_update( #[derive(Debug, Clone, Default)] struct ProviderCredentialUpdate { pre_stored_handles: HashMap, - deferred_store_values: HashMap, replaced_handles: HashMap, } +// Each candidate owns distinct backend objects before its provider CAS. A +// published resource version therefore identifies fully stored credentials, +// and a concurrent loser cannot overwrite the winner's credential values. async fn prepare_provider_credential_update( credentials: Option<&crate::credentials::CredentialRuntime>, provider_name: &str, workspace: &str, provider_id: &str, - _removed_handles: &HashMap, updated_values: &HashMap, existing_handles: &HashMap, ) -> Result { @@ -804,42 +813,41 @@ async fn prepare_provider_credential_update( return Ok(ProviderCredentialUpdate::default()); } - let mut update = ProviderCredentialUpdate::default(); - let mut values_requiring_new_handles = HashMap::new(); - for (credential_key, value) in updated_values { - match existing_handles.get(credential_key) { - Some(existing_handle) if credentials.storage_owns_handle(existing_handle) => { - update - .deferred_store_values - .insert(credential_key.clone(), value.clone()); - } - Some(replaced_handle) => { - values_requiring_new_handles.insert(credential_key.clone(), value.clone()); - update - .replaced_handles - .insert(credential_key.clone(), replaced_handle.clone()); - } - None => { - values_requiring_new_handles.insert(credential_key.clone(), value.clone()); - } - } - } - - if !values_requiring_new_handles.is_empty() { - update.pre_stored_handles = credentials - .store_provider_credentials( - provider_name, - workspace, - provider_id, - &values_requiring_new_handles, - &HashMap::new(), + let object_id = uuid::Uuid::new_v4().to_string(); + let pre_stored_handles = credentials + .store_provider_credentials_with_object_id( + provider_name, + workspace, + provider_id, + &object_id, + updated_values, + &HashMap::new(), + ) + .await + .map_err(|err| { + Status::new( + err.code(), + "credential storage failed before provider publication", ) - .await?; - } + })?; + let replaced_handles = updated_values + .keys() + .filter_map(|key| { + existing_handles + .get(key) + .map(|handle| (key.clone(), handle.clone())) + }) + .collect(); - Ok(update) + Ok(ProviderCredentialUpdate { + pre_stored_handles, + replaced_handles, + }) } +// Retire only handles replaced by the successful provider CAS. Readers of an +// older record can fail resolution after retirement, but cannot resolve its +// handles to credential values from a different provider resource version. async fn finish_provider_credential_update( credentials: Option<&crate::credentials::CredentialRuntime>, provider_name: &str, @@ -847,7 +855,6 @@ async fn finish_provider_credential_update( provider_id: &str, update: ProviderCredentialUpdate, removed_handles: &HashMap, - existing_handles: &HashMap, ) -> Result<(), Status> { let Some(credentials) = credentials else { return Ok(()); @@ -856,18 +863,6 @@ async fn finish_provider_credential_update( return Ok(()); } - if !update.deferred_store_values.is_empty() { - credentials - .store_provider_credentials( - provider_name, - workspace, - provider_id, - &update.deferred_store_values, - existing_handles, - ) - .await?; - } - let mut handles_to_delete = removed_handles.clone(); handles_to_delete.extend(update.replaced_handles); if !handles_to_delete.is_empty() { @@ -878,17 +873,21 @@ async fn finish_provider_credential_update( provider_id, &handles_to_delete, ) - .await?; + .await + .map_err(|err| { + Status::new( + err.code(), + "credential retirement failed after provider publication", + ) + })?; } Ok(()) } -// TODO(credential-drivers): A gateway crash between CAS success and -// finish_provider_credential_update leaves replaced/removed credential handles -// orphaned in the backing store. This best-effort cleanup only covers pre-CAS -// failures. A background reconciliation loop should be added to detect and -// reclaim orphaned handles. +// A failed CAS never owns the published handles. Best-effort cleanup removes +// only this candidate's staged objects; a crash may leave unused backend objects +// but cannot change the credential data named by the committed provider record. async fn cleanup_pre_stored_provider_credentials( credentials: Option<&crate::credentials::CredentialRuntime>, provider_name: &str, @@ -908,7 +907,7 @@ async fn cleanup_pre_stored_provider_credentials( { warn!( provider_name = %provider_name, - error = %err, + code = ?err.code(), "failed to clean up staged provider credentials after provider update failure" ); } @@ -1128,6 +1127,7 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin let mut expires = HashMap::new(); let mut static_credential_bindings = HashMap::new(); let mut static_credential_keys = HashSet::new(); + let mut readiness_reason = openshell_core::proto::ProviderReadinessReason::Unspecified; let now_ms = crate::persistence::current_time_ms(); validate_provider_environment_records_unique_at(store, catalog, records, now_ms).await?; let registry = openshell_providers::ProviderRegistry::new(); @@ -1209,6 +1209,8 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin key = %key, "withholding provider credential not declared by resolved profile" ); + readiness_reason = + openshell_core::proto::ProviderReadinessReason::CredentialsWithheld; continue; } if is_non_injectable_provider_credential(provider, key) @@ -1232,6 +1234,8 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin key = %key, "withholding static provider credential from endpointless profile" ); + readiness_reason = + openshell_core::proto::ProviderReadinessReason::CredentialsWithheld; continue; } let expires_at_ms = provider @@ -1248,6 +1252,8 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin expires_at_ms, "skipping expired provider credential" ); + readiness_reason = + openshell_core::proto::ProviderReadinessReason::CredentialExpired; continue; } expires.entry(key.clone()).or_insert(expires_at_ms); @@ -1283,6 +1289,15 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin let resolved_refs = credentials .resolve_provider_handles(provider, now_ms) .await?; + // Expired handles are removed by the credential runtime before values + // reach this loop. Preserve omission evidence without exposing handles. + if provider.credential_handles.keys().any(|key| { + !is_non_injectable_provider_credential(provider, key) + && !broker_only_credential_keys.contains(key) + && !resolved_refs.values.contains_key(key) + }) { + readiness_reason = openshell_core::proto::ProviderReadinessReason::CredentialExpired; + } for (key, value) in resolved_refs.values { if accepted_stored_credential_keys .as_ref() @@ -1293,6 +1308,8 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin key = %key, "withholding provider credential handle not declared by resolved profile" ); + readiness_reason = + openshell_core::proto::ProviderReadinessReason::CredentialsWithheld; continue; } if is_non_injectable_provider_credential(provider, &key) @@ -1312,6 +1329,8 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin key = %key, "withholding static provider credential handle from endpointless profile" ); + readiness_reason = + openshell_core::proto::ProviderReadinessReason::CredentialsWithheld; continue; } if let Some(expires_at_ms) = resolved_refs.expires_at_ms.get(&key).copied() { @@ -1356,6 +1375,7 @@ pub(super) async fn resolve_provider_environment_from_records_with_policy_bindin } Ok(ProviderEnvironment { + readiness_reason, environment: env, credential_expiration_times: expires, dynamic_credentials: resolve_dynamic_credentials_from_records(catalog, records), @@ -2503,6 +2523,7 @@ pub(super) async fn handle_create_provider( ); Ok(Response::new(ProviderResponse { provider: Some(provider), + ..Default::default() })) } Err(err) => { @@ -2537,6 +2558,7 @@ pub(super) async fn handle_get_provider( Ok(Response::new(ProviderResponse { provider: Some(provider), + ..Default::default() })) } @@ -2689,6 +2711,7 @@ pub(super) async fn handle_import_provider_profiles( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let request = request.into_inner(); let workspace = authorize_and_resolve_profile_workspace( state, @@ -2758,6 +2781,7 @@ pub(super) async fn handle_import_provider_profiles( if let Some(metadata) = stored.metadata.as_mut() { metadata.resource_version = result.resource_version; } + replay_facts.resource(&stored)?; let resource_version = stored_profile_resource_version(&stored); imported.push(profile_response_payload( stored.profile.unwrap_or_default(), @@ -2777,6 +2801,7 @@ pub(super) async fn handle_update_provider_profiles( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let request = request.into_inner(); let workspace = authorize_and_resolve_profile_workspace( state, @@ -2891,6 +2916,7 @@ pub(super) async fn handle_update_provider_profiles( if let Some(metadata) = stored.metadata.as_mut() { metadata.resource_version = result.resource_version; } + replay_facts.resource(&stored)?; let resource_version = stored_profile_resource_version(&stored); let profile = profile_response_payload(stored.profile.unwrap_or_default(), resource_version); @@ -3751,6 +3777,13 @@ pub(super) async fn handle_update_provider( if state.credentials.stores_provider_credentials() && !provider.credentials.is_empty() { state.compute.ensure_workspace(&workspace).await?; } + // Freeze this operation's target identities before updating authority. + // Attachments made later are separate operations; frozen attachment epochs + // prevent an intervening detach/reattach from satisfying an older receipt. + let targets = + sandboxes_using_provider_records(state.store.as_ref(), &workspace, provider.object_name()) + .await?; + let mutation_id = uuid::Uuid::new_v4().to_string(); let catalog = state .provider_profile_sources .snapshot_catalog(state.store.as_ref(), &workspace) @@ -3766,6 +3799,24 @@ pub(super) async fn handle_update_provider( .await; match result { Ok(provider) => { + let provider_version = provider + .metadata + .as_ref() + .map_or(0, |metadata| metadata.resource_version); + let mut target_receipts = Vec::with_capacity(targets.len()); + for sandbox in &targets { + target_receipts.push( + super::provider_readiness::record_provider_mutation( + state, + sandbox, + provider.object_name(), + openshell_core::proto::ProviderMutationKind::Update, + Some((provider.object_id(), provider_version)), + &mutation_id, + ) + .await?, + ); + } emit_provider_lifecycle( &provider.r#type, LifecycleOperation::Update, @@ -3773,6 +3824,8 @@ pub(super) async fn handle_update_provider( ); Ok(Response::new(ProviderResponse { provider: Some(provider), + target_receipts, + mutation_id, })) } Err(err) => { @@ -4331,6 +4384,7 @@ pub(super) async fn handle_configure_provider_refresh( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let request = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -4729,6 +4783,7 @@ pub(super) async fn handle_configure_provider_refresh( .await?; } + replay_facts.refresh(&state_record)?; Ok(Response::new(ConfigureProviderRefreshResponse { status: Some(crate::provider_refresh::refresh_status_from_state( &state_record, @@ -4741,6 +4796,7 @@ pub(super) async fn handle_rotate_provider_credential( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + let replay_facts = super::mutation_replay::ordinary::Facts::from_request(&request); let request = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -4771,6 +4827,7 @@ pub(super) async fn handle_rotate_provider_credential( ) .await?; + replay_facts.refresh(&refresh_state)?; Ok(Response::new(RotateProviderCredentialResponse { status: Some(crate::provider_refresh::refresh_status_from_state( &refresh_state, @@ -5220,6 +5277,7 @@ mod tests { handle_import_provider_profiles( state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(profile), source: format!("{id}.yaml"), @@ -5360,6 +5418,7 @@ mod tests { let response = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(profile), source: "grant-new.yaml".to_string(), @@ -5388,6 +5447,7 @@ mod tests { handle_import_provider_profiles( &task_state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("guarded-import")), source: "guarded-import.yaml".to_string(), @@ -5441,6 +5501,7 @@ mod tests { let response = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(updated_profile.clone()), source: "custom-api.yaml".to_string(), @@ -5486,6 +5547,7 @@ mod tests { let built_in = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(custom_profile("github")), source: "github.yaml".to_string(), @@ -5508,6 +5570,7 @@ mod tests { let missing = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(custom_profile("missing-custom")), source: "missing-custom.yaml".to_string(), @@ -5540,6 +5603,7 @@ mod tests { let missing_version = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(custom_profile("custom-api")), source: "custom-api.yaml".to_string(), @@ -5563,6 +5627,7 @@ mod tests { let stale_error = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(stale_profile), source: "custom-api.yaml".to_string(), @@ -5612,6 +5677,7 @@ mod tests { let response = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(edited_payload), source: "profile-a.yaml".to_string(), @@ -5696,6 +5762,7 @@ mod tests { let response = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(profile), source: "grant-updated.yaml".to_string(), @@ -5880,6 +5947,7 @@ mod tests { handle_import_provider_profiles( state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(profile), source: format!("{id}.yaml"), @@ -6108,6 +6176,7 @@ mod tests { let response = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("custom-api")), source: "custom-api.yaml".to_string(), @@ -6179,6 +6248,7 @@ mod tests { source: "duration-api.proto".to_string(), }], workspace: "default".to_string(), + request_id: String::new(), }), ) .await @@ -6234,6 +6304,7 @@ mod tests { source: "invalid-duration-api.proto".to_string(), }], workspace: "default".to_string(), + request_id: String::new(), }), ) .await @@ -6260,6 +6331,7 @@ mod tests { let imported = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(initial_profile), source: "fanout.yaml".to_string(), @@ -6328,6 +6400,7 @@ mod tests { let response = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), profile: Some(ProviderProfileImportItem { profile: Some(conflicting_profile), source: "fanout.yaml".to_string(), @@ -6368,6 +6441,7 @@ mod tests { let response = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("github")), source: "github.yaml".to_string(), @@ -6396,6 +6470,7 @@ mod tests { let response = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("custom-llm")), source: "custom-llm.yaml".to_string(), @@ -6431,6 +6506,7 @@ mod tests { let response = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ ProviderProfileImportItem { profile: Some(custom_profile(" alex-api ")), @@ -6469,6 +6545,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("alex-api")), source: "alex-api.yaml".to_string(), @@ -6496,6 +6573,7 @@ mod tests { let deleted = handle_delete_provider_profile( &state, authed_request(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: false, id: " Alex-API ".to_string(), workspace: "default".to_string(), @@ -6517,6 +6595,7 @@ mod tests { let response = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ ProviderProfileImportItem { profile: Some(custom_profile("bulk-one")), @@ -6566,6 +6645,7 @@ mod tests { let response = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(ProviderProfile { id: "advanced-api".to_string(), @@ -6693,6 +6773,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("scoped-lint")), source: "scoped-lint.yaml".to_string(), @@ -6730,6 +6811,7 @@ mod tests { crate::grpc::workspace::handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "alpha".to_string(), labels: HashMap::new(), }), @@ -6765,6 +6847,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("custom-api")), source: "custom-api.yaml".to_string(), @@ -6778,6 +6861,7 @@ mod tests { let builtin_err = handle_delete_provider_profile( &state, authed_request(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: false, id: "github".to_string(), workspace: "default".to_string(), @@ -6819,6 +6903,7 @@ mod tests { let in_use_err = handle_delete_provider_profile( &state, authed_request(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: false, id: "custom-api".to_string(), workspace: "default".to_string(), @@ -6832,6 +6917,7 @@ mod tests { let attached = super::super::sandbox::handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "sandbox-custom".to_string(), provider_name: "custom-provider".to_string(), expected_resource_version: 0, @@ -6871,6 +6957,7 @@ mod tests { let err = handle_delete_provider_profile( &state, authed_request(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: false, id: "global-custom".to_string(), workspace: String::new(), @@ -6920,6 +7007,7 @@ mod tests { let response = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -7015,6 +7103,7 @@ mod tests { handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -7087,6 +7176,7 @@ mod tests { let deleted = handle_delete_provider_refresh( &state, authed_request(DeleteProviderRefreshRequest { + request_id: String::new(), allow_missing: false, provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), @@ -7153,6 +7243,7 @@ mod tests { .await .unwrap(); let request = |client_secret: &str| ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "configure-conflict".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -7275,6 +7366,7 @@ mod tests { first_state.credentials.clone(), )); let request = |client_secret: &str| ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "configure-create-race".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -7406,6 +7498,7 @@ mod tests { handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "provider-a".to_string(), credential_key: "REFRESH_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -7490,6 +7583,7 @@ mod tests { handle_delete_provider_refresh( &state, authed_request(DeleteProviderRefreshRequest { + request_id: String::new(), allow_missing: false, provider: "provider-a".to_string(), credential_key: "REFRESH_TOKEN".to_string(), @@ -7549,6 +7643,7 @@ mod tests { let response = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "vertex-sa".to_string(), credential_key: "GOOGLE_VERTEX_AI_SERVICE_ACCOUNT_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::GoogleServiceAccountJwt as i32, @@ -7622,6 +7717,7 @@ mod tests { handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -7673,6 +7769,7 @@ mod tests { let deleted = handle_delete_provider_refresh( &state, authed_request(DeleteProviderRefreshRequest { + request_id: String::new(), allow_missing: false, provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), @@ -7735,6 +7832,7 @@ mod tests { handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "aws-delete".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -7794,6 +7892,7 @@ mod tests { handle_delete_provider_refresh( &state, authed_request(DeleteProviderRefreshRequest { + request_id: String::new(), allow_missing: false, provider: "aws-delete".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), @@ -7985,6 +8084,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "refreshing-graph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -8067,6 +8167,7 @@ mod tests { handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "first-graph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -8088,6 +8189,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "second-graph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -8149,6 +8251,7 @@ mod tests { let endpoint_override = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -8176,6 +8279,7 @@ mod tests { let missing_material = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -8232,6 +8336,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "msgraph".to_string(), credential_key: "MS_GRAPH_ACCESS_TOKEN".to_string(), strategy: strategy as i32, @@ -8265,6 +8370,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("custom-api")), source: "custom-api.yaml".to_string(), @@ -8278,6 +8384,7 @@ mod tests { let deleted = handle_delete_provider_profile( &state, authed_request(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: false, id: "custom-api".to_string(), workspace: "default".to_string(), @@ -8318,6 +8425,7 @@ mod tests { handle_delete_provider_profile( &task_state, authed_request(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: false, id: "guarded-delete".to_string(), workspace: "default".to_string(), @@ -8351,6 +8459,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("guarded-create")), source: "guarded-create.yaml".to_string(), @@ -8370,6 +8479,7 @@ mod tests { handle_create_provider( &task_state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -8575,7 +8685,7 @@ mod tests { } #[tokio::test] - async fn update_provider_record_overwrites_credentials_with_runtime() { + async fn update_provider_credential_publication_waits_for_staged_storage() { let store = test_store().await; let config = openshell_core::Config::new(None).with_credential_drivers(["test-static"]); let credentials = crate::credentials::CredentialRuntime::from_config(&config).unwrap(); @@ -8605,16 +8715,40 @@ mod tests { .handle .clone(); - let updated = update_provider_record_validating( + let (store_hit, release_store) = credentials.gate_next_store(); + let update = update_provider_record_validating( &store, "default", &catalog, provider_with_credential_value("openai-local", "openai", "OPENAI_API_KEY", "sk-second"), &[], Some(&credentials), - ) - .await - .unwrap(); + ); + let inspect_while_storage_pending = async { + store_hit.await.unwrap(); + let published = store + .get_message_by_name::("default", "openai-local") + .await + .unwrap() + .unwrap(); + assert_eq!(published, stored_first); + let resolved = resolve_provider_environment_with_credentials( + &store, + &catalog, + "default", + &["openai-local".to_string()], + &credentials, + ) + .await + .unwrap(); + assert_eq!( + resolved.get("OPENAI_API_KEY").map(String::as_str), + Some("sk-first") + ); + release_store.send(()).unwrap(); + }; + let (updated, ()) = tokio::join!(update, inspect_while_storage_pending); + let updated = updated.unwrap(); assert_eq!( updated .credentials @@ -8630,13 +8764,18 @@ mod tests { .unwrap() .unwrap(); assert!(stored_second.credentials.is_empty()); - assert_eq!( + assert_ne!( stored_second .credential_handles .get("OPENAI_API_KEY") .map(|handle| handle.handle.as_str()), Some(first_handle.as_str()) ); + assert_eq!( + stored_second.metadata.as_ref().unwrap().resource_version, + stored_first.metadata.as_ref().unwrap().resource_version + 1 + ); + assert_eq!(credentials.stored_credential_count(), Some(1)); let result = resolve_provider_environment_with_credentials( &store, @@ -8650,6 +8789,376 @@ mod tests { assert_eq!(result.get("OPENAI_API_KEY"), Some(&"sk-second".to_string())); } + #[tokio::test] + async fn update_provider_credential_store_failure_preserves_published_revision() { + let store = test_store().await; + let config = openshell_core::Config::new(None).with_credential_drivers(["test-static"]); + let credentials = crate::credentials::CredentialRuntime::from_config(&config).unwrap(); + let catalog = ProviderProfileSources::with_default_sources() + .snapshot_catalog(&store, "default") + .await + .unwrap(); + create_provider_record_validating( + &store, + "default", + &catalog, + provider_with_credential_value("openai-local", "openai", "OPENAI_API_KEY", "sk-first"), + Some(&credentials), + ) + .await + .unwrap(); + let before = store + .get_message_by_name::("default", "openai-local") + .await + .unwrap() + .unwrap(); + credentials.fail_next_store(); + + let error = update_provider_record_validating( + &store, + "default", + &catalog, + provider_with_credential_value("openai-local", "openai", "OPENAI_API_KEY", "sk-failed"), + &[], + Some(&credentials), + ) + .await + .unwrap_err(); + + assert_eq!(error.code(), Code::Unavailable); + assert_eq!( + error.message(), + "credential storage failed before provider publication" + ); + let after = store + .get_message_by_name::("default", "openai-local") + .await + .unwrap() + .unwrap(); + assert_eq!(after, before); + assert_eq!(credentials.stored_credential_count(), Some(1)); + let resolved = resolve_provider_environment_with_credentials( + &store, + &catalog, + "default", + &["openai-local".to_string()], + &credentials, + ) + .await + .unwrap(); + assert_eq!( + resolved.get("OPENAI_API_KEY").map(String::as_str), + Some("sk-first") + ); + } + + #[tokio::test] + async fn update_provider_credential_publication_cas_loser_preserves_winner() { + let store = test_store().await; + let config = openshell_core::Config::new(None).with_credential_drivers(["test-static"]); + let credentials = crate::credentials::CredentialRuntime::from_config(&config).unwrap(); + let catalog = ProviderProfileSources::with_default_sources() + .snapshot_catalog(&store, "default") + .await + .unwrap(); + create_provider_record_validating( + &store, + "default", + &catalog, + provider_with_credential_value("openai-local", "openai", "OPENAI_API_KEY", "sk-first"), + Some(&credentials), + ) + .await + .unwrap(); + let initial = store + .get_message_by_name::("default", "openai-local") + .await + .unwrap() + .unwrap(); + let (store_hit, release_store) = credentials.gate_next_store(); + + // Pause one writer after it reads the provider version. A second writer + // publishes while it waits, so only a database CAS can reject the loser. + let loser = update_provider_record_validating( + &store, + "default", + &catalog, + provider_with_credential_value("openai-local", "openai", "OPENAI_API_KEY", "sk-loser"), + &[], + Some(&credentials), + ); + let winner = async { + store_hit.await.unwrap(); + let result = update_provider_record_validating( + &store, + "default", + &catalog, + provider_with_credential_value( + "openai-local", + "openai", + "OPENAI_API_KEY", + "sk-winner", + ), + &[], + Some(&credentials), + ) + .await; + release_store.send(()).unwrap(); + result + }; + let (loser_result, winner_result) = tokio::join!(loser, winner); + + assert_eq!(loser_result.unwrap_err().code(), Code::Aborted); + winner_result.unwrap(); + let published = store + .get_message_by_name::("default", "openai-local") + .await + .unwrap() + .unwrap(); + assert_eq!( + published.metadata.as_ref().unwrap().resource_version, + initial.metadata.as_ref().unwrap().resource_version + 1 + ); + assert_eq!(credentials.stored_credential_count(), Some(1)); + let resolved = resolve_provider_environment_with_credentials( + &store, + &catalog, + "default", + &["openai-local".to_string()], + &credentials, + ) + .await + .unwrap(); + assert_eq!( + resolved.get("OPENAI_API_KEY").map(String::as_str), + Some("sk-winner") + ); + } + + #[tokio::test] + async fn update_provider_receipts_freeze_targets_before_credential_publication() { + let state = test_server_state().await; + handle_create_provider( + &state, + authed_request(CreateProviderRequest { + request_id: String::new(), + provider: Some(provider_with_credential_value( + "openai-local", + "openai", + "OPENAI_API_KEY", + "sk-first", + )), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + .unwrap(); + for name in ["first", "second", "late"] { + state + .store + .put_message(&Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: name.to_string(), + name: name.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + providers: if name == "late" { + Vec::new() + } else { + vec!["openai-local".to_string()] + }, + provider_attachment_epoch: format!("epoch-{name}"), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + } + let (store_hit, release_store) = state.credentials.gate_next_store(); + let update = handle_update_provider( + &state, + authed_request(UpdateProviderRequest { + request_id: String::new(), + provider: Some(provider_with_credential_value( + "openai-local", + "openai", + "OPENAI_API_KEY", + "sk-second", + )), + credential_expiration_times: HashMap::new(), + clear_credential_expiration_keys: Vec::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ); + let attach_from_another_replica = async { + store_hit.await.unwrap(); + // Another gateway's attachment is outside the captured target set, + // even when its write reaches the database before provider publish. + state + .store + .update_message_cas::("late", 0, |sandbox| { + let spec = sandbox.spec.as_mut().unwrap(); + spec.providers.push("openai-local".to_string()); + spec.provider_attachment_epoch = "epoch-late-attached".to_string(); + }) + .await + .unwrap(); + release_store.send(()).unwrap(); + }; + let (response, ()) = tokio::join!(update, attach_from_another_replica); + let response = response.unwrap().into_inner(); + let provider = response.provider.as_ref().unwrap(); + let targets: HashSet<_> = response + .target_receipts + .iter() + .map(|receipt| receipt.desired.as_ref().unwrap().sandbox_name.as_str()) + .collect(); + assert_eq!(targets, HashSet::from(["first", "second"])); + assert!(!response.mutation_id.is_empty()); + for receipt in &response.target_receipts { + assert_eq!(receipt.mutation_id, response.mutation_id); + assert_eq!( + receipt.kind, + openshell_core::proto::ProviderMutationKind::Update as i32 + ); + let desired = receipt.desired.as_ref().unwrap(); + assert_eq!(desired.provider_id, provider.object_id()); + assert_eq!( + desired.provider_resource_version, + provider.metadata.as_ref().unwrap().resource_version + ); + assert_eq!( + desired.attachment_epoch, + format!("epoch-{}", desired.sandbox_name) + ); + } + } + + #[tokio::test] + async fn update_provider_retirement_failure_preserves_publication_and_receipts() { + let state = test_server_state().await; + handle_create_provider( + &state, + authed_request(CreateProviderRequest { + request_id: String::new(), + provider: Some(provider_with_credential_value( + "openai-local", + "openai", + "OPENAI_API_KEY", + "sk-first", + )), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + .unwrap(); + let initial = state + .store + .get_message_by_name::("default", "openai-local") + .await + .unwrap() + .unwrap(); + let initial_version = initial.metadata.as_ref().unwrap().resource_version; + let mut target_epochs = HashMap::new(); + for name in ["s1", "s2"] { + let attachment_epoch = uuid::Uuid::new_v4().to_string(); + state + .store + .put_message(&Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: uuid::Uuid::new_v4().to_string(), + name: name.to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + providers: vec!["openai-local".to_string()], + provider_attachment_epoch: attachment_epoch.clone(), + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + target_epochs.insert(name, attachment_epoch); + } + + // Only old-object retirement fails: staging and the provider CAS must + // still publish the replacement and preserve every selected receipt. + state.credentials.fail_next_delete(); + let result = handle_update_provider( + &state, + authed_request(UpdateProviderRequest { + request_id: String::new(), + provider: Some(provider_with_credential_value( + "openai-local", + "openai", + "OPENAI_API_KEY", + "sk-second", + )), + credential_expiration_times: HashMap::new(), + clear_credential_expiration_keys: Vec::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await; + + let published = state + .store + .get_message_by_name::("default", "openai-local") + .await + .unwrap() + .unwrap(); + let published_version = published.metadata.as_ref().unwrap().resource_version; + assert_eq!(published_version, initial_version + 1); + assert_ne!(published.credential_handles, initial.credential_handles); + let resolved = state + .credentials + .resolve_provider_handles(&published, crate::persistence::current_time_ms()) + .await + .unwrap(); + assert_eq!(resolved.values["OPENAI_API_KEY"], "sk-second"); + assert_eq!(state.credentials.stored_credential_count(), Some(2)); + + let response = result + .expect("published credential rotation must return its mutation receipts") + .into_inner(); + let provider = response.provider.as_ref().unwrap(); + assert_eq!(provider.object_id(), published.object_id()); + assert_eq!( + provider.metadata.as_ref().unwrap().resource_version, + published_version + ); + assert!(!response.mutation_id.is_empty()); + let targets: HashSet<_> = response + .target_receipts + .iter() + .map(|receipt| receipt.desired.as_ref().unwrap().sandbox_name.as_str()) + .collect(); + assert_eq!(targets, HashSet::from(["s1", "s2"])); + assert_eq!(response.target_receipts.len(), target_epochs.len()); + for receipt in &response.target_receipts { + assert!(!receipt.receipt_id.is_empty()); + assert_eq!(receipt.mutation_id, response.mutation_id); + assert_eq!( + receipt.kind, + openshell_core::proto::ProviderMutationKind::Update as i32 + ); + let desired = receipt.desired.as_ref().unwrap(); + assert_eq!(desired.provider_id, published.object_id()); + assert_eq!(desired.provider_resource_version, published_version); + assert_eq!( + desired.attachment_epoch, + target_epochs[desired.sandbox_name.as_str()] + ); + assert!(!desired.policy_hash.is_empty()); + } + } + #[tokio::test] async fn update_provider_record_clears_credential_expiration_by_key() { let store = test_store().await; @@ -8845,6 +9354,7 @@ mod tests { let err = handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider_with_credential_handle( "openai-ref", "openai", @@ -8868,6 +9378,7 @@ mod tests { let err = handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider_with_values("legacy-gitlab", "gitlab")), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -8890,6 +9401,7 @@ mod tests { let response = handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { name: "pypi".to_string(), @@ -8921,6 +9433,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("gitlab")), source: "custom-gitlab.yaml".to_string(), @@ -8934,6 +9447,7 @@ mod tests { let response = handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { name: "private-gitlab".to_string(), @@ -8981,6 +9495,7 @@ mod tests { let imported = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(profile), source: "enterprise-github.yaml".to_string(), @@ -8996,6 +9511,7 @@ mod tests { let provider = handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider_with_credential_value( "enterprise-github", "gh", @@ -9044,6 +9560,7 @@ mod tests { let response = handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider_with_credential_value( "openai-local", "openai", @@ -9146,6 +9663,7 @@ mod tests { let imported = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(profile), source: "provider-profile.yaml".to_string(), @@ -9161,6 +9679,7 @@ mod tests { handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider_with_credential_value( "exchange", "spiffe-token-exchange-demo", @@ -9199,6 +9718,7 @@ mod tests { let err = handle_update_provider( &state, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(provider_with_credential_handle( "openai-local", "openai", @@ -9466,6 +9986,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(ProviderProfile { id: "delegated-refresh-api".to_string(), @@ -9562,6 +10083,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(mixed_required_profile), source: "mixed-required-api.yaml".to_string(), @@ -9605,6 +10127,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(optional_static_profile), source: "optional-static-api.yaml".to_string(), @@ -10149,6 +10672,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(profile), source: "stable-refresh-provider.yaml".to_string(), @@ -10176,6 +10700,7 @@ mod tests { .await .unwrap(); let configure = || ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "stable-refresh".to_string(), credential_key: "ACCESS_TOKEN".to_string(), strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, @@ -10240,6 +10765,7 @@ mod tests { let err = handle_update_provider( &state, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { name: "stable-refresh".to_string(), @@ -10946,6 +11472,10 @@ mod tests { assert_eq!(result.get("FRESH_TOKEN"), Some(&"fresh".to_string())); assert!(!result.contains_key("STALE_TOKEN")); assert!(!result.contains_key("EPOCH_TOKEN")); + assert_eq!( + result.readiness_reason, + openshell_core::proto::ProviderReadinessReason::CredentialExpired + ); assert_eq!( result.credential_expiration_times.get("FRESH_TOKEN"), Some(&(now_ms + 60_000)) @@ -12066,6 +12596,7 @@ mod tests { handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider_with_credential_value( "profile-backed-openai", "openai", @@ -12096,6 +12627,7 @@ mod tests { let error = handle_update_provider( &state, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(update), credential_expiration_times: HashMap::new(), clear_credential_expiration_keys: Vec::new(), @@ -12117,6 +12649,7 @@ mod tests { handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider_with_credential_value( "required-openai", "openai", @@ -12146,6 +12679,7 @@ mod tests { let error = handle_update_provider( &state, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(update), credential_expiration_times: HashMap::new(), clear_credential_expiration_keys: Vec::new(), @@ -12172,6 +12706,7 @@ mod tests { handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider.clone()), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -12202,6 +12737,7 @@ mod tests { let response = handle_update_provider( &state, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(updated_provider.clone()), credential_expiration_times: HashMap::new(), clear_credential_expiration_keys: Vec::new(), @@ -12243,6 +12779,7 @@ mod tests { handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider.clone()), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -12273,6 +12810,7 @@ mod tests { let err = handle_update_provider( &state, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(stale_provider), credential_expiration_times: HashMap::new(), clear_credential_expiration_keys: Vec::new(), @@ -12321,6 +12859,7 @@ mod tests { handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider_with_credential_value( "openai-local", "openai", @@ -12351,6 +12890,7 @@ mod tests { let err = handle_update_provider( &state, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(stale_provider), credential_expiration_times: HashMap::new(), clear_credential_expiration_keys: Vec::new(), @@ -12395,6 +12935,7 @@ mod tests { handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some(provider.clone()), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -12428,6 +12969,7 @@ mod tests { handle_update_provider( &state_clone, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(updated), credential_expiration_times: HashMap::new(), clear_credential_expiration_keys: Vec::new(), @@ -12518,6 +13060,7 @@ mod tests { let response = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "my-aws-v2".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -12576,6 +13119,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "aws-endpoint-override".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -12655,6 +13199,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "aws-partial-source".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -12710,6 +13255,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "aws-lone-session".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -12768,6 +13314,7 @@ mod tests { handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "aws-outputs".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -12848,6 +13395,7 @@ mod tests { handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "aws-update-guard".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -12874,6 +13422,7 @@ mod tests { let err = handle_update_provider( &state, authed_request(UpdateProviderRequest { + request_id: String::new(), provider: Some(Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { name: "aws-update-guard".to_string(), @@ -12943,6 +13492,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "generic-no-profile".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -12997,6 +13547,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "aws-wrong-key".to_string(), credential_key: "AWS_SECRET_ACCESS_KEY".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -13177,6 +13728,7 @@ mod tests { let err = handle_configure_provider_refresh( &state, authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: "new-aws-provider".to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -13254,6 +13806,7 @@ mod tests { let configure = |provider: &str| { authed_request(ConfigureProviderRefreshRequest { + request_id: String::new(), provider: provider.to_string(), credential_key: "AWS_ACCESS_KEY_ID".to_string(), strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole as i32, @@ -13438,6 +13991,7 @@ mod tests { crate::grpc::workspace::handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "beta".to_string(), labels: HashMap::new(), }), @@ -13459,6 +14013,7 @@ mod tests { let created_default = handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some({ let mut p = make_provider(); p.metadata = Some(openshell_core::proto::datamodel::v1::ObjectMeta { @@ -13491,6 +14046,7 @@ mod tests { let created_beta = handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some({ let mut p = make_provider(); p.metadata = Some(openshell_core::proto::datamodel::v1::ObjectMeta { @@ -13588,6 +14144,7 @@ mod tests { let deleted = handle_delete_provider( &state, authed_request(DeleteProviderRequest { + request_id: String::new(), allow_missing: false, name: "shared-name".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -13637,6 +14194,7 @@ mod tests { handle_create_provider( &state, authed_request(CreateProviderRequest { + request_id: String::new(), provider: Some({ let mut p = make_provider(); p.metadata = Some(openshell_core::proto::datamodel::v1::ObjectMeta { @@ -13709,6 +14267,7 @@ mod tests { let import_error = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), workspace: String::new(), profiles: Vec::new(), }), @@ -13725,6 +14284,7 @@ mod tests { let update_error = handle_update_provider_profiles( &state, authed_request(UpdateProviderProfilesRequest { + request_id: String::new(), id: "nonexistent".to_string(), workspace: String::new(), ..UpdateProviderProfilesRequest::default() @@ -13758,6 +14318,7 @@ mod tests { let delete_error = handle_delete_provider_profile( &state, authed_request(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: false, id: "nonexistent".to_string(), workspace: String::new(), @@ -13950,6 +14511,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("ws-custom")), source: "ws-custom.yaml".to_string(), @@ -14003,6 +14565,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile(&id)), source: format!("{id}.yaml"), @@ -14080,6 +14643,7 @@ mod tests { handle_delete_provider_profile( &state, authed_request(DeleteProviderProfileRequest { + request_id: String::new(), allow_missing: false, id, workspace, @@ -14113,6 +14677,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile(&id)), source: format!("{id}.yaml"), @@ -14150,6 +14715,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("scoped-api")), source: "scoped-api.yaml".to_string(), @@ -14195,6 +14761,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("platform-only")), source: "platform-only.yaml".to_string(), @@ -14232,6 +14799,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("shadow-target")), source: "shadow-target.yaml".to_string(), @@ -14247,6 +14815,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(ws_profile), source: "shadow-target.yaml".to_string(), @@ -14280,6 +14849,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("shadow-warn")), source: "shadow-warn.yaml".to_string(), @@ -14293,6 +14863,7 @@ mod tests { let resp = handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("shadow-warn")), source: "shadow-warn.yaml".to_string(), @@ -14322,6 +14893,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("global-only")), source: "global-only.yaml".to_string(), @@ -14335,6 +14907,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(custom_profile("ws-only")), source: "ws-only.yaml".to_string(), @@ -14376,6 +14949,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(platform_profile), source: "scope-test.yaml".to_string(), @@ -14391,6 +14965,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(ws_profile), source: "scope-test.yaml".to_string(), @@ -14425,6 +15000,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(platform_profile), source: "scope-test-ws.yaml".to_string(), @@ -14440,6 +15016,7 @@ mod tests { handle_import_provider_profiles( &state, authed_request(ImportProviderProfilesRequest { + request_id: String::new(), profiles: vec![ProviderProfileImportItem { profile: Some(ws_profile), source: "scope-test-ws.yaml".to_string(), diff --git a/crates/openshell-server/src/grpc/provider_readiness.rs b/crates/openshell-server/src/grpc/provider_readiness.rs new file mode 100644 index 0000000000..0afb4bf6c9 --- /dev/null +++ b/crates/openshell-server/src/grpc/provider_readiness.rs @@ -0,0 +1,628 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Provider views of common configuration operations and session-bound evidence. + +#![allow(clippy::result_large_err)] // The RPC boundary returns tonic status values. + +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime}; + +use openshell_core::proto::{ + GetSandboxProviderStatusRequest, GetSandboxProviderStatusResponse, Provider, + ProviderDesiredIdentity, ProviderMutationKind, ProviderMutationReceipt, + ProviderReadinessObservation, ProviderReadinessReason, ProviderReadinessState, + ProviderReadinessStatus, ReportProviderReadinessRequest, ReportProviderReadinessResponse, + Sandbox, SandboxPhase, SupervisorHello, +}; +use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; +use tonic::{Request, Response, Status}; +use uuid::Uuid; + +use crate::ServerState; +use crate::auth::guard::{enforce_sandbox_scope, ensure_sandbox_principal_scope}; +use crate::auth::workspace_authz::{MinWorkspaceRole, authorize_workspace_selector}; +use crate::config_update_operation; +use crate::persistence::ObjectType; + +const REPORT_INTERVAL_SECONDS: u32 = 5; +const OBSERVATION_TTL_SECONDS: u32 = 15; + +/// Installation evidence owned by one live `ConnectSupervisor` session. +/// Replacing or removing that session discards this evidence with it. +#[derive(Clone, Debug)] +pub struct ProviderReadinessEvidence { + network_instance_id: String, + supported: bool, + process_instance_id: Option, + last_seen: Instant, + observation: Option, + observed_time: Option, +} + +impl ProviderReadinessEvidence { + /// Require the instance last accepted into the persisted sandbox lifecycle. + /// A local session alone cannot prove ownership across gateway replicas. + pub(crate) fn belongs_to_instance(&self, active_instance_id: &str) -> bool { + !active_instance_id.is_empty() && self.network_instance_id == active_instance_id + } + + /// Capture capability and instance identity from the authenticated hello. + pub(crate) fn from_hello(hello: &SupervisorHello) -> Result { + if hello.supports_provider_readiness { + canonical_uuid(&hello.sandbox_id)?; + canonical_uuid(&hello.instance_id)?; + } + Ok(Self { + network_instance_id: hello.instance_id.clone(), + supported: hello.supports_provider_readiness, + process_instance_id: None, + last_seen: Instant::now(), + observation: None, + observed_time: None, + }) + } + + /// Accept an ordered report after the registry verifies session ownership. + /// Retrying an identical report never extends its original acceptance time. + pub(crate) fn accept( + &mut self, + observation: ProviderReadinessObservation, + ) -> Result<(), Status> { + if !self.supported { + return Err(Status::failed_precondition( + "supervisor did not advertise provider readiness support", + )); + } + if observation.sequence == 0 { + return Err(Status::invalid_argument("report sequence is required")); + } + if let Some(last) = self.observation.as_ref() { + if observation.sequence == last.sequence { + return if &observation == last { + Ok(()) + } else { + Err(Status::invalid_argument( + "a provider report sequence must reuse the identical observation", + )) + }; + } + if observation.sequence < last.sequence { + return Err(Status::failed_precondition( + "provider readiness observation is out of order", + )); + } + } + if observation.session_id.is_empty() { + return Err(Status::failed_precondition( + "supervisor session identity is required", + )); + } + ProviderReadinessReason::try_from(observation.reason) + .map_err(|_| Status::invalid_argument("unknown readiness reason"))?; + if !observation.attachment_epoch.is_empty() { + canonical_uuid(&observation.attachment_epoch)?; + } + if observation.policy_hash.len() > 128 + || !observation + .policy_hash + .bytes() + .all(|byte| byte.is_ascii_hexdigit()) + { + return Err(Status::invalid_argument("invalid policy fingerprint")); + } + if observation.launch_environment_installed && observation.process_instance_id.is_empty() { + return Err(Status::invalid_argument( + "process instance identity is required", + )); + } + let observed_time = now_timestamp()?; + if !observation.process_instance_id.is_empty() { + canonical_uuid(&observation.process_instance_id)?; + if self + .process_instance_id + .as_ref() + .is_some_and(|process_id| process_id != &observation.process_instance_id) + { + return Err(Status::failed_precondition("process instance changed")); + } + // The supervisor reports its authenticated boundary's process + // identity. A boundary replacement requires a new control session. + self.process_instance_id = Some(observation.process_instance_id.clone()); + } + self.last_seen = Instant::now(); + self.observed_time = Some(observed_time); + self.observation = Some(observation); + Ok(()) + } +} + +fn registry_unavailable() -> Status { + Status::unavailable("provider readiness state is unavailable") +} + +fn now_timestamp() -> Result { + openshell_core::time::timestamp_from_system_time(SystemTime::now()) + .map_err(|error| Status::internal(format!("create provider readiness timestamp: {error}"))) +} + +fn canonical_uuid(value: &str) -> Result<(), Status> { + let parsed = Uuid::parse_str(value) + .map_err(|_| Status::invalid_argument("invalid readiness instance identity"))?; + if parsed.is_nil() || parsed.to_string() != value { + return Err(Status::invalid_argument( + "invalid readiness instance identity", + )); + } + Ok(()) +} + +/// Persist an immutable receipt for the target frozen before a source mutation. +/// Expected provider identity prevents a competing update from acquiring this +/// receipt even when snapshot reads happen after the source CAS. +pub(super) async fn record_provider_mutation( + state: &Arc, + sandbox: &Sandbox, + provider_name: &str, + kind: ProviderMutationKind, + expected_provider: Option<(&str, u64)>, + mutation_id: &str, +) -> Result { + let mut desired = target_identity(sandbox, expected_provider); + let snapshot_reason = match load_current_snapshot(state, sandbox, provider_name).await { + Ok((snapshot, _)) if same_authority(&desired, &snapshot) => { + desired = snapshot; + ProviderReadinessReason::Unspecified + } + Ok(_) => ProviderReadinessReason::SnapshotMismatch, + Err(_) => ProviderReadinessReason::CredentialsWithheld, + }; + let receipt = ProviderMutationReceipt { + receipt_id: Uuid::new_v4().to_string(), + mutation_id: mutation_id.to_string(), + provider_name: provider_name.to_string(), + workspace: sandbox.object_workspace().to_string(), + kind: kind.into(), + desired: Some(desired), + persisted_time: Some(now_timestamp()?), + }; + config_update_operation::record_provider_operation( + state.store.as_ref(), + receipt, + snapshot_reason, + ) + .await +} + +fn target_identity(sandbox: &Sandbox, provider: Option<(&str, u64)>) -> ProviderDesiredIdentity { + // The empty initial epoch remains an opaque identity paired with the + // sandbox UUID. Every provider-set mutation atomically replaces the epoch. + ProviderDesiredIdentity { + sandbox_id: sandbox.object_id().to_string(), + sandbox_name: sandbox.object_name().to_string(), + attachment_epoch: sandbox + .spec + .as_ref() + .map(|spec| spec.provider_attachment_epoch.clone()) + .unwrap_or_default(), + provider_id: provider.map_or_else(String::new, |(id, _)| id.to_string()), + provider_resource_version: provider.map_or(0, |(_, version)| version), + ..Default::default() + } +} + +fn same_authority(left: &ProviderDesiredIdentity, right: &ProviderDesiredIdentity) -> bool { + left.sandbox_id == right.sandbox_id + && left.sandbox_name == right.sandbox_name + && left.attachment_epoch == right.attachment_epoch + && left.provider_id == right.provider_id + && left.provider_resource_version == right.provider_resource_version +} + +async fn current_target_identity( + state: &Arc, + sandbox: &Sandbox, + provider_name: &str, +) -> Result { + let attached = sandbox + .spec + .as_ref() + .is_some_and(|spec| spec.providers.iter().any(|name| name == provider_name)); + let provider = if attached { + state + .store + .get_by_name( + Provider::object_type(), + sandbox.object_workspace(), + provider_name, + ) + .await + .map_err(|_| registry_unavailable())? + } else { + None + }; + Ok(target_identity( + sandbox, + provider + .as_ref() + .map(|provider| (provider.id.as_str(), provider.resource_version)), + )) +} + +/// Bracket independently stored config and credential records with exact +/// identity reads. Inconsistent reads remain pending; revisions are never +/// treated as counters or compared with greater-than ordering. +async fn load_current_snapshot( + state: &Arc, + sandbox: &Sandbox, + provider_name: &str, +) -> Result<(ProviderDesiredIdentity, ProviderReadinessReason), Status> { + let mut desired = current_target_identity(state, sandbox, provider_name).await?; + let config = super::policy::load_sandbox_config(state, sandbox).await?; + let environment = + super::policy::load_sandbox_provider_environment(state, sandbox, true).await?; + let current = state + .store + .get_message::(sandbox.object_id()) + .await + .map_err(|_| registry_unavailable())? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + let after = current_target_identity(state, ¤t, provider_name).await?; + let final_config = super::policy::load_sandbox_config(state, ¤t).await?; + if !same_authority(&desired, &after) + || config.provider_attachment_epoch != environment.provider_attachment_epoch + || config.provider_env_revision != environment.provider_env_revision + || (config.policy.is_some() && config.policy_hash != environment.policy_hash) + || config.config_revision != final_config.config_revision + || config.provider_env_revision != final_config.provider_env_revision + || config.policy_hash != final_config.policy_hash + { + return Err(Status::aborted("provider readiness snapshot changed")); + } + desired.provider_env_revision = config.provider_env_revision; + desired.config_revision = config.config_revision; + desired.policy_hash = config.policy_hash; + let reason = if config.policy.is_none() { + ProviderReadinessReason::LocalPolicy + } else { + ProviderReadinessReason::try_from(environment.readiness_reason) + .unwrap_or(ProviderReadinessReason::CredentialsWithheld) + }; + Ok((desired, reason)) +} + +/// Return a redacted operator view. Receipt-less lookup reconstructs current +/// intent only; it never claims that a mutation lost before persistence finished. +pub(super) async fn handle_get_sandbox_provider_status( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let request = request.into_inner(); + let authz = authorize_workspace_selector( + &state.store, + &state.admin_role, + &principal, + request.workspace_scope.as_ref(), + MinWorkspaceRole::User, + ) + .await?; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + // Validate the selector before it can contribute to a durable observation. + if request.provider_name.len() > super::MAX_NAME_LEN { + return Err(Status::invalid_argument( + "provider_name exceeds maximum length", + )); + } + let sandbox = state + .store + .get_message_by_name::(&workspace, &request.sandbox_name) + .await + .map_err(|_| registry_unavailable())? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + let receipt_id = if request.receipt_id.is_empty() { + if request.provider_name.is_empty() { + return Err(Status::invalid_argument( + "provider_name or receipt_id is required", + )); + } + // Only existing workspace providers can create observation operations. + // A detached provider still has a useful absent-reference target; + // historical receipts remain queryable after the provider is deleted. + state + .store + .get_by_name(Provider::object_type(), &workspace, &request.provider_name) + .await + .map_err(|_| registry_unavailable())? + .ok_or_else(|| Status::not_found("provider not found"))?; + let current = current_target_identity(state, &sandbox, &request.provider_name).await?; + let provider = (!current.provider_id.is_empty()).then_some(( + current.provider_id.as_str(), + current.provider_resource_version, + )); + record_provider_mutation( + state, + &sandbox, + &request.provider_name, + ProviderMutationKind::Observe, + provider, + &Uuid::new_v4().to_string(), + ) + .await? + .receipt_id + } else { + canonical_uuid(&request.receipt_id)?; + request.receipt_id + }; + let stored = config_update_operation::get_provider_operation( + state.store.as_ref(), + &receipt_id, + &workspace, + ) + .await?; + let receipt = stored.receipt; + if receipt.workspace != workspace + || receipt + .desired + .as_ref() + .is_none_or(|desired| desired.sandbox_id != sandbox.object_id()) + || (!request.provider_name.is_empty() && receipt.provider_name != request.provider_name) + { + return Err(Status::not_found("provider receipt not found")); + } + let current_authority = + current_target_identity(state, &sandbox, &receipt.provider_name).await?; + let (current, current_reason) = if let Ok(snapshot) = + load_current_snapshot(state, &sandbox, &receipt.provider_name).await + { + snapshot + } else { + // A temporarily unreadable config cannot prove supersession or + // completion. Metadata changes remain comparable independently. + let mut fallback = current_authority; + if let Some(desired) = receipt.desired.as_ref() { + fallback.provider_env_revision = desired.provider_env_revision; + fallback.config_revision = desired.config_revision; + fallback.policy_hash.clone_from(&desired.policy_hash); + } + (fallback, ProviderReadinessReason::CredentialsWithheld) + }; + // Refresh lifecycle identity after configuration reads. Another gateway + // replica may have accepted a new supervisor while this replica retained + // the predecessor's local connection and installation evidence. + let active_sandbox = state + .store + .get_message::(sandbox.object_id()) + .await + .map_err(|_| registry_unavailable())? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + let active_instance_id = active_sandbox + .status + .as_ref() + .map_or("", |status| status.main_process_instance_id.as_str()); + let session = state + .supervisor_sessions + .provider_readiness(sandbox.object_id())?; + let mut status = evaluate_status( + receipt, + stored.snapshot_reason, + ¤t, + current_reason, + active_sandbox.phase() == SandboxPhase::Ready as i32, + active_instance_id, + session.as_ref(), + )?; + config_update_operation::observe_provider_status(state.store.as_ref(), &mut status).await?; + Ok(Response::new(GetSandboxProviderStatusResponse { + status: Some(status), + })) +} + +fn observation_matches( + observation: &ProviderReadinessObservation, + desired: &ProviderDesiredIdentity, +) -> bool { + observation.attachment_epoch == desired.attachment_epoch + && observation.provider_env_revision == desired.provider_env_revision + && observation.config_revision == desired.config_revision + && observation.policy_hash == desired.policy_hash +} + +fn failure_state(reason: ProviderReadinessReason) -> ProviderReadinessState { + match reason { + ProviderReadinessReason::CredentialsWithheld + | ProviderReadinessReason::CredentialExpired => ProviderReadinessState::Withheld, + ProviderReadinessReason::CredentialInstallFailed + | ProviderReadinessReason::PolicyActivationFailed + | ProviderReadinessReason::ProcessInstallFailed + | ProviderReadinessReason::UnsupportedSupervisor + | ProviderReadinessReason::LocalPolicy => ProviderReadinessState::Failed, + _ => ProviderReadinessState::Pending, + } +} + +fn evaluate_status( + receipt: ProviderMutationReceipt, + snapshot_reason: ProviderReadinessReason, + current: &ProviderDesiredIdentity, + current_reason: ProviderReadinessReason, + running: bool, + active_instance_id: &str, + session: Option<&ProviderReadinessEvidence>, +) -> Result { + let mut status = ProviderReadinessStatus { + receipt: Some(receipt.clone()), + state: ProviderReadinessState::Persisted.into(), + reason: ProviderReadinessReason::WaitingForSupervisor.into(), + observed: session.and_then(|session| session.observation.clone()), + network_instance_id: session + .map(|session| session.network_instance_id.clone()) + .unwrap_or_default(), + observed_time: session.and_then(|session| session.observed_time), + evaluated_time: Some(now_timestamp()?), + operation: None, + }; + let set = |status: &mut ProviderReadinessStatus, + state: ProviderReadinessState, + reason: ProviderReadinessReason| { + status.state = state.into(); + status.reason = reason.into(); + }; + let Some(desired) = receipt.desired.as_ref() else { + set( + &mut status, + ProviderReadinessState::Failed, + ProviderReadinessReason::SnapshotMismatch, + ); + return Ok(status); + }; + if !same_authority(desired, current) + || (snapshot_reason == ProviderReadinessReason::Unspecified && desired != current) + { + set( + &mut status, + ProviderReadinessState::Superseded, + ProviderReadinessReason::DesiredStateChanged, + ); + } else if snapshot_reason != ProviderReadinessReason::Unspecified { + set(&mut status, ProviderReadinessState::Failed, snapshot_reason); + } else if current_reason != ProviderReadinessReason::Unspecified { + set(&mut status, failure_state(current_reason), current_reason); + } else if !running { + set( + &mut status, + ProviderReadinessState::Pending, + ProviderReadinessReason::SupervisorDisconnected, + ); + } else if let Some(session) = session { + if !session.belongs_to_instance(active_instance_id) { + set( + &mut status, + ProviderReadinessState::Pending, + ProviderReadinessReason::SupervisorDisconnected, + ); + } else if session.last_seen.elapsed() + >= Duration::from_secs(u64::from(OBSERVATION_TTL_SECONDS)) + { + set( + &mut status, + ProviderReadinessState::Pending, + ProviderReadinessReason::SupervisorLeaseExpired, + ); + } else if !session.supported { + set( + &mut status, + ProviderReadinessState::Failed, + ProviderReadinessReason::UnsupportedSupervisor, + ); + } else if let Some(observation) = session.observation.as_ref() { + let reason = ProviderReadinessReason::try_from(observation.reason) + .unwrap_or(ProviderReadinessReason::SnapshotMismatch); + // Installation failures describe one snapshot. A retained failure + // from an older poll must not fail a newly persisted authority. + if !observation_matches(observation, desired) { + set( + &mut status, + ProviderReadinessState::Pending, + ProviderReadinessReason::SnapshotMismatch, + ); + } else if reason != ProviderReadinessReason::Unspecified { + set(&mut status, failure_state(reason), reason); + } else if !observation.credentials_installed { + set( + &mut status, + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForCredentials, + ); + } else if !observation.policy_active { + set( + &mut status, + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForPolicy, + ); + } else if !observation.launch_environment_installed + || observation.process_instance_id.is_empty() + { + set( + &mut status, + ProviderReadinessState::Pending, + ProviderReadinessReason::WaitingForProcess, + ); + } else { + let state = if desired.provider_id.is_empty() { + ProviderReadinessState::Revoked + } else { + ProviderReadinessState::Ready + }; + set(&mut status, state, ProviderReadinessReason::Unspecified); + } + } + } + Ok(status) +} + +fn authorize_provider_readiness( + request: &Request, + sandbox_id: &str, +) -> Result { + let principal = enforce_sandbox_scope(request, sandbox_id)?; + ensure_sandbox_principal_scope(&principal, sandbox_id)?; + Ok(principal) +} + +/// Accept installation evidence only from the sandbox's current supervisor. +/// Authorization is independent from operator permission to inspect progress. +pub(super) async fn handle_report_provider_readiness( + state: &Arc, + request: Request, +) -> Result, Status> { + let sandbox_id = request.get_ref().sandbox_id.clone(); + let principal = authorize_provider_readiness(&request, &sandbox_id)?; + canonical_uuid(&sandbox_id)?; + let observation = request + .into_inner() + .observation + .ok_or_else(|| Status::invalid_argument("provider readiness observation is required"))?; + canonical_uuid(&observation.session_id)?; + // A valid session must still belong to an existing sandbox. The registry + // performs the final current-session check atomically with accepting evidence, + // so a reconnect during this read cannot publish into its replacement. + let sandbox = + super::sandbox::fetch_and_authorize_sandbox(state, &principal, &sandbox_id).await?; + if sandbox.phase() != SandboxPhase::Ready as i32 { + return Err(Status::failed_precondition( + "sandbox supervisor is not ready", + )); + } + let active_instance_id = sandbox + .status + .as_ref() + .map_or("", |status| status.main_process_instance_id.as_str()); + let accepted_sequence = observation.sequence; + state.supervisor_sessions.accept_provider_readiness( + &sandbox_id, + active_instance_id, + observation, + )?; + Ok(Response::new(ReportProviderReadinessResponse { + accepted_sequence, + report_interval: Some( + openshell_core::time::duration_from_std(Duration::from_secs(u64::from( + REPORT_INTERVAL_SECONDS, + ))) + .map_err(|error| Status::internal(format!("create report interval: {error}")))?, + ), + observation_ttl: Some( + openshell_core::time::duration_from_std(Duration::from_secs(u64::from( + OBSERVATION_TTL_SECONDS, + ))) + .map_err(|error| Status::internal(format!("create observation TTL: {error}")))?, + ), + })) +} + +#[cfg(test)] +#[path = "provider_readiness_tests.rs"] +mod tests; diff --git a/crates/openshell-server/src/grpc/provider_readiness_tests.rs b/crates/openshell-server/src/grpc/provider_readiness_tests.rs new file mode 100644 index 0000000000..c5fbe4b974 --- /dev/null +++ b/crates/openshell-server/src/grpc/provider_readiness_tests.rs @@ -0,0 +1,1353 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use super::*; +use crate::auth::principal::{Principal, SandboxIdentitySource, SandboxPrincipal}; +use crate::config_update_operation::CONFIG_UPDATE_OPERATION_OBJECT_TYPE; +use crate::grpc::test_support::{authed_request, test_server_state}; +use crate::persistence::WriteCondition; +use crate::storage_proto::StoredConfigUpdateOperation; +use openshell_core::proto::SandboxSpec; +use openshell_core::proto::datamodel::v1::ObjectMeta; +use prost::Message; +use std::collections::HashMap; + +// Exercise the production session registry while keeping unrelated relay +// channel setup out of each installation-state test. +#[derive(Default)] +struct TestRegistry(crate::supervisor_session::SupervisorSessionRegistry); + +fn register_session( + registry: &crate::supervisor_session::SupervisorSessionRegistry, + hello: &SupervisorHello, +) -> Result { + let evidence = ProviderReadinessEvidence::from_hello(hello)?; + let session_id = Uuid::new_v4().to_string(); + let (sender, _receiver) = tokio::sync::mpsc::channel(1); + let (shutdown, _shutdown_receiver) = tokio::sync::oneshot::channel(); + registry.register( + hello.sandbox_id.clone(), + session_id.clone(), + sender, + shutdown, + ); + assert!(registry.initialize_endpoint_status_authority(&hello.sandbox_id, &session_id)); + registry.initialize_provider_readiness(&hello.sandbox_id, &session_id, evidence)?; + Ok(session_id) +} + +impl TestRegistry { + fn register(&self, hello: &SupervisorHello) -> Result { + register_session(&self.0, hello) + } + + fn accept( + &self, + sandbox_id: &str, + session_id: &str, + observation: ProviderReadinessObservation, + ) -> Result<(), Status> { + assert_eq!(session_id, observation.session_id); + let active_instance = self + .0 + .provider_readiness(sandbox_id)? + .map(|evidence| evidence.network_instance_id) + .unwrap_or_default(); + self.0 + .accept_provider_readiness(sandbox_id, &active_instance, observation) + } + + fn snapshot(&self, sandbox_id: &str) -> Result, Status> { + self.0.provider_readiness(sandbox_id) + } + + fn disconnect(&self, sandbox_id: &str, session_id: &str) { + self.0.remove_if_current(sandbox_id, session_id); + } +} + +fn hello() -> SupervisorHello { + SupervisorHello { + sandbox_id: Uuid::new_v4().to_string(), + instance_id: Uuid::new_v4().to_string(), + supports_provider_readiness: true, + } +} + +fn receipt(hello: &SupervisorHello) -> ProviderMutationReceipt { + ProviderMutationReceipt { + receipt_id: Uuid::new_v4().to_string(), + mutation_id: Uuid::new_v4().to_string(), + provider_name: "synthetic-provider".to_string(), + workspace: "default".to_string(), + kind: ProviderMutationKind::Attach.into(), + desired: Some(ProviderDesiredIdentity { + sandbox_id: hello.sandbox_id.clone(), + sandbox_name: "synthetic".to_string(), + attachment_epoch: Uuid::new_v4().to_string(), + provider_id: Uuid::new_v4().to_string(), + provider_resource_version: 2, + provider_env_revision: u64::MAX - 1, + config_revision: u64::MAX, + policy_hash: "abcd".to_string(), + }), + persisted_time: Some(prost_types::Timestamp { + seconds: 0, + nanos: 1, + }), + } +} + +fn installed( + hello: &SupervisorHello, + session_id: &str, + receipt: &ProviderMutationReceipt, +) -> ProviderReadinessObservation { + let desired = receipt.desired.as_ref().unwrap(); + ProviderReadinessObservation { + session_id: session_id.to_string(), + sequence: 1, + attachment_epoch: desired.attachment_epoch.clone(), + provider_env_revision: desired.provider_env_revision, + config_revision: desired.config_revision, + policy_hash: desired.policy_hash.clone(), + credentials_installed: true, + policy_active: true, + launch_environment_installed: true, + process_instance_id: hello.instance_id.clone(), + reason: ProviderReadinessReason::Unspecified.into(), + } +} + +fn evaluate( + receipt: &ProviderMutationReceipt, + session: Option<&ProviderReadinessEvidence>, +) -> ProviderReadinessStatus { + evaluate_status( + receipt.clone(), + ProviderReadinessReason::Unspecified, + receipt.desired.as_ref().unwrap(), + ProviderReadinessReason::Unspecified, + true, + session.map_or("", |evidence| evidence.network_instance_id.as_str()), + session, + ) + .unwrap() +} + +#[test] +fn readiness_timestamps_distinguish_missing_observations_and_preserve_nanos() { + let hello = hello(); + let receipt = receipt(&hello); + let disconnected = evaluate(&receipt, None); + assert!(disconnected.observed_time.is_none()); + assert!(disconnected.evaluated_time.is_some()); + + let mut evidence = ProviderReadinessEvidence::from_hello(&hello).unwrap(); + assert!(evaluate(&receipt, Some(&evidence)).observed_time.is_none()); + let observation = installed(&hello, &Uuid::new_v4().to_string(), &receipt); + evidence.accept(observation.clone()).unwrap(); + assert!(evidence.observed_time.is_some()); + + // A captured timestamp must survive status projection and report retries + // without millisecond truncation or a fabricated new observation time. + let captured = prost_types::Timestamp { + seconds: 0, + nanos: 1, + }; + evidence.observed_time = Some(captured); + evidence.accept(observation).unwrap(); + let status = evaluate(&receipt, Some(&evidence)); + assert_eq!(status.observed_time, Some(captured)); + openshell_core::time::validate_timestamp(status.evaluated_time.as_ref().unwrap()).unwrap(); +} + +#[test] +fn reporting_requires_own_authenticated_sandbox() { + let hello = hello(); + assert_eq!( + authorize_provider_readiness(&authed_request(()), &hello.sandbox_id) + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + assert_eq!( + authorize_provider_readiness(&Request::new(()), &hello.sandbox_id) + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + let mut request = Request::new(()); + request + .extensions_mut() + .insert(Principal::Sandbox(SandboxPrincipal { + sandbox_id: hello.sandbox_id.clone(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: "test".to_string(), + }, + trust_domain: Some("test".to_string()), + })); + assert!(authorize_provider_readiness(&request, &hello.sandbox_id).is_ok()); + let mut other = hello; + other.sandbox_id = Uuid::new_v4().to_string(); + assert_eq!( + authorize_provider_readiness(&request, &other.sandbox_id) + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); +} + +#[tokio::test] +async fn report_rpc_requires_the_authenticated_sandboxes_current_session() { + let state = test_server_state().await; + let hello = hello(); + let receipt = receipt(&hello); + state + .store + .put_message(&Sandbox { + metadata: Some(ObjectMeta { + id: hello.sandbox_id.clone(), + name: "report-owner".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + status: Some(openshell_core::proto::SandboxStatus { + phase: SandboxPhase::Ready as i32, + main_process_instance_id: hello.instance_id.clone(), + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + let session_id = register_session(&state.supervisor_sessions, &hello).unwrap(); + let report = ReportProviderReadinessRequest { + sandbox_id: hello.sandbox_id.clone(), + observation: Some(installed(&hello, &session_id, &receipt)), + }; + let request = |report: ReportProviderReadinessRequest, sandbox_id: &str| { + let mut request = Request::new(report); + request + .extensions_mut() + .insert(Principal::Sandbox(SandboxPrincipal { + sandbox_id: sandbox_id.to_string(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: "test".to_string(), + }, + trust_domain: Some("test".to_string()), + })); + request + }; + for (unauthorized, code) in [ + (Request::new(report.clone()), tonic::Code::Unauthenticated), + ( + authed_request(report.clone()), + tonic::Code::PermissionDenied, + ), + ( + request(report.clone(), &Uuid::new_v4().to_string()), + tonic::Code::PermissionDenied, + ), + ] { + assert_eq!( + handle_report_provider_readiness(&state, unauthorized) + .await + .unwrap_err() + .code(), + code + ); + } + let response = + handle_report_provider_readiness(&state, request(report.clone(), &hello.sandbox_id)) + .await + .unwrap() + .into_inner(); + assert_eq!(response.accepted_sequence, 1); + assert_eq!( + openshell_core::time::duration_to_std(response.observation_ttl.as_ref().unwrap()).unwrap(), + Duration::from_secs(u64::from(OBSERVATION_TTL_SECONDS)) + ); + assert_eq!( + openshell_core::time::duration_to_std(response.report_interval.as_ref().unwrap()).unwrap(), + Duration::from_secs(u64::from(REPORT_INTERVAL_SECONDS)) + ); + // Another gateway replica can replace the persisted instance without + // touching this process's session registry. The old report must fail. + let mut sandbox = state + .store + .get_message::(&hello.sandbox_id) + .await + .unwrap() + .unwrap(); + sandbox.status.as_mut().unwrap().main_process_instance_id = Uuid::new_v4().to_string(); + state.store.put_message(&sandbox).await.unwrap(); + assert_eq!( + handle_report_provider_readiness(&state, request(report.clone(), &hello.sandbox_id)) + .await + .unwrap_err() + .code(), + tonic::Code::FailedPrecondition + ); + register_session(&state.supervisor_sessions, &hello).unwrap(); + assert_eq!( + handle_report_provider_readiness(&state, request(report, &hello.sandbox_id)) + .await + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); +} + +#[test] +fn report_retries_preserve_evidence_and_reject_reordering_or_changed_content() { + let registry = TestRegistry::default(); + let hello = hello(); + let receipt = receipt(&hello); + let session = registry.register(&hello).unwrap(); + let mut observation = installed(&hello, &session, &receipt); + observation.sequence = 2; + registry + .accept(&hello.sandbox_id, &session, observation.clone()) + .unwrap(); + let accepted = registry.snapshot(&hello.sandbox_id).unwrap().unwrap(); + let mut changed = observation.clone(); + changed.credentials_installed = false; + assert_eq!( + registry + .accept(&hello.sandbox_id, &session, changed) + .unwrap_err() + .code(), + tonic::Code::InvalidArgument + ); + let mut older = observation.clone(); + older.sequence = 1; + assert_eq!( + registry + .accept(&hello.sandbox_id, &session, older) + .unwrap_err() + .code(), + tonic::Code::FailedPrecondition + ); + registry + .accept(&hello.sandbox_id, &session, observation.clone()) + .unwrap(); + let retried = registry.snapshot(&hello.sandbox_id).unwrap().unwrap(); + assert_eq!(retried.observation, Some(observation)); + assert_eq!(retried.last_seen, accepted.last_seen); + assert_eq!(retried.observed_time, accepted.observed_time); +} + +#[test] +fn expired_evidence_requires_a_new_report_sequence() { + let hello = hello(); + let receipt = receipt(&hello); + let mut evidence = ProviderReadinessEvidence::from_hello(&hello).unwrap(); + let mut observation = installed(&hello, &Uuid::new_v4().to_string(), &receipt); + evidence.accept(observation.clone()).unwrap(); + evidence.last_seen -= Duration::from_secs(u64::from(OBSERVATION_TTL_SECONDS) + 1); + let expired_at = evidence.last_seen; + evidence.accept(observation.clone()).unwrap(); + assert_eq!(evidence.last_seen, expired_at); + assert_eq!( + evaluate(&receipt, Some(&evidence)).reason, + ProviderReadinessReason::SupervisorLeaseExpired as i32 + ); + observation.sequence += 1; + evidence.accept(observation).unwrap(); + assert_eq!( + evaluate(&receipt, Some(&evidence)).state, + ProviderReadinessState::Ready as i32 + ); +} + +#[test] +fn unsupported_and_uninitialized_sessions_cannot_publish_evidence() { + let registry = TestRegistry::default(); + let mut hello = hello(); + hello.supports_provider_readiness = false; + let receipt = receipt(&hello); + let session = registry.register(&hello).unwrap(); + assert_eq!( + registry + .accept( + &hello.sandbox_id, + &session, + installed(&hello, &session, &receipt) + ) + .unwrap_err() + .code(), + tonic::Code::FailedPrecondition + ); + assert_eq!( + evaluate( + &receipt, + registry.snapshot(&hello.sandbox_id).unwrap().as_ref() + ) + .reason, + ProviderReadinessReason::UnsupportedSupervisor as i32 + ); + let other = Uuid::new_v4().to_string(); + let (tx, _rx) = tokio::sync::mpsc::channel(1); + let (shutdown, _shutdown_rx) = tokio::sync::oneshot::channel(); + registry + .0 + .register(hello.sandbox_id.clone(), other.clone(), tx, shutdown); + assert_eq!( + registry + .accept( + &hello.sandbox_id, + &other, + installed(&hello, &other, &receipt) + ) + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + assert!(registry.snapshot(&hello.sandbox_id).unwrap().is_none()); +} + +#[test] +fn malformed_reports_do_not_replace_accepted_evidence() { + let registry = TestRegistry::default(); + let hello = hello(); + let receipt = receipt(&hello); + let session = registry.register(&hello).unwrap(); + let initial = installed(&hello, &session, &receipt); + registry + .accept(&hello.sandbox_id, &session, initial.clone()) + .unwrap(); + for case in 0..6 { + let mut invalid = initial.clone(); + invalid.sequence = 2; + match case { + 0 => invalid.sequence = 0, + 1 => invalid.reason = i32::MAX, + 2 => invalid.attachment_epoch = "untrusted-identity".to_string(), + 3 => invalid.policy_hash = "a".repeat(129), + 4 => invalid.policy_hash = "not-a-fingerprint".to_string(), + _ => invalid.process_instance_id.clear(), + } + assert!( + registry + .accept(&hello.sandbox_id, &session, invalid) + .is_err() + ); + assert_eq!( + registry + .snapshot(&hello.sandbox_id) + .unwrap() + .unwrap() + .observation, + Some(initial.clone()) + ); + } +} + +#[test] +fn replacement_disconnect_and_replayed_reports_cannot_restore_readiness() { + let registry = TestRegistry::default(); + let hello = hello(); + let receipt = receipt(&hello); + let first = registry.register(&hello).unwrap(); + let observation = installed(&hello, &first, &receipt); + registry + .accept(&hello.sandbox_id, &first, observation.clone()) + .unwrap(); + assert_eq!( + evaluate( + &receipt, + registry.snapshot(&hello.sandbox_id).unwrap().as_ref() + ) + .state, + ProviderReadinessState::Ready as i32 + ); + let before_retry = registry.snapshot(&hello.sandbox_id).unwrap().unwrap(); + registry + .accept(&hello.sandbox_id, &first, observation.clone()) + .unwrap(); + let after_retry = registry.snapshot(&hello.sandbox_id).unwrap().unwrap(); + assert_eq!(before_retry.last_seen, after_retry.last_seen); + assert_eq!(before_retry.observed_time, after_retry.observed_time); + + let second = registry.register(&hello).unwrap(); + assert_ne!(first, second); + assert!( + registry + .accept(&hello.sandbox_id, &first, observation) + .is_err() + ); + registry.disconnect(&hello.sandbox_id, &first); + let current = registry.snapshot(&hello.sandbox_id).unwrap().unwrap(); + assert_eq!( + registry.0.current_session_id(&hello.sandbox_id), + Some(second.clone()) + ); + assert_eq!( + evaluate(&receipt, Some(¤t)).state, + ProviderReadinessState::Persisted as i32 + ); + registry + .accept( + &hello.sandbox_id, + &second, + installed(&hello, &second, &receipt), + ) + .unwrap(); + registry.disconnect(&hello.sandbox_id, &second); + assert!(registry.snapshot(&hello.sandbox_id).unwrap().is_none()); + assert_ne!( + evaluate(&receipt, None).state, + ProviderReadinessState::Ready as i32 + ); +} + +#[test] +fn sequence_order_does_not_order_revision_fingerprints() { + let registry = TestRegistry::default(); + let hello = hello(); + let receipt = receipt(&hello); + let session = registry.register(&hello).unwrap(); + let mut observation = installed(&hello, &session, &receipt); + registry + .accept(&hello.sandbox_id, &session, observation.clone()) + .unwrap(); + observation.sequence = 2; + observation.config_revision = 1; + observation.provider_env_revision = 1; + registry + .accept(&hello.sandbox_id, &session, observation) + .unwrap(); + assert_eq!( + evaluate( + &receipt, + registry.snapshot(&hello.sandbox_id).unwrap().as_ref() + ) + .reason, + ProviderReadinessReason::SnapshotMismatch as i32 + ); +} + +#[test] +fn partial_failed_incompatible_stopped_and_expired_installations_are_not_ready() { + let registry = TestRegistry::default(); + let hello = hello(); + let receipt = receipt(&hello); + let session_id = registry.register(&hello).unwrap(); + let observation = installed(&hello, &session_id, &receipt); + registry + .accept(&hello.sandbox_id, &session_id, observation) + .unwrap(); + let complete = registry.snapshot(&hello.sandbox_id).unwrap().unwrap(); + for reason in [ + ProviderReadinessReason::CredentialInstallFailed, + ProviderReadinessReason::PolicyActivationFailed, + ProviderReadinessReason::ProcessInstallFailed, + ProviderReadinessReason::CredentialsWithheld, + ProviderReadinessReason::LocalPolicy, + ] { + let mut failed = complete.clone(); + failed.observation.as_mut().unwrap().reason = reason.into(); + assert_ne!( + evaluate(&receipt, Some(&failed)).state, + ProviderReadinessState::Ready as i32 + ); + } + for (credentials, policy, process, reason) in [ + ( + false, + true, + true, + ProviderReadinessReason::WaitingForCredentials, + ), + (true, false, true, ProviderReadinessReason::WaitingForPolicy), + ( + true, + true, + false, + ProviderReadinessReason::WaitingForProcess, + ), + ] { + let mut partial = complete.clone(); + let observation = partial.observation.as_mut().unwrap(); + observation.credentials_installed = credentials; + observation.policy_active = policy; + observation.launch_environment_installed = process; + assert_eq!(evaluate(&receipt, Some(&partial)).reason, reason as i32); + } + let mut incompatible = complete.clone(); + incompatible.supported = false; + assert_eq!( + evaluate(&receipt, Some(&incompatible)).reason, + ProviderReadinessReason::UnsupportedSupervisor as i32 + ); + let mut expired = complete.clone(); + expired.last_seen -= Duration::from_secs(u64::from(OBSERVATION_TTL_SECONDS) + 1); + assert_eq!( + evaluate(&receipt, Some(&expired)).reason, + ProviderReadinessReason::SupervisorLeaseExpired as i32 + ); + let stopped = evaluate_status( + receipt.clone(), + ProviderReadinessReason::Unspecified, + receipt.desired.as_ref().unwrap(), + ProviderReadinessReason::Unspecified, + false, + &hello.instance_id, + Some(&complete), + ) + .unwrap(); + assert_eq!( + stopped.reason, + ProviderReadinessReason::SupervisorDisconnected as i32 + ); + let mut missing = complete; + missing + .observation + .as_mut() + .unwrap() + .process_instance_id + .clear(); + assert_eq!( + evaluate(&receipt, Some(&missing)).reason, + ProviderReadinessReason::WaitingForProcess as i32 + ); +} + +#[test] +fn boundary_ack_is_bound_to_one_supervisor_session() { + let registry = TestRegistry::default(); + let hello = hello(); + let receipt = receipt(&hello); + let session = registry.register(&hello).unwrap(); + let mut observation = installed(&hello, &session, &receipt); + observation.process_instance_id.clear(); + assert!( + registry + .accept(&hello.sandbox_id, &session, observation.clone()) + .is_err() + ); + observation.launch_environment_installed = false; + registry + .accept(&hello.sandbox_id, &session, observation.clone()) + .unwrap(); + assert_eq!( + evaluate( + &receipt, + registry.snapshot(&hello.sandbox_id).unwrap().as_ref() + ) + .reason, + ProviderReadinessReason::WaitingForProcess as i32 + ); + observation.sequence = 2; + observation.launch_environment_installed = true; + observation.process_instance_id = Uuid::new_v4().to_string(); + registry + .accept(&hello.sandbox_id, &session, observation.clone()) + .unwrap(); + assert_eq!( + evaluate( + &receipt, + registry.snapshot(&hello.sandbox_id).unwrap().as_ref() + ) + .state, + ProviderReadinessState::Ready as i32 + ); + observation.sequence = 3; + observation.process_instance_id = Uuid::new_v4().to_string(); + assert!( + registry + .accept(&hello.sandbox_id, &session, observation) + .is_err() + ); +} + +#[test] +fn superseded_authority_cannot_complete_an_older_receipt() { + let registry = TestRegistry::default(); + let hello = hello(); + let receipt = receipt(&hello); + let session_id = registry.register(&hello).unwrap(); + registry + .accept( + &hello.sandbox_id, + &session_id, + installed(&hello, &session_id, &receipt), + ) + .unwrap(); + let session = registry.snapshot(&hello.sandbox_id).unwrap(); + for field in 0..5 { + let mut current = receipt.desired.clone().unwrap(); + match field { + 0 => current.attachment_epoch = Uuid::new_v4().to_string(), + 1 => current.provider_resource_version += 1, + 2 => current.provider_env_revision = 1, + 3 => current.config_revision = 1, + _ => current.policy_hash = "dcba".to_string(), + } + let status = evaluate_status( + receipt.clone(), + ProviderReadinessReason::Unspecified, + ¤t, + ProviderReadinessReason::Unspecified, + true, + &hello.instance_id, + session.as_ref(), + ) + .unwrap(); + assert_eq!(status.state, ProviderReadinessState::Superseded as i32); + } + let failed_snapshot = evaluate_status( + receipt.clone(), + ProviderReadinessReason::SnapshotMismatch, + receipt.desired.as_ref().unwrap(), + ProviderReadinessReason::Unspecified, + true, + &hello.instance_id, + session.as_ref(), + ) + .unwrap(); + assert_eq!(failed_snapshot.state, ProviderReadinessState::Failed as i32); +} + +#[test] +fn older_failed_observation_keeps_new_receipt_pending_until_matching_report() { + let registry = TestRegistry::default(); + let hello = hello(); + let original = receipt(&hello); + let session_id = registry.register(&hello).unwrap(); + let mut failed = installed(&hello, &session_id, &original); + failed.reason = ProviderReadinessReason::CredentialInstallFailed.into(); + registry + .accept(&hello.sandbox_id, &session_id, failed) + .unwrap(); + + let mut replacement = receipt(&hello); + replacement.desired = original.desired; + let desired = replacement.desired.as_mut().unwrap(); + desired.provider_resource_version += 1; + desired.provider_env_revision = 1; + let pending = evaluate( + &replacement, + registry.snapshot(&hello.sandbox_id).unwrap().as_ref(), + ); + assert_eq!(pending.state, ProviderReadinessState::Pending as i32); + assert_eq!( + pending.reason, + ProviderReadinessReason::SnapshotMismatch as i32 + ); + + let mut matching = installed(&hello, &session_id, &replacement); + matching.sequence = 2; + matching.reason = ProviderReadinessReason::CredentialInstallFailed.into(); + registry + .accept(&hello.sandbox_id, &session_id, matching.clone()) + .unwrap(); + let failed = evaluate( + &replacement, + registry.snapshot(&hello.sandbox_id).unwrap().as_ref(), + ); + assert_eq!(failed.state, ProviderReadinessState::Failed as i32); + assert_eq!( + failed.reason, + ProviderReadinessReason::CredentialInstallFailed as i32 + ); + + matching.sequence = 3; + matching.reason = ProviderReadinessReason::Unspecified.into(); + registry + .accept(&hello.sandbox_id, &session_id, matching) + .unwrap(); + assert_eq!( + evaluate( + &replacement, + registry.snapshot(&hello.sandbox_id).unwrap().as_ref() + ) + .state, + ProviderReadinessState::Ready as i32 + ); +} + +#[tokio::test] +async fn attach_waiting_for_update_captures_published_revision_and_becomes_ready() { + use openshell_core::proto::{ + AttachSandboxProviderRequest, CreateProviderRequest, UpdateProviderRequest, + }; + + let state = test_server_state().await; + let hello = hello(); + let mut sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: hello.sandbox_id.clone(), + name: "attach-race".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + sandbox + .status + .as_mut() + .unwrap() + .main_process_instance_id + .clone_from(&hello.instance_id); + state.store.put_message(&sandbox).await.unwrap(); + let provider = |value: &str| Provider { + metadata: Some(ObjectMeta { + name: "work-github".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + r#type: "github".to_string(), + credentials: HashMap::from([("GITHUB_TOKEN".to_string(), value.to_string())]), + ..Default::default() + }; + let initial = super::super::provider::handle_create_provider( + &state, + authed_request(CreateProviderRequest { + request_id: String::new(), + provider: Some(provider("synthetic-first")), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + .unwrap() + .into_inner() + .provider + .unwrap(); + + // The credential driver's gate holds UpdateProvider inside the shared + // mutation guard while the attach request reaches that same guard. + let (store_hit, release_store) = state.credentials.gate_next_store(); + let update_state = Arc::clone(&state); + let replacement = provider("synthetic-second"); + let update = tokio::spawn(async move { + super::super::provider::handle_update_provider( + &update_state, + authed_request(UpdateProviderRequest { + request_id: String::new(), + provider: Some(replacement), + credential_expiration_times: HashMap::new(), + clear_credential_expiration_keys: Vec::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + }); + tokio::time::timeout(Duration::from_secs(5), store_hit) + .await + .unwrap() + .unwrap(); + let attach_wait_probe = Arc::new(tokio::sync::Notify::new()); + let mut attach_request = authed_request(AttachSandboxProviderRequest { + request_id: String::new(), + sandbox_name: "attach-race".to_string(), + provider_name: "work-github".to_string(), + expected_resource_version: 0, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }); + attach_request + .extensions_mut() + .insert(Arc::clone(&attach_wait_probe)); + let attach_state = Arc::clone(&state); + let attach = tokio::spawn(async move { + super::super::sandbox::handle_attach_sandbox_provider(&attach_state, attach_request).await + }); + tokio::time::timeout(Duration::from_secs(5), attach_wait_probe.notified()) + .await + .unwrap(); + release_store.send(()).unwrap(); + let published = tokio::time::timeout(Duration::from_secs(5), update) + .await + .unwrap() + .unwrap() + .unwrap() + .into_inner() + .provider + .unwrap(); + let attached = tokio::time::timeout(Duration::from_secs(5), attach) + .await + .unwrap() + .unwrap() + .unwrap() + .into_inner(); + assert!(attached.attached); + let receipt = attached.receipt.unwrap(); + let desired = receipt.desired.as_ref().unwrap(); + let published_version = published.metadata.as_ref().unwrap().resource_version; + assert_ne!( + published_version, + initial.metadata.as_ref().unwrap().resource_version + ); + assert_eq!(desired.provider_resource_version, published_version); + assert_eq!(desired.provider_id, published.object_id()); + + let session_id = register_session(&state.supervisor_sessions, &hello).unwrap(); + state + .supervisor_sessions + .accept_provider_readiness( + &hello.sandbox_id, + &hello.instance_id, + installed(&hello, &session_id, &receipt), + ) + .unwrap(); + let status = handle_get_sandbox_provider_status( + &state, + authed_request(GetSandboxProviderStatusRequest { + sandbox_name: "attach-race".to_string(), + provider_name: "work-github".to_string(), + receipt_id: receipt.receipt_id, + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + .unwrap() + .into_inner() + .status + .unwrap(); + assert_eq!(status.state, ProviderReadinessState::Ready as i32); +} + +#[tokio::test] +async fn status_rejects_oversized_provider_name_before_persisting_receipt() { + let state = test_server_state().await; + let sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: Uuid::new_v4().to_string(), + name: "s1".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + let response = handle_get_sandbox_provider_status( + &state, + authed_request(GetSandboxProviderStatusRequest { + sandbox_name: "s1".to_string(), + provider_name: "x".repeat(super::super::MAX_NAME_LEN + 1), + receipt_id: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await; + let receipt_count = state + .store + .count_in_workspace(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, "default") + .await + .unwrap(); + assert_eq!(receipt_count, 0, "invalid status query persisted a receipt"); + let error = response.unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert_eq!(error.message(), "provider_name exceeds maximum length"); +} + +#[tokio::test] +async fn status_accepts_maximum_provider_name_and_receipt_only_lookup() { + let state = test_server_state().await; + let sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: Uuid::new_v4().to_string(), + name: "s1".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + let provider_name = "x".repeat(super::super::MAX_NAME_LEN); + let provider = Provider { + metadata: Some(ObjectMeta { + id: Uuid::new_v4().to_string(), + name: provider_name.clone(), + workspace: "default".to_string(), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&provider).await.unwrap(); + let response = handle_get_sandbox_provider_status( + &state, + authed_request(GetSandboxProviderStatusRequest { + sandbox_name: "s1".to_string(), + provider_name: provider_name.clone(), + receipt_id: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + .unwrap() + .into_inner(); + let receipt = response.status.unwrap().receipt.unwrap(); + assert_eq!(receipt.provider_name, provider_name); + assert_eq!(receipt.kind, ProviderMutationKind::Observe as i32); + assert!(receipt.desired.as_ref().unwrap().provider_id.is_empty()); + + // Receipt-only requery retains the persisted detached-provider intent even + // after its record is deleted, without creating another observation. + state + .store + .delete(Provider::object_type(), provider.object_id()) + .await + .unwrap(); + let repeated = handle_get_sandbox_provider_status( + &state, + authed_request(GetSandboxProviderStatusRequest { + sandbox_name: "s1".to_string(), + provider_name: String::new(), + receipt_id: receipt.receipt_id.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(repeated.status.unwrap().receipt, Some(receipt)); + assert_eq!( + state + .store + .count_in_workspace(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, "default") + .await + .unwrap(), + 1 + ); +} + +async fn observation_fixture() -> ( + Arc, + Sandbox, + Provider, + GetSandboxProviderStatusRequest, +) { + let state = test_server_state().await; + let sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: Uuid::new_v4().to_string(), + name: "observe-sandbox".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + policy: Some(openshell_policy::restrictive_default_policy()), + provider_attachment_epoch: Uuid::new_v4().to_string(), + ..Default::default() + }), + ..Default::default() + }; + let provider = Provider { + metadata: Some(ObjectMeta { + id: Uuid::new_v4().to_string(), + name: "observe-provider".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&sandbox).await.unwrap(); + state.store.put_message(&provider).await.unwrap(); + let query = GetSandboxProviderStatusRequest { + sandbox_name: "observe-sandbox".to_string(), + provider_name: "observe-provider".to_string(), + receipt_id: String::new(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }; + (state, sandbox, provider, query) +} + +#[tokio::test] +async fn repeated_and_concurrent_receiptless_status_reuses_one_operation() { + let (state, _, _, query) = observation_fixture().await; + let results = futures::future::join_all( + (0..8).map(|_| handle_get_sandbox_provider_status(&state, authed_request(query.clone()))), + ) + .await; + let receipts: Vec<_> = results + .into_iter() + .map(|result| { + result + .unwrap() + .into_inner() + .status + .unwrap() + .receipt + .unwrap() + }) + .collect(); + let first = receipts.first().unwrap(); + assert!(receipts.iter().all(|receipt| receipt == first)); + let repeated = handle_get_sandbox_provider_status(&state, authed_request(query)) + .await + .unwrap() + .into_inner() + .status + .unwrap() + .receipt + .unwrap(); + assert_eq!(&repeated, first); + assert_eq!( + state + .store + .count_in_workspace(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, "default") + .await + .unwrap(), + 1 + ); +} + +#[tokio::test] +async fn receiptless_status_changed_target_creates_a_distinct_operation() { + let (state, mut sandbox, _, query) = observation_fixture().await; + let original = handle_get_sandbox_provider_status(&state, authed_request(query.clone())) + .await + .unwrap() + .into_inner() + .status + .unwrap() + .receipt + .unwrap(); + sandbox.spec.as_mut().unwrap().provider_attachment_epoch = Uuid::new_v4().to_string(); + state.store.put_message(&sandbox).await.unwrap(); + let replacement = handle_get_sandbox_provider_status(&state, authed_request(query)) + .await + .unwrap() + .into_inner() + .status + .unwrap() + .receipt + .unwrap(); + assert_ne!(replacement.receipt_id, original.receipt_id); + assert_ne!(replacement.desired, original.desired); + assert_eq!( + state + .store + .count_in_workspace(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, "default") + .await + .unwrap(), + 2 + ); +} + +#[tokio::test] +async fn receiptless_status_unknown_provider_does_not_persist() { + let (state, _, provider, query) = observation_fixture().await; + state + .store + .delete(Provider::object_type(), provider.object_id()) + .await + .unwrap(); + let error = handle_get_sandbox_provider_status(&state, authed_request(query)) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::NotFound); + assert_eq!(error.message(), "provider not found"); + assert_eq!( + state + .store + .count_in_workspace(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, "default") + .await + .unwrap(), + 0 + ); +} + +#[tokio::test] +async fn stored_change_is_bound_to_its_sandbox_and_provider() { + let state = test_server_state().await; + let mut owner = Sandbox { + metadata: Some(ObjectMeta { + id: Uuid::new_v4().to_string(), + name: "owner".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + provider_attachment_epoch: Uuid::new_v4().to_string(), + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + ..Default::default() + }; + state.store.put_message(&owner).await.unwrap(); + let receipt = record_provider_mutation( + &state, + &owner, + "provider-owner", + ProviderMutationKind::Detach, + None, + &Uuid::new_v4().to_string(), + ) + .await + .unwrap(); + owner.metadata.as_mut().unwrap().id = Uuid::new_v4().to_string(); + owner.metadata.as_mut().unwrap().name = "other".to_string(); + state.store.put_message(&owner).await.unwrap(); + for (sandbox_name, provider_name) in [("other", "provider-owner"), ("owner", "other-provider")] + { + let request = GetSandboxProviderStatusRequest { + sandbox_name: sandbox_name.to_string(), + provider_name: provider_name.to_string(), + receipt_id: receipt.receipt_id.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }; + assert_eq!( + handle_get_sandbox_provider_status(&state, authed_request(request)) + .await + .unwrap_err() + .code(), + tonic::Code::NotFound + ); + } +} + +#[tokio::test] +async fn detach_receipt_persists_but_gateway_restart_requires_fresh_installation() { + let state = test_server_state().await; + let hello = hello(); + let mut sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: hello.sandbox_id.clone(), + name: "readiness".to_string(), + workspace: "default".to_string(), + ..Default::default() + }), + spec: Some(SandboxSpec { + provider_attachment_epoch: Uuid::new_v4().to_string(), + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + sandbox + .status + .as_mut() + .unwrap() + .main_process_instance_id + .clone_from(&hello.instance_id); + state.store.put_message(&sandbox).await.unwrap(); + let receipt = record_provider_mutation( + &state, + &sandbox, + "detached", + ProviderMutationKind::Detach, + None, + &Uuid::new_v4().to_string(), + ) + .await + .unwrap(); + let record = state + .store + .get(CONFIG_UPDATE_OPERATION_OBJECT_TYPE, &receipt.receipt_id) + .await + .unwrap() + .unwrap(); + let stored = StoredConfigUpdateOperation::decode(record.payload.as_slice()).unwrap(); + assert_eq!( + stored.provider_snapshot_reason, + ProviderReadinessReason::Unspecified as i32 + ); + assert!( + state + .store + .put_if( + CONFIG_UPDATE_OPERATION_OBJECT_TYPE, + &receipt.receipt_id, + &receipt.receipt_id, + "default", + &record.payload, + None, + WriteCondition::MustCreate + ) + .await + .is_err() + ); + let query = GetSandboxProviderStatusRequest { + sandbox_name: "readiness".to_string(), + provider_name: "detached".to_string(), + receipt_id: receipt.receipt_id.clone(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }; + let initial = handle_get_sandbox_provider_status(&state, authed_request(query.clone())) + .await + .unwrap() + .into_inner() + .status + .unwrap(); + assert_eq!(initial.state, ProviderReadinessState::Persisted as i32); + let session_id = register_session(&state.supervisor_sessions, &hello).unwrap(); + state + .supervisor_sessions + .accept_provider_readiness( + &hello.sandbox_id, + &hello.instance_id, + installed(&hello, &session_id, &receipt), + ) + .unwrap(); + let ready = handle_get_sandbox_provider_status(&state, authed_request(query.clone())) + .await + .unwrap() + .into_inner() + .status + .unwrap(); + assert_eq!(ready.state, ProviderReadinessState::Revoked as i32); + + // A different replica may accept a replacement supervisor while this + // gateway still has the old local session and matching config hashes. + sandbox.status.as_mut().unwrap().main_process_instance_id = Uuid::new_v4().to_string(); + state.store.put_message(&sandbox).await.unwrap(); + let replaced = handle_get_sandbox_provider_status(&state, authed_request(query.clone())) + .await + .unwrap() + .into_inner() + .status + .unwrap(); + assert_eq!(replaced.state, ProviderReadinessState::Pending as i32); + assert_eq!( + replaced.reason, + ProviderReadinessReason::SupervisorDisconnected as i32 + ); + sandbox + .status + .as_mut() + .unwrap() + .main_process_instance_id + .clone_from(&hello.instance_id); + state.store.put_message(&sandbox).await.unwrap(); + + let mut restarted = test_server_state().await; + Arc::get_mut(&mut restarted).unwrap().store = Arc::clone(&state.store); + let after_restart = + handle_get_sandbox_provider_status(&restarted, authed_request(query.clone())) + .await + .unwrap() + .into_inner() + .status + .unwrap(); + assert_eq!( + after_restart.state, + ProviderReadinessState::Persisted as i32 + ); + assert_eq!(after_restart.receipt, Some(receipt)); + sandbox.spec.as_mut().unwrap().provider_attachment_epoch = Uuid::new_v4().to_string(); + state.store.put_message(&sandbox).await.unwrap(); + let changed = handle_get_sandbox_provider_status(&state, authed_request(query)) + .await + .unwrap() + .into_inner() + .status + .unwrap(); + assert_eq!(changed.state, ProviderReadinessState::Superseded as i32); +} diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 429a756c7c..25376a296a 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -29,12 +29,12 @@ use openshell_core::proto::{ ExecSandboxEvent, ExecSandboxExit, ExecSandboxInput, ExecSandboxRequest, ExecSandboxStderr, ExecSandboxStdout, GetSandboxRequest, GetSandboxTemplateRequest, ListSandboxProvidersRequest, ListSandboxProvidersResponse, ListSandboxTemplatesRequest, ListSandboxTemplatesResponse, - ListSandboxesRequest, ListSandboxesResponse, Provider, ResourceRequirements, - RevokeSshSessionRequest, RevokeSshSessionResponse, SandboxResources, SandboxResponse, - SandboxSpec, SandboxStreamEvent, SandboxTemplateResponse, SandboxWorkloadTemplate, - SandboxWorkloadTemplateProvenance, SshRelayTarget, StartSandboxRequest, StopSandboxRequest, - TcpForwardFrame, TcpForwardInit, TcpRelayTarget, WatchSandboxRequest, relay_open, - tcp_forward_init, + ListSandboxesRequest, ListSandboxesResponse, Provider, ProviderMutationKind, + ResourceRequirements, RevokeSshSessionRequest, RevokeSshSessionResponse, SandboxResources, + SandboxResponse, SandboxSpec, SandboxStreamEvent, SandboxTemplateResponse, + SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, SshRelayTarget, + StartSandboxRequest, StopSandboxRequest, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, + WatchSandboxRequest, relay_open, tcp_forward_init, }; use openshell_core::proto::{ BeginRootfsTarStagingRequest, BeginRootfsTarStagingResponse, Sandbox, SandboxPhase, @@ -172,6 +172,8 @@ pub(super) async fn handle_create_sandbox( request: Request, ) -> Result, Status> { let create_request = request.get_ref().clone(); + // Sandbox creation retains large configuration values across awaits. + // Box the inner future to keep this wrapper small for every caller. let result = Box::pin(handle_create_sandbox_inner(state, request)).await; let created_sandbox = result .as_ref() @@ -373,6 +375,10 @@ async fn handle_create_sandbox_inner( (resolved, Some(provenance)) }; + // Attachment identity belongs to the gateway. Accepting an epoch from a + // create request or workload template could revive stale installation proof. + spec.provider_attachment_epoch = uuid::Uuid::new_v4().to_string(); + // Leave an omitted command empty rather than persisting a concrete shell: // the sandbox boundary resolves the default login shell against the agent image // (bash when present, otherwise /bin/sh on minimal images like Alpine), @@ -1067,6 +1073,11 @@ pub(super) async fn handle_attach_sandbox_provider( request: Request, ) -> Result, Status> { let principal = super::extract_principal(&request)?; + #[cfg(test)] + let attach_wait_probe = request + .extensions() + .get::>() + .cloned(); let request = request.into_inner(); let authz = authorize_workspace_selector( &state.store, @@ -1093,20 +1104,27 @@ pub(super) async fn handle_attach_sandbox_provider( ))); } - get_provider_record(state.store.as_ref(), &workspace, &request.provider_name) - .await - .map_err(|err| { - if err.code() == tonic::Code::NotFound { - Status::failed_precondition(format!( - "provider '{}' not found", - request.provider_name - )) - } else { - err - } - })?; - + // The receipt must capture the provider revision selected by this + // serialized mutation, after any preceding credential update has finished. + #[cfg(test)] + if let Some(probe) = attach_wait_probe { + probe.notify_one(); + } let _sandbox_sync_guard = state.compute.sandbox_sync_guard().await; + let provider_record = + get_provider_record(state.store.as_ref(), &workspace, &request.provider_name) + .await + .map_err(|err| { + if err.code() == tonic::Code::NotFound { + Status::failed_precondition(format!( + "provider '{}' not found", + request.provider_name + )) + } else { + err + } + })?; + let sandbox = sandbox_by_name(state, &workspace, &request.sandbox_name).await?; let sandbox_id = sandbox .metadata @@ -1172,6 +1190,7 @@ pub(super) async fn handle_attach_sandbox_provider( let provider_name = request.provider_name.clone(); let attached = Arc::new(AtomicBool::new(false)); let attached_clone = attached.clone(); + let mutation_id = uuid::Uuid::new_v4().to_string(); let sandbox = state .store @@ -1179,16 +1198,22 @@ pub(super) async fn handle_attach_sandbox_provider( &sandbox_id, request.expected_resource_version, |sandbox| { + attached_clone.store(false, Ordering::Relaxed); let Some(ref mut spec) = sandbox.spec else { // Spec should always exist post-creation; if missing, fail CAS to surface error return; }; + if spec.provider_attachment_epoch.is_empty() { + spec.provider_attachment_epoch.clone_from(&mutation_id); + } + dedupe_provider_names(&mut spec.providers); if !spec.providers.iter().any(|name| name == &provider_name) && spec.providers.len() < MAX_PROVIDERS { spec.providers.push(provider_name.clone()); + spec.provider_attachment_epoch.clone_from(&mutation_id); attached_clone.store(true, Ordering::Relaxed); } }, @@ -1197,6 +1222,18 @@ pub(super) async fn handle_attach_sandbox_provider( .map_err(|e| super::persistence_error_to_status(e, "attach sandbox provider"))?; let attached = attached.load(Ordering::Relaxed); + let receipt = super::provider_readiness::record_provider_mutation( + state, + &sandbox, + &request.provider_name, + ProviderMutationKind::Attach, + Some(( + provider_record.object_id(), + provider_record.get_resource_version(), + )), + &mutation_id, + ) + .await?; info!( sandbox_name = %request.sandbox_name, @@ -1208,6 +1245,7 @@ pub(super) async fn handle_attach_sandbox_provider( Ok(Response::new(AttachSandboxProviderResponse { sandbox: Some(sandbox), attached, + receipt: Some(receipt), })) } @@ -1271,6 +1309,7 @@ pub(super) async fn handle_detach_sandbox_provider( let provider_name = request.provider_name.clone(); let detached = Arc::new(AtomicBool::new(false)); let detached_clone = detached.clone(); + let mutation_id = uuid::Uuid::new_v4().to_string(); let sandbox = state .store @@ -1278,14 +1317,20 @@ pub(super) async fn handle_detach_sandbox_provider( &sandbox_id, request.expected_resource_version, |sandbox| { + detached_clone.store(false, Ordering::Relaxed); let Some(ref mut spec) = sandbox.spec else { // Spec should always exist post-creation; if missing, fail CAS to surface error return; }; + if spec.provider_attachment_epoch.is_empty() { + spec.provider_attachment_epoch.clone_from(&mutation_id); + } + let before_len = spec.providers.len(); spec.providers.retain(|name| name != &provider_name); if spec.providers.len() != before_len { + spec.provider_attachment_epoch.clone_from(&mutation_id); detached_clone.store(true, Ordering::Relaxed); // Only dedupe after making a change dedupe_provider_names(&mut spec.providers); @@ -1296,6 +1341,15 @@ pub(super) async fn handle_detach_sandbox_provider( .map_err(|e| super::persistence_error_to_status(e, "detach sandbox provider"))?; let detached = detached.load(Ordering::Relaxed); + let receipt = super::provider_readiness::record_provider_mutation( + state, + &sandbox, + &request.provider_name, + ProviderMutationKind::Detach, + None, + &mutation_id, + ) + .await?; info!( sandbox_name = %request.sandbox_name, @@ -1307,6 +1361,7 @@ pub(super) async fn handle_detach_sandbox_provider( Ok(Response::new(DetachSandboxProviderResponse { sandbox: Some(sandbox), detached, + receipt: Some(receipt), })) } @@ -3282,6 +3337,7 @@ mod tests { #[test] fn sandbox_create_telemetry_uses_resolved_template_gpu_request() { let request = CreateSandboxRequest { + request_id: String::new(), spec: Some(SandboxSpec { providers: vec!["github".to_string()], policy: Some(openshell_core::proto::SandboxPolicy::default()), @@ -3321,6 +3377,7 @@ mod tests { #[test] fn sandbox_create_telemetry_falls_back_to_request_for_unresolved_template() { let request = CreateSandboxRequest { + request_id: String::new(), spec: Some(SandboxSpec { providers: vec!["github".to_string()], ..SandboxSpec::default() @@ -3758,6 +3815,7 @@ mod tests { handle_delete_sandbox_inner( &delete_state, authed_request(DeleteSandboxRequest { + request_id: String::new(), allow_missing: false, name: "reused-name".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -3821,6 +3879,7 @@ mod tests { let response = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, @@ -3862,6 +3921,7 @@ mod tests { let response = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, @@ -3900,6 +3960,7 @@ mod tests { let response = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, @@ -3951,6 +4012,7 @@ mod tests { let response = handle_detach_sandbox_provider( &state, authed_request(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, @@ -3976,6 +4038,7 @@ mod tests { let response = handle_detach_sandbox_provider( &state, authed_request(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "work-github".to_string(), expected_resource_version: 0, @@ -4023,6 +4086,7 @@ mod tests { let error = handle_detach_sandbox_provider( &state, authed_request(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "work-gcp".to_string(), expected_resource_version: 0, @@ -4091,6 +4155,7 @@ mod tests { let err = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "missing".to_string(), expected_resource_version: 0, @@ -4262,6 +4327,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "collision".to_string(), spec: Some(SandboxSpec { providers: vec!["provider-a".to_string(), "provider-b".to_string()], @@ -4290,6 +4356,7 @@ mod tests { let response = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "user-catalog".to_string(), spec: Some(SandboxSpec::default()), labels: HashMap::new(), @@ -4324,6 +4391,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "reserved-policy-key".to_string(), spec: Some(SandboxSpec { policy: Some(policy), @@ -4691,6 +4759,7 @@ mod tests { let response = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "annotated".to_string(), spec: Some(SandboxSpec::default()), labels: HashMap::new(), @@ -4749,6 +4818,7 @@ mod tests { let response = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "partial-id".to_string(), spec: Some(SandboxSpec { policy: Some(policy), @@ -4814,6 +4884,7 @@ mod tests { let response = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "kube-partial-id".to_string(), spec: Some(SandboxSpec { policy: Some(policy), @@ -4849,6 +4920,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "bad-label".to_string(), spec: Some(SandboxSpec::default()), labels: HashMap::from([("team".to_string(), "x".repeat(512))]), @@ -4880,6 +4952,7 @@ mod tests { handle_create_sandbox( &task_state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "guarded-create".to_string(), spec: Some(SandboxSpec { providers: vec!["work-github".to_string()], @@ -4921,6 +4994,7 @@ mod tests { let created = handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(test_workload_template("gpu-kata")), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -4977,6 +5051,7 @@ mod tests { let deleted = handle_delete_sandbox_template( &state, authed_request(DeleteSandboxTemplateRequest { + request_id: String::new(), allow_missing: false, name: "gpu-kata".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( @@ -5019,6 +5094,7 @@ mod tests { handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(gpu), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5037,6 +5113,7 @@ mod tests { handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(cpu), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5073,6 +5150,7 @@ mod tests { let err = handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(test_workload_template(" gpu-kata ")), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5111,6 +5189,7 @@ mod tests { crate::grpc::workspace::handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "beta".to_string(), labels: HashMap::new(), }), @@ -5124,6 +5203,7 @@ mod tests { let err = handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(template), workspace_scope: Some(openshell_core::proto::workspace_selector("default")), }), @@ -5161,6 +5241,7 @@ mod tests { let err = handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(template), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5300,6 +5381,7 @@ mod tests { let err = handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(test_workload_template("overflow")), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5331,6 +5413,7 @@ mod tests { handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(test_workload_template(&format!("overflow-{index}"))), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5379,6 +5462,7 @@ mod tests { "template", "resource_requirements", ], + &["provider_attachment_epoch"], ); } @@ -5386,6 +5470,7 @@ mod tests { message_name: &str, copied_from_create_request: &[&str], rejected_template_workload_overrides: &[&str], + generated_by_gateway: &[&str], ) { let pool = prost_reflect::DescriptorPool::decode(openshell_core::FILE_DESCRIPTOR_SET) .expect("decode descriptor set"); @@ -5395,8 +5480,16 @@ mod tests { let classified: std::collections::HashSet<&str> = copied_from_create_request .iter() .chain(rejected_template_workload_overrides.iter()) + .chain(generated_by_gateway.iter()) .copied() .collect(); + assert_eq!( + classified.len(), + copied_from_create_request.len() + + rejected_template_workload_overrides.len() + + generated_by_gateway.len(), + "every field must have exactly one create-time owner" + ); let actual: std::collections::HashSet = message .fields() .map(|field| field.name().to_string()) @@ -5407,7 +5500,8 @@ mod tests { classified.contains(field.as_str()), "{message_name}.{field} is not classified for template-backed sandbox creates. \ Add it to copied_from_create_request when callers own the create-time value, \ - or to rejected_template_workload_overrides when the workload template owns it." + to rejected_template_workload_overrides when the workload template owns it, \ + or to generated_by_gateway when the gateway replaces the caller's value." ); } @@ -5420,6 +5514,56 @@ mod tests { } } + #[tokio::test] + async fn create_sandbox_ignores_caller_provider_attachment_epoch() { + let state = test_server_state().await; + handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), + template: Some(test_workload_template("epoch-template")), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + .unwrap(); + let supplied_epoch = uuid::Uuid::new_v4().to_string(); + let mut generated_epochs = std::collections::HashSet::new(); + for (name, workload_template_name) in + [("direct-epoch", ""), ("template-epoch", "epoch-template")] + { + let created = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: name.to_string(), + spec: Some(SandboxSpec { + provider_attachment_epoch: supplied_epoch.clone(), + ..Default::default() + }), + workload_template_name: workload_template_name.to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner() + .sandbox + .unwrap(); + let epoch = &created.spec.as_ref().unwrap().provider_attachment_epoch; + assert_ne!(epoch, &supplied_epoch); + assert!(uuid::Uuid::parse_str(epoch).is_ok()); + assert!(generated_epochs.insert(epoch.clone())); + let stored = state + .store + .get_message::(created.object_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(&stored.spec.unwrap().provider_attachment_epoch, epoch); + } + } + #[tokio::test] async fn create_sandbox_from_workload_template_resolves_workload_and_preserves_governance() { let state = test_server_state().await; @@ -5431,6 +5575,7 @@ mod tests { handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(test_workload_template("gpu-kata")), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5455,6 +5600,7 @@ mod tests { let created = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "from-template".to_string(), spec: Some(SandboxSpec { providers: vec!["work-github".to_string()], @@ -5535,6 +5681,7 @@ mod tests { handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(template), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5547,6 +5694,7 @@ mod tests { let created = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "from-template".to_string(), spec: Some(SandboxSpec::default()), labels: HashMap::new(), @@ -5586,6 +5734,7 @@ mod tests { handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(template), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5598,6 +5747,7 @@ mod tests { let created = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "from-template".to_string(), spec: Some(SandboxSpec::default()), labels: HashMap::new(), @@ -5637,6 +5787,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "from-corrupt".to_string(), spec: Some(SandboxSpec::default()), labels: HashMap::new(), @@ -5661,6 +5812,7 @@ mod tests { handle_create_sandbox_template( &state, authed_request(CreateSandboxTemplateRequest { + request_id: String::new(), template: Some(test_workload_template("gpu-kata")), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -5673,6 +5825,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "bad-template-create".to_string(), spec: Some(SandboxSpec { environment: HashMap::from([("INLINE".to_string(), "blocked".to_string())]), @@ -5701,6 +5854,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "bad-template-create".to_string(), spec: Some(SandboxSpec::default()), labels: HashMap::new(), @@ -5726,6 +5880,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "bad-template-create".to_string(), spec: Some(SandboxSpec { providers: (0..=MAX_PROVIDERS).map(|i| format!("p-{i}")).collect(), @@ -5754,6 +5909,7 @@ mod tests { let err = handle_create_sandbox( &state, authed_request(CreateSandboxRequest { + request_id: String::new(), name: "bad-direct-create".to_string(), spec: Some(SandboxSpec { providers: (0..=MAX_PROVIDERS).map(|i| format!("p-{i}")).collect(), @@ -5797,6 +5953,7 @@ mod tests { let err = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "provider-b".to_string(), expected_resource_version: 0, @@ -5844,6 +6001,7 @@ mod tests { let response = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "provider-31".to_string(), expected_resource_version: 0, @@ -5899,6 +6057,7 @@ mod tests { let err = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "provider-32".to_string(), expected_resource_version: 0, @@ -5946,6 +6105,7 @@ mod tests { let err = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: long_name, expected_resource_version: 0, @@ -5973,6 +6133,7 @@ mod tests { let err = handle_detach_sandbox_provider( &state, authed_request(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: long_name, expected_resource_version: 0, @@ -6185,6 +6346,7 @@ mod tests { let response = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "github".to_string(), expected_resource_version: current_version, @@ -6237,6 +6399,7 @@ mod tests { let err = handle_attach_sandbox_provider( &state, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "github".to_string(), expected_resource_version: 99, @@ -6300,6 +6463,7 @@ mod tests { let response = handle_detach_sandbox_provider( &state, authed_request(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "github".to_string(), expected_resource_version: current_version, @@ -6352,6 +6516,7 @@ mod tests { let err = handle_detach_sandbox_provider( &state, authed_request(DetachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: "github".to_string(), expected_resource_version: 99, @@ -6433,6 +6598,7 @@ mod tests { handle_attach_sandbox_provider( &state_clone, authed_request(AttachSandboxProviderRequest { + request_id: String::new(), sandbox_name: "work".to_string(), provider_name: format!("provider-{i}"), expected_resource_version: initial_version, @@ -6497,6 +6663,7 @@ mod tests { crate::grpc::workspace::handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "beta".to_string(), labels: HashMap::new(), }), @@ -6813,6 +6980,7 @@ mod tests { let err = handle_delete_sandbox( &state, non_member_request(DeleteSandboxRequest { + request_id: String::new(), allow_missing: false, workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), name: "any".into(), @@ -6830,6 +6998,7 @@ mod tests { handle_stop_sandbox( &state, non_member_request(StopSandboxRequest { + request_id: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), name: "any".into(), }), @@ -6838,6 +7007,7 @@ mod tests { handle_start_sandbox( &state, non_member_request(StartSandboxRequest { + request_id: String::new(), workspace_scope: Some(openshell_core::proto::workspace_selector("no-such-ws")), name: "any".into(), }), diff --git a/crates/openshell-server/src/grpc/service.rs b/crates/openshell-server/src/grpc/service.rs index 2d142cd082..544eb4f5d0 100644 --- a/crates/openshell-server/src/grpc/service.rs +++ b/crates/openshell-server/src/grpc/service.rs @@ -434,6 +434,7 @@ mod tests { let exposed = handle_expose_service( &state, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "web".to_string(), target_port: 8080, @@ -486,6 +487,7 @@ mod tests { let deleted = handle_delete_service( &state, authed_request(DeleteServiceRequest { + request_id: String::new(), allow_missing: false, sandbox: "my-sandbox".to_string(), service: "web".to_string(), @@ -544,6 +546,7 @@ mod tests { handle_expose_service( &state1, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "web".to_string(), target_port: 8080, @@ -561,6 +564,7 @@ mod tests { handle_expose_service( &state2, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "web".to_string(), target_port: 9090, @@ -612,6 +616,7 @@ mod tests { handle_expose_service( &state, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "web".to_string(), target_port: 7070, @@ -630,6 +635,7 @@ mod tests { handle_expose_service( &state1, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "web".to_string(), target_port: 8080, @@ -647,6 +653,7 @@ mod tests { handle_expose_service( &state2, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "web".to_string(), target_port: 9090, @@ -704,6 +711,7 @@ mod tests { crate::grpc::workspace::handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "beta".to_string(), labels: HashMap::new(), }), @@ -735,6 +743,7 @@ mod tests { handle_expose_service( &state, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "web".to_string(), target_port: 8080, @@ -750,6 +759,7 @@ mod tests { handle_expose_service( &state, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "web".to_string(), target_port: 9090, @@ -839,6 +849,7 @@ mod tests { let deleted = handle_delete_service( &state, authed_request(DeleteServiceRequest { + request_id: String::new(), allow_missing: false, sandbox: "my-sandbox".to_string(), service: "web".to_string(), @@ -891,6 +902,7 @@ mod tests { handle_expose_service( &state, authed_request(ExposeServiceRequest { + request_id: String::new(), sandbox: "my-sandbox".to_string(), service: "api".to_string(), target_port: 3000, diff --git a/crates/openshell-server/src/grpc/workspace.rs b/crates/openshell-server/src/grpc/workspace.rs index 729dfd79ee..98a13590a4 100644 --- a/crates/openshell-server/src/grpc/workspace.rs +++ b/crates/openshell-server/src/grpc/workspace.rs @@ -454,6 +454,21 @@ pub(super) async fn handle_delete_workspace( })) } +pub(super) fn authorize_member_role(role: i32, grant: AuthGrant) -> Result<(), Status> { + let role = WorkspaceRole::try_from(role).unwrap_or(WorkspaceRole::Unspecified); + if role == WorkspaceRole::Unspecified { + return Err(Status::invalid_argument( + "role must be USER or ADMIN, not UNSPECIFIED", + )); + } + if role == WorkspaceRole::Admin && grant != AuthGrant::PlatformAdmin { + return Err(Status::permission_denied( + "only platform admins can assign the workspace admin role", + )); + } + Ok(()) +} + pub(super) async fn handle_add_workspace_member( state: &Arc, request: Request, @@ -477,17 +492,7 @@ pub(super) async fn handle_add_workspace_member( return Err(Status::invalid_argument("principal_subject is required")); } - let role = WorkspaceRole::try_from(req.role).unwrap_or(WorkspaceRole::Unspecified); - if role == WorkspaceRole::Unspecified { - return Err(Status::invalid_argument( - "role must be USER or ADMIN, not UNSPECIFIED", - )); - } - if role == WorkspaceRole::Admin && authz.grant != AuthGrant::PlatformAdmin { - return Err(Status::permission_denied( - "only platform admins can assign the workspace admin role", - )); - } + authorize_member_role(req.role, authz.grant)?; let count = state .store @@ -658,6 +663,7 @@ mod tests { let resp = handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "new-ws".to_string(), labels: HashMap::from([("env".to_string(), "test".to_string())]), }), @@ -686,6 +692,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "dup-ws".to_string(), labels: HashMap::new(), }), @@ -696,6 +703,7 @@ mod tests { let err = handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "dup-ws".to_string(), labels: HashMap::new(), }), @@ -713,6 +721,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "fetch-me".to_string(), labels: HashMap::from([("team".to_string(), "infra".to_string())]), }), @@ -786,6 +795,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "ephemeral".to_string(), labels: HashMap::new(), }), @@ -811,6 +821,7 @@ mod tests { let err = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "ephemeral".to_string(), }), @@ -833,6 +844,7 @@ mod tests { let resp = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "ephemeral".to_string(), }), @@ -853,6 +865,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "templated".to_string(), labels: HashMap::new(), }), @@ -878,6 +891,7 @@ mod tests { let err = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "templated".to_string(), }), @@ -904,6 +918,7 @@ mod tests { let resp = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "templated".to_string(), }), @@ -924,6 +939,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "sessioned".to_string(), labels: HashMap::new(), }), @@ -952,6 +968,7 @@ mod tests { let err = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "sessioned".to_string(), }), @@ -973,6 +990,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "profiles-ws".to_string(), labels: HashMap::new(), }), @@ -998,6 +1016,7 @@ mod tests { let err = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "profiles-ws".to_string(), }), @@ -1024,6 +1043,7 @@ mod tests { let resp = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "profiles-ws".to_string(), }), @@ -1044,6 +1064,7 @@ mod tests { let err = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "default".to_string(), }), @@ -1060,6 +1081,7 @@ mod tests { let resp = handle_add_workspace_member( &state, authed_request(AddWorkspaceMemberRequest { + request_id: String::new(), workspace: "default".to_string(), principal_subject: "alice@example.com".to_string(), role: WorkspaceRole::Admin.into(), @@ -1076,6 +1098,7 @@ mod tests { handle_add_workspace_member( &state, authed_request(AddWorkspaceMemberRequest { + request_id: String::new(), workspace: "default".to_string(), principal_subject: "bob@example.com".to_string(), role: WorkspaceRole::User.into(), @@ -1106,6 +1129,7 @@ mod tests { handle_add_workspace_member( &state, authed_request(AddWorkspaceMemberRequest { + request_id: String::new(), workspace: "default".to_string(), principal_subject: "charlie@example.com".to_string(), role: WorkspaceRole::User.into(), @@ -1117,6 +1141,7 @@ mod tests { let resp = handle_remove_workspace_member( &state, authed_request(RemoveWorkspaceMemberRequest { + request_id: String::new(), allow_missing: false, workspace: "default".to_string(), principal_subject: "charlie@example.com".to_string(), @@ -1152,6 +1177,7 @@ mod tests { handle_add_workspace_member( &state, authed_request(AddWorkspaceMemberRequest { + request_id: String::new(), workspace: "default".to_string(), principal_subject: "dave@example.com".to_string(), role: WorkspaceRole::User.into(), @@ -1163,6 +1189,7 @@ mod tests { let err = handle_add_workspace_member( &state, authed_request(AddWorkspaceMemberRequest { + request_id: String::new(), workspace: "default".to_string(), principal_subject: "dave@example.com".to_string(), role: WorkspaceRole::Admin.into(), @@ -1181,6 +1208,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "cleanup-test".to_string(), labels: HashMap::new(), }), @@ -1191,6 +1219,7 @@ mod tests { handle_add_workspace_member( &state, authed_request(AddWorkspaceMemberRequest { + request_id: String::new(), workspace: "cleanup-test".to_string(), principal_subject: "alice@example.com".to_string(), role: WorkspaceRole::Admin.into(), @@ -1202,6 +1231,7 @@ mod tests { handle_add_workspace_member( &state, authed_request(AddWorkspaceMemberRequest { + request_id: String::new(), workspace: "cleanup-test".to_string(), principal_subject: "bob@example.com".to_string(), role: WorkspaceRole::User.into(), @@ -1226,6 +1256,7 @@ mod tests { let resp = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "cleanup-test".to_string(), }), @@ -1294,6 +1325,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "term-test".to_string(), labels: HashMap::new(), }), @@ -1319,6 +1351,7 @@ mod tests { let err = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "term-test".to_string(), }), @@ -1347,6 +1380,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "dying-ws".to_string(), labels: HashMap::new(), }), @@ -1373,6 +1407,7 @@ mod tests { let _ = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "dying-ws".to_string(), }), @@ -1393,6 +1428,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "idempotent-ws".to_string(), labels: HashMap::new(), }), @@ -1419,6 +1455,7 @@ mod tests { let _ = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "idempotent-ws".to_string(), }), @@ -1436,6 +1473,7 @@ mod tests { let resp = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "idempotent-ws".to_string(), }), @@ -1456,6 +1494,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "cleanup-retry".to_string(), labels: HashMap::new(), }), @@ -1466,6 +1505,7 @@ mod tests { let err = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "cleanup-retry".to_string(), }), @@ -1485,6 +1525,7 @@ mod tests { let retry = handle_delete_workspace( &state, Request::new(DeleteWorkspaceRequest { + request_id: String::new(), allow_missing: false, name: "cleanup-retry".to_string(), }), @@ -1516,6 +1557,7 @@ mod tests { handle_create_workspace( &state, Request::new(CreateWorkspaceRequest { + request_id: String::new(), name: "labeled-ws".to_string(), labels: labels.clone(), }), diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index d68c93c6b6..47eefb7704 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -18,6 +18,7 @@ pub mod certgen; pub mod cli; mod compute; pub mod config_file; +mod config_update_operation; mod credentials; mod defaults; mod gateway_listener; diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index f112522558..ac31017880 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -447,11 +447,14 @@ where let context = gateway_interceptor_context(req.extensions()); let principal = req.extensions().get::().cloned(); - let (parts, body) = req.into_parts(); + let (mut parts, body) = req.into_parts(); let mut body = match collect_intercepted_grpc_body(body).await { Ok(body) => body, Err(status) => return Ok(status.into_http()), }; + // Retain only in memory. evaluate_request below validates the single + // uncompressed frame before this extension reaches typed dispatch. + let original_body = body.clone(); if let Some(state) = state.as_ref() { body = match hydrate_update_provider_identity(&path, body, state, principal.as_ref()) @@ -467,6 +470,12 @@ where Err(status) => return Ok(status.into_http()), }; + parts + .extensions + .insert(crate::grpc::mutation_replay::OriginalMutation( + original_body[GRPC_FRAME_HEADER_LEN..].to_vec(), + )); + let req = Request::from_parts( parts, boxed_body_from_bytes(Bytes::from(intercepted.body.clone())), @@ -474,6 +483,10 @@ where let response = inner.ready().await?.call(req).await?; if grpc_status_from_response(&response) != "0" + || response + .headers() + .get("openshell-replayed") + .is_some_and(|value| value == "true") || !interceptors.has_post_commit(&intercepted) { return Ok(response); @@ -1854,6 +1867,196 @@ mod tests { interceptor_task.abort(); } + #[derive(Clone, Default)] + struct ReplayTestInterceptor { + modifications: Arc, + validations: Arc, + observations: Arc, + deny: Arc, + name: Arc>, + } + + #[tonic::async_trait] + impl GatewayInterceptor for ReplayTestInterceptor { + async fn describe( + &self, + request: tonic::Request, + ) -> Result, tonic::Status> { + let mut manifest = PostCommitTestInterceptor + .describe(request) + .await? + .into_inner(); + manifest.bindings.push(InterceptorBinding { + id: "validate-create".into(), + selector: manifest.bindings[0].selector.clone(), + phases: vec![ + GatewayInterceptorPhase::ModifyOperation.into(), + GatewayInterceptorPhase::Validate.into(), + ], + failure_policy: "fail_closed".into(), + }); + Ok(tonic::Response::new(manifest)) + } + + async fn evaluate( + &self, + request: tonic::Request, + ) -> Result, tonic::Status> { + use openshell_core::proto::gateway_interceptor::v1::{ + JsonPatch, interceptor_evaluation::Phase, + }; + let mut result = InterceptorResult { + allowed: true, + ..Default::default() + }; + match request.into_inner().phase.unwrap() { + Phase::ModifyOperation(_) => { + self.modifications.fetch_add(1, Ordering::SeqCst); + result.patches.push(JsonPatch { + op: "replace".into(), + path: "/name".into(), + value: Some(prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue( + self.name.lock().unwrap().clone(), + )), + }), + ..Default::default() + }); + } + Phase::Validate(_) => { + self.validations.fetch_add(1, Ordering::SeqCst); + result.allowed = !self.deny.load(Ordering::SeqCst); + result.reason = "current policy denies creation".into(); + result.status_code = "PERMISSION_DENIED".into(); + } + Phase::PostCommit(_) => { + self.observations.fetch_add(1, Ordering::SeqCst); + } + } + Ok(tonic::Response::new(result)) + } + + async fn snapshot_provider_profiles( + &self, + request: tonic::Request, + ) -> Result, tonic::Status> { + PostCommitTestInterceptor + .snapshot_provider_profiles(request) + .await + } + } + + #[tokio::test] + async fn mutation_replay_revalidates_interceptors_and_observes_commit_once() { + use openshell_core::proto::{ + SandboxResponse, SandboxSpec, open_shell_server::OpenShellServer, + }; + let interceptor = ReplayTestInterceptor::default(); + *interceptor.name.lock().unwrap() = "intercepted-create".into(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let service = interceptor.clone(); + let task = tokio::spawn(async move { + tonic::transport::Server::builder() + .add_service(GatewayInterceptorServer::new(service)) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await + .unwrap(); + }); + let runtime = openshell_gateway_interceptors::initialize(vec![GatewayInterceptorConfig { + name: "post-commit-test".into(), + grpc_endpoint: format!("http://{address}"), + ..Default::default() + }]) + .await + .unwrap(); + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("key"); + std::fs::write(&key, b"test-only-private-key").unwrap(); + let mut state = crate::grpc::test_support::test_server_state().await; + Arc::get_mut(&mut state).unwrap().config.gateway_jwt = + Some(openshell_core::config::GatewayJwtConfig { + signing_key_path: key, + public_key_path: directory.path().join("public"), + kid_path: directory.path().join("kid"), + gateway_id: "test".into(), + ttl_secs: None, + }); + let inner = OpenShellServer::new(OpenShellService::new(state.clone())); + let mut service = GatewayInterceptorGrpcService::new(inner, runtime, Some(state)); + let input = CreateSandboxRequest { + name: "client-original".into(), + request_id: uuid::Uuid::new_v4().to_string(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + spec: Some(SandboxSpec::default()), + ..Default::default() + }; + let request = || { + let principal = crate::grpc::test_support::authed_request(()) + .extensions() + .get::() + .unwrap() + .clone(); + Request::builder() + .uri("/openshell.v1.OpenShell/CreateSandbox") + .header("content-type", "application/grpc") + .header("openshell-replayed", "true") + .extension(principal) + .body(boxed_body_from_bytes(grpc_frame(&input.encode_to_vec()))) + .unwrap() + }; + let first = service + .ready() + .await + .unwrap() + .call(request()) + .await + .unwrap(); + assert!(!first.headers().contains_key("openshell-replayed")); + let first = first.into_body().collect().await.unwrap(); + assert_eq!(first.trailers().unwrap().get("grpc-status").unwrap(), "0"); + let first = decode_unary_grpc_message::(&first.to_bytes()).unwrap(); + assert_eq!( + first + .sandbox + .as_ref() + .unwrap() + .metadata + .as_ref() + .unwrap() + .name, + "intercepted-create" + ); + let replay = service + .ready() + .await + .unwrap() + .call(request()) + .await + .unwrap(); + assert_eq!(replay.headers().get("openshell-replayed").unwrap(), "true"); + let replay = replay.into_body().collect().await.unwrap(); + assert_eq!( + decode_unary_grpc_message::(&replay.to_bytes()).unwrap(), + first + ); + assert_eq!(interceptor.modifications.load(Ordering::SeqCst), 2); + assert_eq!(interceptor.validations.load(Ordering::SeqCst), 2); + assert_eq!(interceptor.observations.load(Ordering::SeqCst), 1); + interceptor.deny.store(true, Ordering::SeqCst); + let denied = service + .ready() + .await + .unwrap() + .call(request()) + .await + .unwrap(); + assert_eq!(denied.headers().get("grpc-status").unwrap(), "7"); + assert_eq!(interceptor.validations.load(Ordering::SeqCst), 3); + assert_eq!(interceptor.observations.load(Ordering::SeqCst), 1); + task.abort(); + } + #[test] fn grpc_trailer_status_takes_precedence_over_headers() { let response = Response::builder() diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index e15eed5c4d..32250b5c77 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -116,13 +116,13 @@ mod tests { use std::collections::{BTreeMap, BTreeSet, VecDeque}; const STORAGE_V1_SCHEMA_SHA256: &str = - "574bf5fcff731bd6e3fd84ed3f124161035bd236ef0fb7e32b4d8a8c55ceba5e"; + "d68401809d8cea445c35233ef32412bbd041cb2ac5acaf368a0d0bf74d2ddf17"; const PUBLIC_RPC_SCHEMA_SHA256: &str = - "d323fdd0c989049950ed3bf9cc2cbae9f05e1ae83b13fa2a65a2f5db1ebab95f"; + "418130a28d1a5398d3d7f73f11b7f025d027c70f215be320dfe8e58371769f83"; const DURABLE_SCHEMA_SHA256: &str = - "65066c0b0eef57a4c708f20fcbbb8e8f47376da9f4bf73dfc3bca0b3df174ba8"; + "557ca283c55fd46b213d5573b950ba8604cc3f4b31bad3e433eb9c5f9975138d"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "39e8aaf0d1fbc86906c49a9e7f60641a3ce203d3130799c8065e09acf9d53ddf"; + "f541c25bb3e1e5806865bc61470c66d10c16cca7399bf5909c77dc384d469171"; // A persisted Sandbox without endpoint status retains its lifecycle fields; // the absent repeated field decodes empty and needs no database rewrite. const SANDBOX_WITHOUT_ENDPOINT_STATUS: &str = "0a1e0a0a73616e64626f782d6964120773616e64626f783a0764656661756c741a2b0a0773616e64626f782a0d0a05526561647912045472756530023807420d73757065727669736f722d6964"; @@ -138,9 +138,10 @@ mod tests { "0a0472756c651a07666978747572652d0000403f3a0b6578616d706c652e636f6d40bb035002"; const V0_0_116_POLICY_RECORD: &str = "0a09706f6c6963792d6964120a73616e64626f782d6964180222030102032a0673686132353632066c6f616465643a046e6f6e6540fa0148ac0252110a06736f75726365120766697874757265"; const V0_0_116_DRAFT_RECORD: &str = "0a086368756e6b2d6964120a73616e64626f782d69641802220770656e64696e672a0472756c65320204053a076669787475726549000000000000e83f50de02589003620b6578616d706c652e636f6d68bb037801"; - const STORAGE_MESSAGE_NAMES: [&str; 8] = [ + const STORAGE_MESSAGE_NAMES: [&str; 9] = [ "DraftChunkPayload", "PolicyRevisionPayload", + "StoredConfigUpdateOperation", "StoredDraftChunk", "StoredPolicyRevision", "StoredProviderCredentialRefreshState", @@ -148,12 +149,21 @@ mod tests { "StoredProviderProfile", "StoredRefreshMaterialDeletion", ]; - const DURABLE_ROOTS: [&str; 12] = [ + const PROVIDER_READINESS_RPC_SIGNATURES: [&str; 2] = [ + "openshell.v1.OpenShell/GetSandboxProviderStatus|.openshell.v1.GetSandboxProviderStatusRequest|.openshell.v1.GetSandboxProviderStatusResponse|false|false", + "openshell.v1.OpenShell/ReportProviderReadiness|.openshell.v1.ReportProviderReadinessRequest|.openshell.v1.ReportProviderReadinessResponse|false|false", + ]; + // Synthetic SandboxSpec bytes with log level, provider, and command fields, + // emitted before the gateway-owned attachment epoch field was introduced. + const PRE_READINESS_SANDBOX_SPEC: &str = + "0a04696e666f421273796e7468657469632d70726f766964657262046563686f"; + const DURABLE_ROOTS: &[&str] = &[ ".openshell.datamodel.v1.Provider", ".openshell.datamodel.v1.Workspace", ".openshell.sandbox.v1.SandboxPolicy", ".openshell.storage.v1.DraftChunkPayload", ".openshell.storage.v1.PolicyRevisionPayload", + ".openshell.storage.v1.StoredConfigUpdateOperation", ".openshell.storage.v1.StoredProviderCredentialRefreshStateV2", ".openshell.storage.v1.StoredProviderProfile", ".openshell.v1.Sandbox", @@ -495,19 +505,34 @@ mod tests { } } methods.sort(); - assert_eq!(compiled_method_count, 101, "classify every compiled RPC"); - assert_eq!(methods.len(), 75, "inventory every public gateway RPC"); + for signature in PROVIDER_READINESS_RPC_SIGNATURES { + assert!( + methods.iter().any(|method| method == signature), + "provider readiness RPC is missing or changed: {signature}" + ); + } + assert_eq!( + compiled_method_count, + 101 + PROVIDER_READINESS_RPC_SIGNATURES.len(), + "classify every compiled RPC" + ); + assert_eq!( + methods.len(), + 75 + PROVIDER_READINESS_RPC_SIGNATURES.len(), + "inventory every public gateway RPC" + ); assert_eq!( methods .iter() .filter(|method| method.starts_with("openshell.v1.OpenShell/")) .count(), - 75 + 75 + PROVIDER_READINESS_RPC_SIGNATURES.len() ); assert!(methods.iter().all(|method| !method.contains(".storage."))); let public_closure = schema_closure(&index, public_roots); - let durable_closure = schema_closure(&index, DURABLE_ROOTS.into_iter().map(str::to_string)); + let durable_closure = + schema_closure(&index, DURABLE_ROOTS.iter().copied().map(str::to_string)); let overlap_messages = public_closure .messages .intersection(&durable_closure.messages) @@ -533,28 +558,39 @@ mod tests { let durable_inventory_hash = schema_fingerprint(&index, &durable_closure); let overlap_hash = format!("{:x}", Sha256::digest(overlap_inventory.as_bytes())); + // Report the complete measured inventory on failure so one schema + // change exposes every affected boundary in the same focused run. assert_eq!( - (public_closure.messages.len(), public_closure.enums.len()), - (283, 14) - ); - assert_eq!( - (durable_closure.messages.len(), durable_closure.enums.len()), - (83, 9) + ( + (public_closure.messages.len(), public_closure.enums.len()), + (durable_closure.messages.len(), durable_closure.enums.len()), + (overlap_messages.len(), overlap_enums.len()), + public_inventory_hash.as_str(), + durable_inventory_hash.as_str(), + overlap_hash.as_str(), + ), + ( + (294, 20), + (90, 15), + (78, 15), + PUBLIC_RPC_SCHEMA_SHA256, + DURABLE_SCHEMA_SHA256, + PUBLIC_DURABLE_OVERLAP_SHA256 + ), + "the public/durable schema inventory changed; review API and storage ownership, preserve prior-payload decoding, and update the reviewed fingerprints" ); - assert_eq!((overlap_messages.len(), overlap_enums.len()), (73, 9)); + } - assert_eq!( - public_inventory_hash, PUBLIC_RPC_SCHEMA_SHA256, - "the public RPC schema closure changed; review API compatibility and update the inventory and architecture/gateway.md" - ); - assert_eq!( - durable_inventory_hash, DURABLE_SCHEMA_SHA256, - "a durable protobuf root or transitive dependency changed; record migration handling and a prior-version fixture before updating this fingerprint" - ); - assert_eq!( - overlap_hash, PUBLIC_DURABLE_OVERLAP_SHA256, - "the public/durable protobuf overlap changed; review both API and storage compatibility before updating this inventory" - ); + #[test] + fn pre_readiness_sandbox_spec_decodes_with_initial_attachment_epoch() { + let spec = openshell_core::proto::SandboxSpec::decode( + legacy_bytes(PRE_READINESS_SANDBOX_SPEC).as_slice(), + ) + .expect("prior sandbox spec must decode"); + assert_eq!(spec.log_level, "info"); + assert_eq!(spec.providers, ["synthetic-provider"]); + assert_eq!(spec.command, ["echo"]); + assert!(spec.provider_attachment_epoch.is_empty()); } fn legacy_bytes(encoded: &str) -> Vec { diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index 12ebecaee8..1bf961e464 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -14,14 +14,16 @@ use tracing::{debug, info, warn}; use uuid::Uuid; use openshell_core::proto::{ - GatewayMessage, RelayFrame, RelayInit, RelayOpen, ReportMainProcessExitRequest, - ReportMainProcessExitResponse, Sandbox, SandboxPhase, SessionAccepted, SshRelayTarget, - SupervisorMessage, gateway_message, relay_open, supervisor_message, + GatewayMessage, ProviderReadinessObservation, RelayFrame, RelayInit, RelayOpen, + ReportMainProcessExitRequest, ReportMainProcessExitResponse, Sandbox, SandboxPhase, + SessionAccepted, SshRelayTarget, SupervisorMessage, gateway_message, relay_open, + supervisor_message, }; use openshell_core::transport_errors::is_expected_transport_close_status; use crate::ServerState; use crate::auth::principal::Principal; +use crate::grpc::provider_readiness::ProviderReadinessEvidence; use crate::persistence::ObjectId; const HEARTBEAT_INTERVAL_SECS: u32 = 15; @@ -71,6 +73,9 @@ struct LiveSession { /// gateway restart invalidates every session and startup reconciliation /// resets any persisted endpoint result before requests are served. endpoint_report_cursor: Option, + /// Installation evidence belongs to this connection and is never restored + /// from persistence or inherited by a replacement supervisor session. + provider_readiness: Option, #[allow(dead_code)] connected_at: Instant, } @@ -155,6 +160,7 @@ impl SupervisorSessionRegistry { terminal_delivery_finalized: false, endpoint_status_initialized: false, endpoint_report_cursor: None, + provider_readiness: None, connected_at: Instant::now(), }, ); @@ -267,6 +273,79 @@ impl SupervisorSessionRegistry { .is_some_and(|session| session.session_id == session_id) } + /// Bind the authenticated hello's installation capability to its session. + /// Initialization is single-use and cannot erase accepted observations. + pub(crate) fn initialize_provider_readiness( + &self, + sandbox_id: &str, + session_id: &str, + evidence: ProviderReadinessEvidence, + ) -> Result<(), Status> { + let mut sessions = self + .sessions + .lock() + .map_err(|_| Status::unavailable("supervisor session state is unavailable"))?; + let session = sessions + .get_mut(sandbox_id) + .filter(|session| session.session_id == session_id) + .ok_or_else(|| Status::failed_precondition("supervisor session was replaced"))?; + if session.provider_readiness.is_some() { + return Err(Status::failed_precondition( + "provider readiness is already initialized", + )); + } + session.provider_readiness = Some(evidence); + Ok(()) + } + + /// Accept installation evidence only while its session owns this sandbox. + /// Session comparison and publication share one lock so reconnects cannot + /// transfer a predecessor's evidence into the replacement session. + pub(crate) fn accept_provider_readiness( + &self, + sandbox_id: &str, + active_instance_id: &str, + observation: ProviderReadinessObservation, + ) -> Result<(), Status> { + let mut sessions = self + .sessions + .lock() + .map_err(|_| Status::unavailable("supervisor session state is unavailable"))?; + let evidence = sessions + .get_mut(sandbox_id) + .filter(|session| { + session.session_id == observation.session_id && session.endpoint_status_initialized + }) + .and_then(|session| session.provider_readiness.as_mut()) + .ok_or_else(|| { + Status::permission_denied( + "provider readiness requires the active supervisor session", + ) + })?; + if !evidence.belongs_to_instance(active_instance_id) { + return Err(Status::failed_precondition( + "provider readiness requires the current sandbox instance", + )); + } + evidence.accept(observation) + } + + /// Snapshot installation evidence from the current initialized session. + /// Disconnect and replacement discard the previous connection's state. + pub(crate) fn provider_readiness( + &self, + sandbox_id: &str, + ) -> Result, Status> { + let sessions = self + .sessions + .lock() + .map_err(|_| Status::unavailable("supervisor session state is unavailable"))?; + Ok(sessions + .get(sandbox_id) + .filter(|session| session.endpoint_status_initialized) + .and_then(|session| session.provider_readiness.clone())) + } + /// Mark the current session as the observation authority after its /// public endpoint results have been durably reset. pub(crate) fn initialize_endpoint_status_authority( @@ -870,6 +949,9 @@ pub async fn handle_connect_supervisor( crate::auth::guard::ensure_sandbox_principal_scope(principal, &sandbox_id)?; } require_persisted_sandbox(&state.store, &sandbox_id).await?; + // Validate readiness identities before replacing a healthy session. Older + // supervisors remain usable but cannot assert provider installation. + let provider_readiness = ProviderReadinessEvidence::from_hello(&hello)?; let session_id = Uuid::new_v4().to_string(); info!( @@ -919,6 +1001,16 @@ pub async fn handle_connect_supervisor( "supervisor session was replaced during endpoint status initialization", )); } + if let Err(error) = state.supervisor_sessions.initialize_provider_readiness( + &sandbox_id, + &session_id, + provider_readiness, + ) { + state + .supervisor_sessions + .remove_if_current(&sandbox_id, &session_id); + return Err(error); + } // Step 3: Send SessionAccepted. let accepted = GatewayMessage { diff --git a/crates/openshell-server/tests/common/mod.rs b/crates/openshell-server/tests/common/mod.rs index b005b53300..5391a3ab4e 100644 --- a/crates/openshell-server/tests/common/mod.rs +++ b/crates/openshell-server/tests/common/mod.rs @@ -221,6 +221,22 @@ impl OpenShell for TestOpenShell { Ok(Response::new(GetGatewayConfigResponse::default())) } + async fn get_sandbox_provider_status( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider readiness is not exercised by this mock", + )) + } + + async fn report_provider_readiness( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("provider readiness")) + } + async fn get_sandbox_provider_environment( &self, _request: tonic::Request, diff --git a/crates/openshell-server/tests/supervisor_relay_integration.rs b/crates/openshell-server/tests/supervisor_relay_integration.rs index 448f3e4765..f3ae883f78 100644 --- a/crates/openshell-server/tests/supervisor_relay_integration.rs +++ b/crates/openshell-server/tests/supervisor_relay_integration.rs @@ -248,6 +248,22 @@ impl OpenShell for RelayGateway { ) -> Result, Status> { Err(Status::unimplemented("unused")) } + async fn get_sandbox_provider_status( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented( + "provider readiness is not exercised by this mock", + )) + } + + async fn report_provider_readiness( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("provider readiness")) + } + async fn get_sandbox_provider_environment( &self, _: tonic::Request, diff --git a/crates/openshell-supervisor-middleware/src/headers.rs b/crates/openshell-supervisor-middleware/src/headers.rs index 1dc37bff20..056ad32cf7 100644 --- a/crates/openshell-supervisor-middleware/src/headers.rs +++ b/crates/openshell-supervisor-middleware/src/headers.rs @@ -305,28 +305,39 @@ fn is_request_protected(name: &str) -> bool { || name.starts_with("x-openshell-credential") } -fn is_response_protected(name: &str) -> bool { +/// Return whether a response header can carry authentication material and must +/// never be exposed to middleware. +#[must_use] +pub fn is_response_credential_header(name: &str) -> bool { + let name = name.to_ascii_lowercase(); matches!( - name, + name.as_str(), "authentication-info" - | "connection" - | "content-encoding" - | "content-length" - | "content-range" - | "keep-alive" | "proxy-authenticate" | "proxy-authentication-info" | "proxy-authorization" - | "proxy-connection" | "set-cookie" - | "te" - | "trailer" - | "transfer-encoding" - | "upgrade" | "www-authenticate" ) || name.starts_with("x-openshell-credential") } +fn is_response_protected(name: &str) -> bool { + is_response_credential_header(name) + || matches!( + name, + "connection" + | "content-encoding" + | "content-length" + | "content-range" + | "keep-alive" + | "proxy-connection" + | "te" + | "trailer" + | "transfer-encoding" + | "upgrade" + ) +} + fn is_response_remove_only(name: &str) -> bool { matches!( name, @@ -642,6 +653,25 @@ mod tests { } } + #[test] + fn response_authority_keeps_visible_body_metadata_read_only() { + let existing = [ + header("content-length", "5"), + header("content-encoding", "gzip"), + header("content-range", "bytes 0-4/10"), + ]; + for name in ["Content-Length", "Content-Encoding", "Content-Range"] { + for mutation in [ + write(name, "replacement", ExistingHeaderAction::Overwrite), + remove(name), + ] { + let error = apply(HeaderAuthority::Response, &existing, &[], &[mutation]) + .expect_err("read-only response body metadata"); + assert!(matches!(error, HeaderMutationError::Protected { .. })); + } + } + } + #[test] fn response_authority_protects_credential_headers_from_writes_and_removals() { let existing = [header("set-cookie", "session=upstream")]; diff --git a/crates/openshell-supervisor-middleware/src/lib.rs b/crates/openshell-supervisor-middleware/src/lib.rs index e69b808ee6..d9926678c4 100644 --- a/crates/openshell-supervisor-middleware/src/lib.rs +++ b/crates/openshell-supervisor-middleware/src/lib.rs @@ -5,8 +5,16 @@ pub mod headers; mod remote; +mod response; mod websocket; +pub use response::{ + HttpResponseDiagnostics, HttpResponseFinish, HttpResponseInvocation, + HttpResponseInvocationOutcome, HttpResponseMiddlewareFailure, HttpResponsePreflightInput, + HttpResponsePreflightOutcome, HttpResponseSession, MAX_HTTP_RESPONSE_RETAINED_BODY_BYTES, + MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES, is_stale_http_response_integrity_header, +}; + pub use websocket::{ WebSocketCoverage, WebSocketCoverageState, WebSocketInvocation, WebSocketInvocationOutcome, WebSocketMessageAdmission, WebSocketMessageOutcome, WebSocketMessageType, @@ -626,6 +634,16 @@ impl MiddlewareDispatch { Self::Grpc(service) => service.open_websocket_session(receiver).await, } } + + async fn open_http_response_pre_return( + &self, + receiver: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + match self { + Self::InProcess(service) => service.open_http_response_pre_return(receiver).await, + Self::Grpc(service) => service.open_http_response_pre_return(receiver).await, + } + } } struct MiddlewareServiceState { @@ -836,6 +854,7 @@ fn validate_payload_limit(source: &str, binding: &MiddlewareBinding) -> Result Result Err(miette!( - "{source} advertises HTTP_RESPONSE/PRE_RETURN, which is not yet supported" - )), + ) => Ok(SupportedBinding::HttpResponsePreReturn), ( Some(SupervisorMiddlewareOperation::WebsocketMessage), Some(SupervisorMiddlewarePhase::PreCredentials), @@ -3721,7 +3738,7 @@ mod tests { } #[test] - fn manifest_rejects_http_response_pre_return_binding_until_dispatch_is_available() { + fn manifest_accepts_http_response_pre_return_binding_when_dispatch_is_available() { let registration = external_registration(4096); let manifest = MiddlewareManifest { name: "example/response".into(), @@ -3738,13 +3755,8 @@ mod tests { expected_audience: String::new(), }; - let error = validate_external_manifest(®istration, &manifest, 4096, false) - .expect_err("HTTP response pre-return binding must remain unavailable"); - assert!( - error - .to_string() - .contains("HTTP_RESPONSE/PRE_RETURN, which is not yet supported") - ); + validate_external_manifest(®istration, &manifest, 4096, false) + .expect("HTTP response pre-return binding is supported"); } #[test] diff --git a/crates/openshell-supervisor-middleware/src/remote.rs b/crates/openshell-supervisor-middleware/src/remote.rs index 9443038100..80049b69dc 100644 --- a/crates/openshell-supervisor-middleware/src/remote.rs +++ b/crates/openshell-supervisor-middleware/src/remote.rs @@ -103,6 +103,14 @@ impl GrpcMiddlewareService { ) -> std::result::Result { self.service.open_websocket_session(receiver).await } + + /// Open a remote HTTP response pre-return stream through the gRPC adapter. + pub async fn open_http_response_pre_return( + &self, + receiver: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + self.service.open_http_response_pre_return(receiver).await + } } #[derive(Clone)] diff --git a/crates/openshell-supervisor-middleware/src/response.rs b/crates/openshell-supervisor-middleware/src/response.rs new file mode 100644 index 0000000000..073bebd88d --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/response.rs @@ -0,0 +1,2617 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! HTTP response pre-return middleware chain execution. + +mod preflight; +mod validation; + +#[cfg(test)] +use validation::permitted_body_modes; +use validation::{ + BodyAction, CurrentBodyAction, encoded_header_bytes, strip_stale_integrity, + validate_body_result, validate_trailers_result, +}; + +use std::collections::BTreeMap; +use std::time::Duration; + +use futures::StreamExt as _; +use prost::Message as _; +use tokio::sync::mpsc; +use tokio::time::Instant; + +use openshell_core::proto::{ + Finding, HttpHeader, HttpRequestTarget, HttpResponseBodyMode, HttpResponseBodyPassThrough, + HttpResponseBodyUnit, HttpResponseEvent, HttpResponseEventResult, HttpResponsePreflight, + HttpResponseTrailers, MiddlewareSessionEnd, MiddlewareSessionEndReason, RequestContext, + http_response_body_result, http_response_body_skip_remaining, http_response_body_transform, + http_response_body_unit, http_response_event, http_response_event_result, + http_response_preflight_result, +}; + +use super::{ + ChainEntry, ChainRunner, DescribedChainEntry, MAX_MIDDLEWARE_CHAIN_TIMEOUT, + MAX_MIDDLEWARE_CONTEXT_BYTES, MAX_MIDDLEWARE_FINDING_BYTES, MAX_MIDDLEWARE_FINDINGS_PER_STAGE, + MAX_MIDDLEWARE_HEADER_BYTES, MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES, MAX_MIDDLEWARE_HEADERS, + MAX_MIDDLEWARE_METADATA_BYTES, MAX_MIDDLEWARE_METADATA_ENTRIES, MAX_MIDDLEWARE_REASON_BYTES, + MAX_MIDDLEWARE_REASON_CODE_BYTES, MAX_MIDDLEWARE_TARGET_BYTES, MiddlewareDiagnosticPolicy, + MiddlewareSessionAdmission, MiddlewareSessionPermit, NamespacedFinding, OnError, headers, + is_stable_reason_code, middleware_denial_reason, +}; + +const STREAM_CHANNEL_CAPACITY: usize = 4; +const SESSION_END_TIMEOUT: Duration = Duration::from_millis(10); +pub const MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES: usize = 64 * 1024; +/// Maximum logical body bytes retained across a session's stage buffers and +/// pending output. Temporary exchange copies have the per-binding payload cap. +pub const MAX_HTTP_RESPONSE_RETAINED_BODY_BYTES: usize = 8 * 1024 * 1024; + +/// Return whether a response metadata field becomes stale after body changes. +#[must_use] +pub fn is_stale_http_response_integrity_header(name: &str) -> bool { + matches!( + name.to_ascii_lowercase().as_str(), + "accept-ranges" + | "etag" + | "content-md5" + | "digest" + | "content-digest" + | "repr-digest" + | "signature" + | "signature-input" + ) +} + +#[derive(Debug, Clone)] +pub struct HttpResponsePreflightInput { + pub context: RequestContext, + pub target: HttpRequestTarget, + pub status_code: u16, + /// Parsed upstream Content-Length when present and valid. + pub declared_body_length: Option, + /// Sanitized, lowercased final response headers in wire order. + pub headers: Vec, + /// Lowercased names nominated by the original response's `Connection` + /// fields. Their values are not exposed to middleware. + pub connection_nominated_headers: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HttpResponseInvocationOutcome { + Skip, + BlockDelivery, + HeadersOnly, + WholeBody, + Stream, + Trailers, + PassThrough, + Transform, + SkipRemaining, + FailOpen, + FailClosed, +} + +#[derive(Debug, Clone)] +pub struct HttpResponseInvocation { + pub config_name: String, + pub implementation: String, + pub outcome: HttpResponseInvocationOutcome, + pub sequence: Option, + pub input_size: usize, + pub output_size: Option, + pub failed: bool, + pub stage_disabled: bool, + pub reason_code: Option, + pub failure_category: Option, +} + +pub struct HttpResponsePreflightOutcome { + pub allowed: bool, + pub reason: String, + pub denial: Option, + pub headers: Vec, + pub session: Option, + pub findings: Vec, + pub metadata: BTreeMap>, + pub invocations: Vec, + pub session_capacity_exhausted: bool, +} + +#[derive(Debug)] +pub struct HttpResponseMiddlewareFailure { + pub reason: String, + pub denial: Option, + /// Exchange diagnostics collected before a consuming operation failed. + pub diagnostics: HttpResponseDiagnostics, +} + +impl std::fmt::Display for HttpResponseMiddlewareFailure { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.reason) + } +} + +impl std::error::Error for HttpResponseMiddlewareFailure {} + +impl HttpResponseMiddlewareFailure { + fn with_diagnostics(mut self, diagnostics: HttpResponseDiagnostics) -> Self { + self.diagnostics = diagnostics; + self + } +} + +#[derive(Debug)] +pub struct HttpResponseFinish { + /// Units released while whole-body stages were finalized. + pub body_units: Vec>, + pub trailers: Vec, + /// True when a whole-body stage transformed or deleted body bytes. The + /// caller must strip stale representation validators before commitment. + pub strip_stale_integrity_headers: bool, + pub findings: Vec, + pub metadata: BTreeMap>, + pub invocations: Vec, +} + +#[derive(Debug, Default)] +pub struct HttpResponseDiagnostics { + pub findings: Vec, + pub metadata: BTreeMap>, + pub invocations: Vec, +} + +struct HttpResponseStageTransport { + sender: mpsc::Sender, + responses: super::HttpResponseResultStream, +} + +impl HttpResponseStageTransport { + async fn end(self, reason: MiddlewareSessionEndReason) { + let _ = tokio::time::timeout(SESSION_END_TIMEOUT, self.end_inner(reason)).await; + } + + async fn end_inner(self, reason: MiddlewareSessionEndReason) { + if self.sender.send(session_end_event(reason)).await.is_err() { + return; + } + self.drain().await; + } + + async fn drain(self) { + let Self { + sender, + mut responses, + } = self; + // Keep the response stream alive while half-closing the request side. + // Dropping both handles together schedules an HTTP/2 CANCEL and can + // discard the terminal event before remote middleware receives it. + drop(sender); + while responses.next().await.is_some() {} + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum StageMode { + HeadersOnly, + WholeBody, + Stream, +} + +struct HttpResponseStage { + entry: DescribedChainEntry, + transport: Option, + mode: StageMode, + next_sequence: u64, + whole_body: Vec, +} + +impl HttpResponseStage { + fn is_active(&self) -> bool { + self.transport.is_some() + } + + fn is_body_active(&self) -> bool { + self.is_active() && self.mode != StageMode::HeadersOnly + } + + async fn end(&mut self, reason: MiddlewareSessionEndReason) { + if let Some(transport) = self.transport.take() { + transport.end(reason).await; + } + } +} + +pub struct HttpResponseSession { + runner: ChainRunner, + stages: Vec, + findings: Vec, + metadata: BTreeMap>, + invocations: Vec, + session_admission: Option, + body_transformed: bool, + retained_body_bytes: usize, + defer_output_until_finish: bool, + deferred_output: Vec>, + connection_nominated_headers: Vec, + whole_body_deadline: Option, +} + +impl HttpResponseSession { + pub fn take_diagnostics(&mut self) -> HttpResponseDiagnostics { + HttpResponseDiagnostics { + findings: std::mem::take(&mut self.findings), + metadata: std::mem::take(&mut self.metadata), + invocations: std::mem::take(&mut self.invocations), + } + } + + #[must_use] + pub fn requires_whole_body(&self) -> bool { + self.stages.iter().any(|stage| { + stage.is_active() && stage.mode == StageMode::WholeBody && stage.next_sequence == 1 + }) + } + + /// Start the platform-owned whole-body wall-clock deadline. + pub fn start_whole_body_deadline(&mut self, timeout: Duration) { + self.whole_body_deadline = self.requires_whole_body().then(|| Instant::now() + timeout); + } + + #[must_use] + pub fn whole_body_deadline(&self) -> Option { + self.requires_whole_body() + .then_some(self.whole_body_deadline) + .flatten() + } + + /// Fail each still-buffering whole-body stage in policy order. + /// + /// Fail-open stages release their retained input through the remaining + /// chain. A fail-closed stage stops the response with a typed failure. + pub async fn expire_whole_body_deadline( + &mut self, + ) -> Result>, HttpResponseMiddlewareFailure> { + self.whole_body_deadline = None; + let mut released = std::mem::take(&mut self.deferred_output); + let chain_deadline = Instant::now() + MAX_MIDDLEWARE_CHAIN_TIMEOUT; + for index in 0..self.stages.len() { + if !self.stages[index].is_active() + || self.stages[index].mode != StageMode::WholeBody + || self.stages[index].next_sequence != 1 + { + continue; + } + let original = std::mem::take(&mut self.stages[index].whole_body); + let output = self + .handle_stage_failure(index, "whole_body_accumulation_timeout", None, original) + .await?; + if !output.is_empty() { + released.extend( + self.process_units_from(index + 1, output, chain_deadline) + .await?, + ); + } + } + self.defer_output_until_finish = false; + self.release_body_bytes(&released); + Ok(released) + } + + #[must_use] + pub fn stream_unit_limit(&self) -> usize { + self.stages + .iter() + .filter(|stage| stage.is_active() && stage.mode == StageMode::Stream) + .map(|stage| { + stage + .entry + .max_payload_bytes + .clamp(1, MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES) + }) + .min() + .unwrap_or(MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES) + } + + /// Process one normalized body unit through the active chain. + /// + /// The caller must provide no more than [`Self::stream_unit_limit`] bytes. + /// A whole-body barrier retains output until [`Self::finish`] is called. + pub async fn push_body( + &mut self, + data: Vec, + ) -> Result>, HttpResponseMiddlewareFailure> { + if data.len() > self.stream_unit_limit() { + return Err(HttpResponseMiddlewareFailure { + reason: "response_stream_unit_over_capacity".into(), + denial: None, + diagnostics: HttpResponseDiagnostics::default(), + }); + } + let _work = self + .runner + .reserve_middleware_work_admission() + .await + .map_err(|error| HttpResponseMiddlewareFailure { + reason: format!("middleware_failed: {error}"), + denial: None, + diagnostics: HttpResponseDiagnostics::default(), + })?; + let deadline = Instant::now() + MAX_MIDDLEWARE_CHAIN_TIMEOUT; + // Between pushes, the first active whole-body barrier owns all input + // not returned to the relay (at most the 4 MiB binding cap). Later + // barriers cannot receive bytes until it finishes or disables itself; + // finish consumes the session and expiry disables all such barriers. + // Replacement admission reserves an additional upstream unit below. + self.retained_body_bytes += data.len(); + debug_assert!(self.retained_body_bytes <= MAX_HTTP_RESPONSE_RETAINED_BODY_BYTES); + let output = self.process_units_from(0, vec![data], deadline).await?; + if !self.defer_output_until_finish { + self.release_body_bytes(&output); + return Ok(output); + } + if self.requires_whole_body() { + self.deferred_output.extend(output); + return Ok(Vec::new()); + } + + self.defer_output_until_finish = false; + let mut released = std::mem::take(&mut self.deferred_output); + released.extend(output); + self.release_body_bytes(&released); + Ok(released) + } + + /// Finalize every body stage, preserve normalized trailers, and end streams. + pub async fn finish( + mut self, + mut trailers: Vec, + ) -> Result { + let _work = match self.runner.reserve_middleware_work_admission().await { + Ok(work) => work, + Err(error) => { + return Err(HttpResponseMiddlewareFailure { + reason: format!("middleware_failed: {error}"), + denial: None, + diagnostics: self.take_diagnostics(), + }); + } + }; + let deadline = Instant::now() + MAX_MIDDLEWARE_CHAIN_TIMEOUT; + let mut released = std::mem::take(&mut self.deferred_output); + for index in 0..self.stages.len() { + let stage_output = match self.finish_stage(index, deadline).await { + Ok(output) => output, + Err(failure) => { + self.end_all(MiddlewareSessionEndReason::MiddlewareFailure) + .await; + return Err(failure.with_diagnostics(self.take_diagnostics())); + } + }; + if !stage_output.is_empty() { + let output = match self + .process_units_from(index + 1, stage_output, deadline) + .await + { + Ok(output) => output, + Err(failure) => { + self.end_all(MiddlewareSessionEndReason::MiddlewareFailure) + .await; + return Err(failure.with_diagnostics(self.take_diagnostics())); + } + }; + released.extend(output); + } + } + + if self.body_transformed { + strip_stale_integrity(&mut trailers); + } + let trailers = match self.process_trailers(trailers, deadline).await { + Ok(trailers) => trailers, + Err(failure) => { + self.end_all(MiddlewareSessionEndReason::MiddlewareFailure) + .await; + return Err(failure.with_diagnostics(self.take_diagnostics())); + } + }; + self.end_all(MiddlewareSessionEndReason::Normal).await; + self.session_admission.take(); + Ok(HttpResponseFinish { + body_units: released, + trailers, + strip_stale_integrity_headers: self.body_transformed, + findings: self.findings, + metadata: self.metadata, + invocations: self.invocations, + }) + } + + pub async fn end(mut self, reason: MiddlewareSessionEndReason) { + self.end_all(reason).await; + } + + fn release_body_bytes(&mut self, units: &[Vec]) { + self.retained_body_bytes -= units.iter().map(Vec::len).sum::(); + } + + async fn process_units_from( + &mut self, + start: usize, + mut units: Vec>, + deadline: Instant, + ) -> Result>, HttpResponseMiddlewareFailure> { + for index in start..self.stages.len() { + let mut next = Vec::new(); + for unit in units { + let chunk_limit = if self.stages[index].mode == StageMode::Stream { + self.stages[index] + .entry + .max_payload_bytes + .min(MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES) + } else { + unit.len().max(1) + }; + if unit.is_empty() { + next.extend(self.process_stage_unit(index, unit, deadline).await?); + } else { + for chunk in unit.chunks(chunk_limit) { + next.extend( + self.process_stage_unit(index, chunk.to_vec(), deadline) + .await?, + ); + } + } + } + units = next; + if units.is_empty() + && self.stages[index + 1..] + .iter() + .all(|stage| stage.mode != StageMode::WholeBody) + { + break; + } + } + Ok(units) + } + + async fn process_stage_unit( + &mut self, + index: usize, + data: Vec, + deadline: Instant, + ) -> Result>, HttpResponseMiddlewareFailure> { + let deadline = self.exchange_deadline(deadline); + let stage = &mut self.stages[index]; + if !stage.is_active() || stage.mode == StageMode::HeadersOnly { + return Ok(vec![data]); + } + if stage.mode == StageMode::WholeBody { + if stage.whole_body.len().saturating_add(data.len()) > stage.entry.max_payload_bytes { + let mut original = std::mem::take(&mut stage.whole_body); + original.extend_from_slice(&data); + return self + .handle_stage_failure(index, "whole_body_over_capacity", None, original) + .await; + } + stage.whole_body.extend_from_slice(&data); + return Ok(Vec::new()); + } + + let sequence = stage.next_sequence; + stage.next_sequence += 1; + let event = body_event(sequence, data.clone(), false); + let result = match exchange(stage, event, deadline).await { + Ok(result) => result, + Err(reason) => { + let reason = self.classify_timeout_reason(reason); + return self + .handle_stage_failure(index, &reason, Some(sequence), data) + .await; + } + }; + self.apply_body_result(index, result, sequence, data).await + } + + async fn finish_stage( + &mut self, + index: usize, + deadline: Instant, + ) -> Result>, HttpResponseMiddlewareFailure> { + if !self.stages[index].is_body_active() { + return Ok(Vec::new()); + } + let deadline = self.exchange_deadline(deadline); + let mode = self.stages[index].mode; + let mut output = Vec::new(); + if mode == StageMode::WholeBody { + let data = std::mem::take(&mut self.stages[index].whole_body); + let sequence = 1; + self.stages[index].next_sequence = 2; + let result = match exchange( + &mut self.stages[index], + body_event(sequence, data.clone(), true), + deadline, + ) + .await + { + Ok(result) => result, + Err(reason) => { + let reason = self.classify_timeout_reason(reason); + return self + .handle_stage_failure(index, &reason, Some(sequence), data) + .await; + } + }; + output.extend( + self.apply_body_result(index, result, sequence, data) + .await?, + ); + } + + if mode == StageMode::Stream { + let sequence = self.stages[index].next_sequence; + self.stages[index].next_sequence += 1; + let result = match exchange( + &mut self.stages[index], + body_event(sequence, Vec::new(), true), + deadline, + ) + .await + { + Ok(result) => result, + Err(reason) => { + let reason = self.classify_timeout_reason(reason); + return self + .handle_stage_failure(index, &reason, Some(sequence), Vec::new()) + .await; + } + }; + output.extend( + self.apply_body_result(index, result, sequence, Vec::new()) + .await?, + ); + } + Ok(output) + } + + async fn apply_body_result( + &mut self, + index: usize, + result: HttpResponseEventResult, + sequence: u64, + original: Vec, + ) -> Result>, HttpResponseMiddlewareFailure> { + let max_payload_bytes = self.stages[index].entry.max_payload_bytes; + let decision = match validate_body_result(result, sequence, max_payload_bytes) { + Ok(decision) => decision, + Err(reason) => { + return self + .handle_stage_failure(index, reason, Some(sequence), original) + .await; + } + }; + let input_size = original.len(); + let replacement_size = match &decision.action { + BodyAction::Transform(replacement) + | BodyAction::SkipRemaining(CurrentBodyAction::Transform(replacement)) => { + Some(replacement.len()) + } + _ => None, + }; + if let Some(replacement_size) = replacement_size { + let retained = self.retained_body_bytes - input_size + replacement_size; + // Reserve room for one more normalized upstream unit. Whole-body + // barriers bound the input retained between calls to push_body. + if retained + > MAX_HTTP_RESPONSE_RETAINED_BODY_BYTES - MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES + { + return self + .handle_stage_failure( + index, + "response_body_aggregate_over_capacity", + Some(sequence), + original, + ) + .await; + } + self.retained_body_bytes = retained; + } + let stage = &mut self.stages[index]; + collect_diagnostics( + stage, + decision.findings, + decision.metadata, + &mut self.findings, + &mut self.metadata, + ); + let reason_code = (!decision.reason_code.is_empty()).then_some(decision.reason_code); + match decision.action { + BodyAction::PassThrough => { + let output_size = original.len(); + self.invocations.push(body_invocation_with_reason( + stage, + HttpResponseInvocationOutcome::PassThrough, + sequence, + input_size, + output_size, + reason_code, + )); + Ok((!original.is_empty()) + .then_some(original) + .into_iter() + .collect()) + } + BodyAction::Transform(replacement) => { + self.body_transformed = true; + self.invocations.push(body_invocation_with_reason( + stage, + HttpResponseInvocationOutcome::Transform, + sequence, + input_size, + replacement.len(), + reason_code, + )); + Ok((!replacement.is_empty()) + .then_some(replacement) + .into_iter() + .collect()) + } + BodyAction::SkipRemaining(action) => { + let output = match action { + CurrentBodyAction::PassThrough => original, + CurrentBodyAction::Transform(replacement) => { + self.body_transformed = true; + replacement + } + }; + stage.mode = StageMode::HeadersOnly; + self.invocations.push(body_invocation_with_reason( + stage, + HttpResponseInvocationOutcome::SkipRemaining, + sequence, + input_size, + output.len(), + reason_code, + )); + stage.end(MiddlewareSessionEndReason::Normal).await; + self.release_admission_if_idle(); + Ok((!output.is_empty()).then_some(output).into_iter().collect()) + } + BodyAction::BlockDelivery => { + let config_name = stage.entry.entry.name.clone(); + let denial_reason = middleware_denial_reason(&config_name, reason_code.as_deref()); + self.invocations.push(body_invocation_with_reason( + stage, + HttpResponseInvocationOutcome::BlockDelivery, + sequence, + input_size, + 0, + reason_code.clone(), + )); + self.end_all(MiddlewareSessionEndReason::MiddlewareDenial) + .await; + Err(HttpResponseMiddlewareFailure { + reason: denial_reason, + denial: Some(super::MiddlewareDenial { + config_name, + reason_code, + }), + diagnostics: HttpResponseDiagnostics::default(), + }) + } + } + } + + async fn handle_stage_failure( + &mut self, + index: usize, + reason: &str, + sequence: Option, + original: Vec, + ) -> Result>, HttpResponseMiddlewareFailure> { + let stage = &mut self.stages[index]; + let fail_open = stage.entry.on_error() == OnError::FailOpen; + let outcome = if fail_open { + HttpResponseInvocationOutcome::FailOpen + } else { + HttpResponseInvocationOutcome::FailClosed + }; + self.invocations.push(HttpResponseInvocation { + config_name: stage.entry.entry.name.clone(), + implementation: stage.entry.entry.implementation.clone(), + outcome, + sequence, + input_size: original.len(), + output_size: None, + failed: true, + stage_disabled: true, + reason_code: None, + failure_category: Some(response_failure_category(reason).into()), + }); + stage + .end(MiddlewareSessionEndReason::MiddlewareFailure) + .await; + self.release_admission_if_idle(); + if fail_open { + if original.is_empty() { + Ok(Vec::new()) + } else { + Ok(vec![original]) + } + } else { + Err(HttpResponseMiddlewareFailure { + reason: format!("middleware_failed: {reason}"), + denial: None, + diagnostics: HttpResponseDiagnostics::default(), + }) + } + } + + async fn end_all(&mut self, reason: MiddlewareSessionEndReason) { + for stage in &mut self.stages { + stage.end(reason).await; + } + } + + fn release_admission_if_idle(&mut self) { + if self.stages.iter().all(|stage| !stage.is_active()) { + self.session_admission.take(); + } + } + + fn exchange_deadline(&self, chain_deadline: Instant) -> Instant { + self.whole_body_deadline() + .map_or(chain_deadline, |deadline| deadline.min(chain_deadline)) + } + + fn classify_timeout_reason(&self, reason: String) -> String { + if reason == "middleware_timeout" + && self + .whole_body_deadline + .is_some_and(|deadline| Instant::now() >= deadline) + { + "whole_body_accumulation_timeout".into() + } else { + reason + } + } + + async fn process_trailers( + &mut self, + mut trailers: Vec, + deadline: Instant, + ) -> Result, HttpResponseMiddlewareFailure> { + for index in 0..self.stages.len() { + if !self.stages[index].is_body_active() { + continue; + } + let event = HttpResponseEvent { + event: Some(http_response_event::Event::Trailers(HttpResponseTrailers { + headers: trailers.clone(), + })), + }; + let result = match exchange(&mut self.stages[index], event, deadline).await { + Ok(result) => result, + Err(reason) => { + trailers = self + .handle_trailer_failure(index, &reason, trailers) + .await?; + continue; + } + }; + let decision = match validate_trailers_result( + result, + &trailers, + &self.stages[index].entry, + &self.connection_nominated_headers, + ) { + Ok(decision) => decision, + Err(reason) => { + trailers = self + .handle_trailer_failure(index, &reason, trailers) + .await?; + continue; + } + }; + let input_size = encoded_header_bytes(&trailers); + trailers = decision.headers; + let output_size = encoded_header_bytes(&trailers); + let reason_code = (!decision.reason_code.is_empty()).then_some(decision.reason_code); + let stage = &mut self.stages[index]; + collect_diagnostics( + stage, + decision.findings, + decision.metadata, + &mut self.findings, + &mut self.metadata, + ); + self.invocations.push(HttpResponseInvocation { + config_name: stage.entry.entry.name.clone(), + implementation: stage.entry.entry.implementation.clone(), + outcome: HttpResponseInvocationOutcome::Trailers, + sequence: None, + input_size, + output_size: Some(output_size), + failed: false, + stage_disabled: false, + reason_code, + failure_category: None, + }); + } + Ok(trailers) + } + + async fn handle_trailer_failure( + &mut self, + index: usize, + reason: &str, + original: Vec, + ) -> Result, HttpResponseMiddlewareFailure> { + let stage = &mut self.stages[index]; + let fail_open = stage.entry.on_error() == OnError::FailOpen; + self.invocations.push(HttpResponseInvocation { + config_name: stage.entry.entry.name.clone(), + implementation: stage.entry.entry.implementation.clone(), + outcome: if fail_open { + HttpResponseInvocationOutcome::FailOpen + } else { + HttpResponseInvocationOutcome::FailClosed + }, + sequence: None, + input_size: encoded_header_bytes(&original), + output_size: None, + failed: true, + stage_disabled: true, + reason_code: None, + failure_category: Some(response_failure_category(reason).into()), + }); + stage + .end(MiddlewareSessionEndReason::MiddlewareFailure) + .await; + self.release_admission_if_idle(); + if fail_open { + Ok(original) + } else { + Err(HttpResponseMiddlewareFailure { + reason: format!("middleware_failed: {reason}"), + denial: None, + diagnostics: HttpResponseDiagnostics::default(), + }) + } + } +} + +async fn exchange( + stage: &mut HttpResponseStage, + event: HttpResponseEvent, + chain_deadline: Instant, +) -> Result { + let remaining = chain_deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err("middleware_chain_timeout".into()); + } + let timeout = stage.entry.timeout.min(remaining); + let Some(transport) = stage.transport.as_mut() else { + return Err("middleware_stream_closed".into()); + }; + match tokio::time::timeout(timeout, async { + transport + .sender + .send(event) + .await + .map_err(|_| tonic::Status::unavailable("middleware request stream closed"))?; + transport + .responses + .next() + .await + .ok_or_else(|| tonic::Status::unavailable("middleware result stream closed"))? + }) + .await + { + Ok(Ok(result)) => Ok(result), + Ok(Err(error)) => { + let policy = stage + .entry + .service + .as_ref() + .map_or(MiddlewareDiagnosticPolicy::Preserve, |service| { + service.diagnostic_policy + }); + Err(policy.error_reason(&error)) + } + Err(_) => Err("middleware_timeout".into()), + } +} + +fn body_event(sequence: u64, data: Vec, end_of_stream: bool) -> HttpResponseEvent { + HttpResponseEvent { + event: Some(http_response_event::Event::Body(HttpResponseBodyUnit { + sequence, + payload: Some(http_response_body_unit::Payload::Data(data)), + end_of_stream, + })), + } +} + +fn session_end_event(reason: MiddlewareSessionEndReason) -> HttpResponseEvent { + HttpResponseEvent { + event: Some(http_response_event::Event::SessionEnd( + MiddlewareSessionEnd { + reason: reason as i32, + protocol_error: None, + }, + )), + } +} + +fn body_invocation_with_reason( + stage: &HttpResponseStage, + outcome: HttpResponseInvocationOutcome, + sequence: u64, + input_size: usize, + output_size: usize, + reason_code: Option, +) -> HttpResponseInvocation { + HttpResponseInvocation { + config_name: stage.entry.entry.name.clone(), + implementation: stage.entry.entry.implementation.clone(), + outcome, + sequence: Some(sequence), + input_size, + output_size: Some(output_size), + failed: false, + stage_disabled: false, + reason_code, + failure_category: None, + } +} + +fn collect_diagnostics( + stage: &HttpResponseStage, + mut findings: Vec, + mut metadata: std::collections::HashMap, + all_findings: &mut Vec, + all_metadata: &mut BTreeMap>, +) { + if stage + .entry + .service + .as_ref() + .is_some_and(|service| service.diagnostic_policy == MiddlewareDiagnosticPolicy::Normalize) + { + metadata.clear(); + for finding in &mut findings { + finding.r#type = format!("{}.finding", stage.entry.entry.implementation); + finding.label = super::EXTERNAL_FINDING_LABEL.to_string(); + finding.confidence.clear(); + finding.severity = "medium".into(); + } + } + all_findings.extend(findings.into_iter().map(|finding| NamespacedFinding { + middleware: stage.entry.entry.name.clone(), + finding, + })); + if !metadata.is_empty() { + all_metadata.insert( + stage.entry.entry.name.clone(), + metadata.into_iter().collect(), + ); + } +} + +fn collect_preflight_diagnostics( + entry: &DescribedChainEntry, + findings: Vec, + metadata: std::collections::HashMap, + all_findings: &mut Vec, + all_metadata: &mut BTreeMap>, +) { + let stage = HttpResponseStage { + entry: entry.clone(), + transport: None, + mode: StageMode::HeadersOnly, + next_sequence: 1, + whole_body: Vec::new(), + }; + collect_diagnostics(&stage, findings, metadata, all_findings, all_metadata); +} + +fn collect_preflight_failure( + entry: &DescribedChainEntry, + reason: &str, + invocations: &mut Vec, +) -> Option { + let fail_closed = entry.on_error() == OnError::FailClosed; + invocations.push(HttpResponseInvocation { + config_name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + outcome: if fail_closed { + HttpResponseInvocationOutcome::FailClosed + } else { + HttpResponseInvocationOutcome::FailOpen + }, + sequence: None, + input_size: 0, + output_size: None, + failed: true, + stage_disabled: true, + reason_code: None, + failure_category: Some(response_failure_category(reason).into()), + }); + fail_closed.then(|| format!("middleware_failed: {reason}")) +} + +fn response_failure_category(reason: &str) -> &'static str { + if reason == "middleware_session_capacity_exhausted" { + "session_capacity" + } else if reason.contains("over_capacity") { + "payload_capacity" + } else if reason.contains("timeout") { + "timeout" + } else if reason.contains("stream_closed") + || reason.contains("stream closed") + || reason.contains("transport") + || reason.contains("unavailable") + { + "transport" + } else if matches!( + reason, + "bodyless_response" + | "response_input_unrepresentable" + | "partial_response" + | "content_coding_not_identity" + | "cache_control_no_transform" + ) { + "response_not_inspectable" + } else { + "invalid_result" + } +} + +fn empty_preflight_outcome(headers: Vec) -> HttpResponsePreflightOutcome { + HttpResponsePreflightOutcome { + allowed: true, + reason: String::new(), + denial: None, + headers, + session: None, + findings: Vec::new(), + metadata: BTreeMap::new(), + invocations: Vec::new(), + session_capacity_exhausted: false, + } +} + +fn failed_preflight_outcome( + headers: Vec, + reason: String, + findings: Vec, + metadata: BTreeMap>, + invocations: Vec, +) -> HttpResponsePreflightOutcome { + HttpResponsePreflightOutcome { + allowed: false, + reason, + denial: None, + headers, + session: None, + findings, + metadata, + invocations, + session_capacity_exhausted: false, + } +} + +fn blocked_preflight_outcome( + headers: Vec, + denial: super::MiddlewareDenial, + findings: Vec, + metadata: BTreeMap>, + invocations: Vec, +) -> HttpResponsePreflightOutcome { + HttpResponsePreflightOutcome { + allowed: false, + reason: middleware_denial_reason(&denial.config_name, denial.reason_code.as_deref()), + denial: Some(denial), + headers, + session: None, + findings, + metadata, + invocations, + session_capacity_exhausted: false, + } +} + +fn response_preflight_input_failure( + entries: &[DescribedChainEntry], + headers: Vec, + reason: &str, +) -> HttpResponsePreflightOutcome { + let mut outcome = empty_preflight_outcome(headers); + for entry in entries { + if let Some(reason) = collect_preflight_failure(entry, reason, &mut outcome.invocations) { + outcome.allowed = false; + outcome.reason = reason; + break; + } + } + outcome +} + +fn response_session_capacity_exhausted( + entries: Vec, + headers: Vec, +) -> HttpResponsePreflightOutcome { + let mut invocations = Vec::new(); + let fail_closed = entries.iter().any(|entry| { + collect_preflight_failure( + entry, + "middleware_session_capacity_exhausted", + &mut invocations, + ) + .is_some() + }); + HttpResponsePreflightOutcome { + allowed: !fail_closed, + reason: if fail_closed { + "middleware_failed: middleware_session_capacity_exhausted".into() + } else { + String::new() + }, + denial: None, + headers, + session: None, + findings: Vec::new(), + metadata: BTreeMap::new(), + invocations, + session_capacity_exhausted: true, + } +} + +async fn end_stages(stages: &mut [HttpResponseStage], reason: MiddlewareSessionEndReason) { + for stage in stages { + stage.end(reason).await; + } +} + +async fn handle_opened_preflight_failure( + entry: &DescribedChainEntry, + current_stage: &mut HttpResponseStage, + prior_stages: &mut [HttpResponseStage], + reason: &str, + invocations: &mut Vec, +) -> Option { + current_stage + .end(MiddlewareSessionEndReason::MiddlewareFailure) + .await; + let failure = collect_preflight_failure(entry, reason, invocations); + if failure.is_some() { + end_stages(prior_stages, MiddlewareSessionEndReason::MiddlewareFailure).await; + } + failure +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use openshell_core::middleware::{HttpRequestView, InProcessMiddleware}; + use openshell_core::proto::{ + Decision, ExistingHeaderAction, HeaderMutation, HttpRequestResult, HttpResponseBodyResult, + HttpResponseBodyTransform, HttpResponsePreflightInspect, HttpResponsePreflightResult, + HttpResponsePreflightSkip, HttpResponseTrailersResult, MiddlewareBinding, + MiddlewareManifest, WriteHeader, header_mutation, http_response_preflight_result, + }; + use tokio_stream::wrappers::ReceiverStream; + use tokio_stream::wrappers::TcpListenerStream; + + use super::*; + + #[derive(Clone, Copy)] + enum Script { + HeadersOnly, + Stream, + WholeBody, + InvalidSequence, + Configured, + HangBody, + LargeStream, + Expansion, + DeleteBody, + SkipBody, + Skip, + InvalidSkipReason, + TrailerMutation, + InvalidTrailerMutation, + } + + struct ResponseService { + script: Script, + } + + struct PreflightLifecycleService { + completion_tx: mpsc::UnboundedSender<(String, Vec)>, + } + + #[derive(Clone)] + struct RemoteResponseService { + session_end_tx: Option>, + } + + #[tonic::async_trait] + impl openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware + for RemoteResponseService + { + type EvaluateWebSocketSessionStream = super::super::WebSocketResponseStream; + + async fn describe( + &self, + _request: tonic::Request<()>, + ) -> Result, tonic::Status> { + Ok(tonic::Response::new(response_manifest( + "test/remote-response", + ))) + } + + async fn validate_config( + &self, + _request: tonic::Request, + ) -> Result, tonic::Status> + { + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + _request: tonic::Request, + ) -> Result, tonic::Status> { + Ok(tonic::Response::new(HttpRequestResult { + decision: Decision::Allow as i32, + ..Default::default() + })) + } + + async fn evaluate_web_socket_session( + &self, + _request: tonic::Request< + tonic::Streaming, + >, + ) -> Result, tonic::Status> { + Err(tonic::Status::unimplemented("HTTP response-only service")) + } + } + + #[tonic::async_trait] + impl openshell_core::proto::middleware::v1::http_response_pre_return_server::HttpResponsePreReturn + for RemoteResponseService + { + type EvaluateStream = super::super::HttpResponseResultStream; + + async fn evaluate( + &self, + request: tonic::Request>, + ) -> Result, tonic::Status> { + let mut requests = request.into_inner(); + // Exercise servers that inspect the initial request before sending + // response headers, rather than returning a stream immediately. + let first = requests.next().await.expect("initial request"); + assert!(matches!(&first, Ok(HttpResponseEvent { + event: Some(http_response_event::Event::Preflight(_)) + }))); + let mut requests = futures::stream::iter([first]).chain(requests); + let (sender, receiver) = mpsc::channel(4); + let session_end_tx = self.session_end_tx.clone(); + tokio::spawn(async move { + while let Some(Ok(event)) = requests.next().await { + match event.event { + Some(http_response_event::Event::Preflight(_)) => { + let result = HttpResponseEventResult { + result: Some( + http_response_event_result::Result::PreflightResult( + HttpResponsePreflightResult { + action: Some( + http_response_preflight_result::Action::Inspect( + HttpResponsePreflightInspect { + body_mode: + HttpResponseBodyMode::HeadersOnly as i32, + header_mutations: vec![write_header( + "cache-control", + "remote", + )], + }, + ), + ), + ..Default::default() + }, + ), + ), + }; + if sender.send(Ok(result)).await.is_err() { + break; + } + } + Some(http_response_event::Event::SessionEnd(end)) => { + if let Some(sender) = &session_end_tx + && let Ok(reason) = MiddlewareSessionEndReason::try_from(end.reason) + { + let _ = sender.send(reason); + } + break; + } + None => break, + _ => {} + } + } + }); + Ok(tonic::Response::new(Box::pin(ReceiverStream::new(receiver)))) + } + } + + #[tonic::async_trait] + impl InProcessMiddleware for ResponseService { + async fn describe(&self) -> MiddlewareManifest { + MiddlewareManifest { + name: "test/response".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: openshell_core::proto::SupervisorMiddlewareOperation::HttpResponse + as i32, + phase: openshell_core::proto::SupervisorMiddlewarePhase::PreReturn as i32, + max_payload_bytes: if matches!( + self.script, + Script::LargeStream | Script::Expansion + ) { + 128 * 1024 + } else { + 4096 + }, + request_timeout: matches!(self.script, Script::HangBody).then(|| { + openshell_core::time::duration_from_std(Duration::from_millis(10)) + .expect("test timeout is in protobuf range") + }), + }], + expected_audience: String::new(), + } + } + + async fn validate_config( + &self, + _middleware_name: &str, + _config: &prost_types::Struct, + ) -> miette::Result<()> { + Ok(()) + } + + async fn evaluate_http_request( + &self, + _request: HttpRequestView<'_>, + ) -> miette::Result { + Ok(HttpRequestResult { + decision: Decision::Allow as i32, + ..Default::default() + }) + } + + async fn open_http_response_pre_return( + &self, + mut requests: mpsc::Receiver, + ) -> Result { + let (sender, receiver) = mpsc::channel(4); + let script = self.script; + tokio::spawn(async move { + let mut selected_script = script; + while let Some(event) = requests.recv().await { + let Some(event) = event.event else { + break; + }; + let result = match event { + http_response_event::Event::Preflight(preflight) => { + if matches!(script, Script::Configured) { + selected_script = match preflight + .config + .as_ref() + .and_then(|config| config.fields.get("mode")) + .and_then(|value| value.kind.as_ref()) + { + Some(prost_types::value::Kind::StringValue(mode)) + if mode == "whole" => + { + Script::WholeBody + } + Some(prost_types::value::Kind::StringValue(mode)) + if mode == "stream" => + { + Script::Stream + } + _ => Script::HeadersOnly, + }; + } + if matches!(selected_script, Script::Skip | Script::InvalidSkipReason) { + HttpResponseEventResult { + result: Some( + http_response_event_result::Result::PreflightResult( + HttpResponsePreflightResult { + action: Some( + http_response_preflight_result::Action::Skip( + HttpResponsePreflightSkip {}, + ), + ), + reason: if matches!( + selected_script, + Script::InvalidSkipReason + ) { + "x".repeat(MAX_MIDDLEWARE_REASON_BYTES + 1) + } else { + "not selected".into() + }, + reason_code: "path_not_selected".into(), + ..Default::default() + }, + ), + ), + } + } else { + let (body_mode, header_mutations) = match selected_script { + Script::HeadersOnly => ( + HttpResponseBodyMode::HeadersOnly, + vec![write_header("cache-control", "private")], + ), + Script::Stream + | Script::InvalidSequence + | Script::HangBody + | Script::LargeStream + | Script::Expansion + | Script::DeleteBody + | Script::SkipBody + | Script::TrailerMutation + | Script::InvalidTrailerMutation => { + (HttpResponseBodyMode::StreamBytes, Vec::new()) + } + Script::WholeBody => { + (HttpResponseBodyMode::WholeBodyBytes, Vec::new()) + } + Script::Configured + | Script::Skip + | Script::InvalidSkipReason => unreachable!(), + }; + HttpResponseEventResult { + result: Some( + http_response_event_result::Result::PreflightResult( + HttpResponsePreflightResult { + action: Some( + http_response_preflight_result::Action::Inspect( + HttpResponsePreflightInspect { + body_mode: body_mode as i32, + header_mutations, + }, + ), + ), + ..Default::default() + }, + ), + ), + } + } + } + http_response_event::Event::Body(body) => { + if matches!(selected_script, Script::HangBody) { + continue; + } + let Some(http_response_body_unit::Payload::Data(data)) = body.payload + else { + break; + }; + let replacement = match selected_script { + Script::Expansion => vec![b'x'; 128 * 1024], + Script::DeleteBody => Vec::new(), + Script::SkipBody => b"replacement".to_vec(), + Script::Stream + | Script::InvalidSequence + | Script::LargeStream + | Script::TrailerMutation + | Script::InvalidTrailerMutation => data.to_ascii_uppercase(), + Script::WholeBody => [b"whole:".as_slice(), &data].concat(), + Script::HeadersOnly + | Script::Configured + | Script::HangBody + | Script::Skip + | Script::InvalidSkipReason => break, + }; + let transform = HttpResponseBodyTransform { + replacement: Some(http_response_body_transform::Replacement::Data( + replacement, + )), + }; + let action = if matches!(selected_script, Script::SkipBody) { + http_response_body_result::Action::SkipRemaining( + openshell_core::proto::HttpResponseBodySkipRemaining { + current: Some( + http_response_body_skip_remaining::Current::Transform( + transform, + ), + ), + }, + ) + } else { + http_response_body_result::Action::Transform(transform) + }; + HttpResponseEventResult { + result: Some(http_response_event_result::Result::BodyResult( + HttpResponseBodyResult { + sequence: if matches!( + selected_script, + Script::InvalidSequence + ) { + body.sequence + 1 + } else { + body.sequence + }, + action: Some(action), + ..Default::default() + }, + )), + } + } + http_response_event::Event::Trailers(_) => HttpResponseEventResult { + result: Some(http_response_event_result::Result::TrailersResult( + HttpResponseTrailersResult { + trailer_mutations: match selected_script { + Script::TrailerMutation => { + vec![write_header("x-upstream", "changed")] + } + Script::InvalidTrailerMutation => vec![ + write_header("x-upstream", "changed"), + write_header("x-new", "not-allowed"), + ], + _ => Vec::new(), + }, + ..Default::default() + }, + )), + }, + http_response_event::Event::SessionEnd(_) => break, + }; + if sender.send(Ok(result)).await.is_err() { + break; + } + } + }); + Ok(Box::pin(ReceiverStream::new(receiver))) + } + } + + #[tonic::async_trait] + impl InProcessMiddleware for PreflightLifecycleService { + async fn describe(&self) -> MiddlewareManifest { + response_manifest("test/preflight-lifecycle") + } + + async fn validate_config( + &self, + _middleware_name: &str, + _config: &prost_types::Struct, + ) -> miette::Result<()> { + Ok(()) + } + + async fn evaluate_http_request( + &self, + _request: HttpRequestView<'_>, + ) -> miette::Result { + unreachable!() + } + + async fn open_http_response_pre_return( + &self, + mut requests: mpsc::Receiver, + ) -> Result { + let (sender, receiver) = mpsc::channel(4); + let completion_tx = self.completion_tx.clone(); + tokio::spawn(async move { + let Some(HttpResponseEvent { + event: Some(http_response_event::Event::Preflight(preflight)), + }) = requests.recv().await + else { + return; + }; + let config_value = |name: &str| { + preflight + .config + .as_ref() + .and_then(|config| config.fields.get(name)) + .and_then(|value| value.kind.as_ref()) + .and_then(|kind| match kind { + prost_types::value::Kind::StringValue(value) => Some(value.clone()), + _ => None, + }) + .unwrap_or_default() + }; + let label = config_value("label"); + let behavior = config_value("behavior"); + let inspect = |body_mode, header_mutations| HttpResponsePreflightResult { + action: Some(http_response_preflight_result::Action::Inspect( + HttpResponsePreflightInspect { + body_mode, + header_mutations, + }, + )), + ..Default::default() + }; + let result = match behavior.as_str() { + "stream" => http_response_event_result::Result::PreflightResult(inspect( + HttpResponseBodyMode::StreamBytes as i32, + Vec::new(), + )), + "wrong-envelope" => http_response_event_result::Result::BodyResult( + HttpResponseBodyResult::default(), + ), + "invalid-diagnostics" => { + let mut result = + inspect(HttpResponseBodyMode::HeadersOnly as i32, Vec::new()); + result.reason = "x".repeat(MAX_MIDDLEWARE_REASON_BYTES + 1); + http_response_event_result::Result::PreflightResult(result) + } + "unsupported-body-mode" => http_response_event_result::Result::PreflightResult( + inspect(i32::MAX, Vec::new()), + ), + "invalid-header-mutation" => { + http_response_event_result::Result::PreflightResult(inspect( + HttpResponseBodyMode::HeadersOnly as i32, + vec![write_header("content-length", "1")], + )) + } + "no-action" => http_response_event_result::Result::PreflightResult( + HttpResponsePreflightResult::default(), + ), + behavior => panic!("unknown lifecycle test behavior: {behavior}"), + }; + if sender + .send(Ok(HttpResponseEventResult { + result: Some(result), + })) + .await + .is_err() + { + return; + } + + let mut terminal_reasons = Vec::new(); + while let Some(event) = requests.recv().await { + if let Some(http_response_event::Event::SessionEnd(end)) = event.event + && let Ok(reason) = MiddlewareSessionEndReason::try_from(end.reason) + { + terminal_reasons.push(reason); + } + } + let _ = completion_tx.send((label, terminal_reasons)); + }); + Ok(Box::pin(ReceiverStream::new(receiver))) + } + } + + fn write_header(name: &str, value: &str) -> HeaderMutation { + HeaderMutation { + operation: Some(header_mutation::Operation::Write(WriteHeader { + name: name.into(), + value: value.into(), + on_existing: ExistingHeaderAction::Overwrite as i32, + })), + } + } + + fn response_manifest(name: &str) -> MiddlewareManifest { + MiddlewareManifest { + name: name.into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: openshell_core::proto::SupervisorMiddlewareOperation::HttpResponse + as i32, + phase: openshell_core::proto::SupervisorMiddlewarePhase::PreReturn as i32, + max_payload_bytes: 4096, + request_timeout: None, + }], + expected_audience: String::new(), + } + } + + fn entry(on_error: OnError) -> ChainEntry { + ChainEntry { + name: "response".into(), + implementation: "test/response".into(), + order: 0, + config: prost_types::Struct::default(), + on_error, + } + } + + fn configured_entry(name: &str, order: i32, mode: &str) -> ChainEntry { + ChainEntry { + name: name.into(), + implementation: "test/response".into(), + order, + config: prost_types::Struct { + fields: [( + "mode".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue(mode.into())), + }, + )] + .into(), + }, + on_error: OnError::FailClosed, + } + } + + fn lifecycle_entry(name: &str, order: i32, behavior: &str, on_error: OnError) -> ChainEntry { + let string_value = |value: &str| prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue(value.into())), + }; + ChainEntry { + name: name.into(), + implementation: "test/preflight-lifecycle".into(), + order, + config: prost_types::Struct { + fields: [ + ("label".into(), string_value(name)), + ("behavior".into(), string_value(behavior)), + ] + .into(), + }, + on_error, + } + } + + fn input(status_code: u16) -> HttpResponsePreflightInput { + HttpResponsePreflightInput { + context: RequestContext { + request_id: "req-1".into(), + sandbox_id: "sandbox-1".into(), + ..Default::default() + }, + target: HttpRequestTarget { + scheme: "https".into(), + host: "example.com".into(), + port: 443, + method: "GET".into(), + path: "/data".into(), + query: String::new(), + }, + status_code, + declared_body_length: None, + headers: vec![HttpHeader { + name: "content-type".into(), + value: "text/plain".into(), + }], + connection_nominated_headers: Vec::new(), + } + } + + #[tokio::test] + async fn response_preflight_envelope_limits_obey_selected_stage_policies() { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::HeadersOnly, + })); + for limit in 0..4 { + let mut input = input(200); + match limit { + 0 => input.context.request_id = "x".repeat(MAX_MIDDLEWARE_CONTEXT_BYTES + 1), + 1 => input.target.path = "x".repeat(MAX_MIDDLEWARE_TARGET_BYTES + 1), + 2 => input.headers = vec![input.headers[0].clone(); MAX_MIDDLEWARE_HEADERS + 1], + _ => input.headers[0].value = "x".repeat(MAX_MIDDLEWARE_HEADER_BYTES + 1), + } + for last_policy in [OnError::FailOpen, OnError::FailClosed] { + let entries = [entry(OnError::FailOpen), entry(last_policy)]; + let outcome = runner + .preflight_http_response(&entries, input.clone()) + .await + .unwrap(); + assert_eq!(outcome.allowed, last_policy == OnError::FailOpen); + assert_eq!(outcome.headers, input.headers); + assert!(outcome.session.is_none()); + assert_eq!(outcome.invocations.len(), 2); + assert!( + outcome + .invocations + .iter() + .all(|invocation| invocation.failed && invocation.stage_disabled) + ); + assert_eq!( + outcome.invocations[1].failure_category.as_deref(), + Some("payload_capacity") + ); + } + } + let described = runner + .describe_http_response_chain(&[entry(OnError::FailOpen), entry(OnError::FailClosed)]) + .await + .unwrap(); + let outcome = runner.http_response_input_unrepresentable(&described); + assert!(!outcome.allowed); + assert_eq!(outcome.invocations.len(), 2); + assert!(outcome.invocations.iter().all(|invocation| { + invocation.failure_category.as_deref() == Some("response_not_inspectable") + })); + } + + #[tokio::test] + async fn invalid_opened_preflight_stages_receive_one_failure_terminal_event() { + for behavior in [ + "wrong-envelope", + "invalid-diagnostics", + "unsupported-body-mode", + "invalid-header-mutation", + "no-action", + ] { + for on_error in [OnError::FailOpen, OnError::FailClosed] { + let (completion_tx, mut completion_rx) = mpsc::unbounded_channel(); + let runner = + ChainRunner::new(Arc::new(PreflightLifecycleService { completion_tx })); + let entries = [ + lifecycle_entry("prior", 0, "stream", OnError::FailClosed), + lifecycle_entry("invalid", 1, behavior, on_error), + ]; + let mut outcome = runner + .preflight_http_response(&entries, input(200)) + .await + .expect("invalid preflight response"); + assert_eq!(outcome.allowed, on_error == OnError::FailOpen); + if let Some(session) = outcome.session.take() { + session.end(MiddlewareSessionEndReason::Normal).await; + } + + let mut completions = BTreeMap::new(); + for _ in 0..2 { + let (label, reasons) = + tokio::time::timeout(Duration::from_secs(1), completion_rx.recv()) + .await + .expect("bounded terminal event delivery") + .expect("opened stage completion"); + assert!(completions.insert(label, reasons).is_none()); + } + assert_eq!( + completions.get("invalid").map(Vec::as_slice), + Some([MiddlewareSessionEndReason::MiddlewareFailure].as_slice()), + "invalid behavior: {behavior}, policy: {on_error:?}" + ); + let prior_reason = if on_error == OnError::FailOpen { + MiddlewareSessionEndReason::Normal + } else { + MiddlewareSessionEndReason::MiddlewareFailure + }; + assert_eq!( + completions.get("prior").map(Vec::as_slice), + Some([prior_reason].as_slice()), + "invalid behavior: {behavior}, policy: {on_error:?}" + ); + assert!(completion_rx.try_recv().is_err()); + } + } + } + + #[test] + fn stream_mode_requires_only_one_byte_of_payload_capacity() { + let mut described = DescribedChainEntry { + entry: entry(OnError::FailClosed), + service: None, + binding: None, + max_payload_bytes: 1, + timeout: Duration::from_millis(500), + }; + + let modes = permitted_body_modes(&input(200), &described, None); + assert!(modes.contains(&(HttpResponseBodyMode::StreamBytes as i32))); + + described.max_payload_bytes = 0; + let modes = permitted_body_modes(&input(200), &described, None); + assert!(!modes.contains(&(HttpResponseBodyMode::StreamBytes as i32))); + } + + struct ReadPreflightBeforeOpening { + failure: Option, + } + + #[tonic::async_trait] + impl InProcessMiddleware for ReadPreflightBeforeOpening { + async fn describe(&self) -> MiddlewareManifest { + let mut manifest = response_manifest("test/response"); + manifest.bindings[0].request_timeout = Some( + openshell_core::time::duration_from_std(Duration::from_millis(10)) + .expect("test timeout is in protobuf range"), + ); + manifest + } + + async fn validate_config(&self, _: &str, _: &prost_types::Struct) -> miette::Result<()> { + Ok(()) + } + + async fn evaluate_http_request( + &self, + _: HttpRequestView<'_>, + ) -> miette::Result { + unreachable!() + } + + async fn open_http_response_pre_return( + &self, + mut requests: mpsc::Receiver, + ) -> Result { + let first = requests.recv().await.expect("initial preflight"); + assert!(matches!( + first.event, + Some(http_response_event::Event::Preflight(_)) + )); + if let Some(hang) = self.failure { + if hang { + futures::future::pending::<()>().await; + } + return Err(tonic::Status::unavailable("startup failed")); + } + let response = HttpResponseEventResult { + result: Some(http_response_event_result::Result::PreflightResult( + HttpResponsePreflightResult { + action: Some(http_response_preflight_result::Action::Inspect( + HttpResponsePreflightInspect { + body_mode: HttpResponseBodyMode::HeadersOnly as i32, + header_mutations: Vec::new(), + }, + )), + ..Default::default() + }, + )), + }; + Ok(Box::pin(futures::stream::iter([Ok(response)]))) + } + } + + #[tokio::test] + async fn preflight_can_be_read_before_open_returns() { + let runner = ChainRunner::new(Arc::new(ReadPreflightBeforeOpening { failure: None })); + let outcome = tokio::time::timeout( + Duration::from_secs(1), + runner.preflight_http_response(&[entry(OnError::FailClosed)], input(200)), + ) + .await + .expect("bounded startup") + .expect("preflight"); + assert!(outcome.allowed, "{}", outcome.reason); + } + + #[tokio::test] + async fn preflight_opening_failure_obeys_policy_and_releases_admission() { + for hang in [false, true] { + for on_error in [OnError::FailOpen, OnError::FailClosed] { + let runner = ChainRunner::new(Arc::new(ReadPreflightBeforeOpening { + failure: Some(hang), + })); + let permits = runner.registry.session_admission.available_permits(); + let outcome = tokio::time::timeout( + Duration::from_secs(1), + runner.preflight_http_response(&[entry(on_error)], input(200)), + ) + .await + .expect("bounded opening failure") + .unwrap(); + assert_eq!(outcome.allowed, on_error == OnError::FailOpen); + assert!(outcome.session.is_none()); + assert_eq!( + runner.registry.session_admission.available_permits(), + permits + ); + assert!(outcome.invocations[0].failed); + } + } + } + + #[tokio::test] + async fn multiple_whole_body_barriers_preserve_accounting_on_overflow_and_expiry() { + for expire in [false, true] { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::Configured, + })); + let mut entries = vec![ + configured_entry("first", 0, "whole"), + configured_entry("second", 1, "whole"), + configured_entry("stream", 2, "stream"), + ]; + for entry in &mut entries { + entry.on_error = OnError::FailOpen; + } + let mut outcome = runner + .preflight_http_response(&entries, input(200)) + .await + .unwrap(); + let mut session = outcome.session.take().unwrap(); + for _ in 0..2 { + assert!( + session + .push_body(vec![b'a'; 2048]) + .await + .unwrap() + .is_empty() + ); + assert!(session.retained_body_bytes <= 4096); + assert_eq!( + session + .stages + .iter() + .filter(|stage| !stage.whole_body.is_empty()) + .count(), + 1 + ); + } + let output = if expire { + session.start_whole_body_deadline(Duration::ZERO); + session.expire_whole_body_deadline().await.unwrap() + } else { + session.push_body(vec![b'a'; 2048]).await.unwrap() + }; + assert_eq!( + output.concat(), + vec![b'A'; if expire { 4096 } else { 6144 }] + ); + assert_eq!(session.retained_body_bytes, 0); + assert_eq!( + session.push_body(b"next".to_vec()).await.unwrap().concat(), + b"NEXT" + ); + assert_eq!(session.retained_body_bytes, 0); + assert!( + session + .finish(Vec::new()) + .await + .unwrap() + .body_units + .is_empty() + ); + } + } + + #[tokio::test] + async fn deleted_and_skip_remaining_units_release_body_accounting() { + for script in [Script::DeleteBody, Script::SkipBody] { + let runner = ChainRunner::new(Arc::new(ResponseService { script })); + let mut outcome = runner + .preflight_http_response(&[entry(OnError::FailClosed)], input(200)) + .await + .unwrap(); + let mut session = outcome.session.take().unwrap(); + for index in 0..3 { + let output = session.push_body(b"original".to_vec()).await.unwrap(); + let expected = match script { + Script::DeleteBody => Vec::new(), + Script::SkipBody if index == 0 => b"replacement".to_vec(), + Script::SkipBody => b"original".to_vec(), + _ => unreachable!(), + }; + assert_eq!(output.concat(), expected); + assert_eq!(session.retained_body_bytes, 0); + } + assert!( + session + .finish(Vec::new()) + .await + .unwrap() + .body_units + .is_empty() + ); + } + } + + #[tokio::test] + async fn expanding_stages_obey_aggregate_budget_and_failure_policy() { + for on_error in [OnError::FailClosed, OnError::FailOpen] { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::Expansion, + })); + let permits = runner.registry.session_admission.available_permits(); + let entries = (0..9) + .map(|order| { + let mut entry = entry(on_error); + entry.name = format!("expand-{order}"); + entry.order = order; + entry + }) + .collect::>(); + let mut outcome = runner + .preflight_http_response(&entries, input(200)) + .await + .unwrap(); + let mut session = outcome.session.take().unwrap(); + let result = tokio::time::timeout(Duration::from_secs(5), session.push_body(vec![1])) + .await + .expect("bounded expansion"); + match result { + Ok(output) => { + assert_eq!(on_error, OnError::FailOpen); + assert!( + output.iter().map(Vec::len).sum::() + < MAX_HTTP_RESPONSE_RETAINED_BODY_BYTES + ); + assert!(output.iter().flatten().all(|byte| *byte == b'x')); + assert_eq!(session.retained_body_bytes, 0); + assert!( + session + .invocations + .iter() + .any(|invocation| invocation.outcome + == HttpResponseInvocationOutcome::FailOpen) + ); + // Holding returned output applies backpressure: subsequent + // stage work starts only when the relay calls again. + drop(output); + for _ in 0..3 { + let output = session.push_body(vec![1]).await.unwrap(); + assert!( + output.iter().map(Vec::len).sum::() + < MAX_HTTP_RESPONSE_RETAINED_BODY_BYTES + ); + assert_eq!(session.retained_body_bytes, 0); + } + let finish = session.finish(Vec::new()).await.unwrap(); + assert!( + finish.body_units.iter().map(Vec::len).sum::() + < MAX_HTTP_RESPONSE_RETAINED_BODY_BYTES + ); + } + Err(failure) => { + assert_eq!(on_error, OnError::FailClosed); + assert!( + failure + .reason + .contains("response_body_aggregate_over_capacity") + ); + session + .end(MiddlewareSessionEndReason::MiddlewareFailure) + .await; + } + } + assert_eq!( + runner.registry.session_admission.available_permits(), + permits + ); + } + } + + #[tokio::test] + async fn headers_only_preflight_applies_end_to_end_mutation() { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::HeadersOnly, + })); + let outcome = runner + .preflight_http_response(&[entry(OnError::FailClosed)], input(200)) + .await + .expect("response preflight"); + + assert!(outcome.allowed); + assert_eq!( + outcome + .headers + .iter() + .find(|header| header.name == "cache-control") + .map(|header| header.value.as_str()), + Some("private") + ); + assert!(outcome.session.is_none()); + } + + #[tokio::test] + async fn stream_mode_transforms_lockstep_units_and_preserves_trailers() { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::Stream, + })); + let mut outcome = runner + .preflight_http_response(&[entry(OnError::FailClosed)], input(200)) + .await + .expect("response preflight"); + let mut session = outcome.session.take().expect("streaming session"); + + assert_eq!( + session + .push_body(b"hello".to_vec()) + .await + .expect("transform stream unit"), + vec![b"HELLO".to_vec()] + ); + let original_trailers = vec![HttpHeader { + name: "x-upstream".into(), + value: "retained".into(), + }]; + let finish = session + .finish(original_trailers.clone()) + .await + .expect("finish stream"); + assert!(finish.body_units.is_empty()); + assert_eq!(finish.trailers, original_trailers); + } + + #[tokio::test] + async fn whole_body_mode_releases_replacement_only_at_finish() { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::WholeBody, + })); + let mut outcome = runner + .preflight_http_response(&[entry(OnError::FailClosed)], input(200)) + .await + .expect("response preflight"); + let mut session = outcome.session.take().expect("whole-body session"); + assert!(session.requires_whole_body()); + assert!( + session + .push_body(b"one".to_vec()) + .await + .expect("buffer first unit") + .is_empty() + ); + assert!( + session + .push_body(b"two".to_vec()) + .await + .expect("buffer second unit") + .is_empty() + ); + + let finish = session.finish(Vec::new()).await.expect("finish whole body"); + assert_eq!(finish.body_units, vec![b"whole:onetwo".to_vec()]); + } + + #[tokio::test] + async fn mixed_profile_chain_respects_policy_order_and_whole_body_barrier() { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::Configured, + })); + let entries = vec![ + configured_entry("stream", 20, "stream"), + configured_entry("whole", 10, "whole"), + ]; + let mut outcome = runner + .preflight_http_response(&entries, input(200)) + .await + .expect("mixed response preflight"); + let mut session = outcome.session.take().expect("mixed response session"); + assert!(session.requires_whole_body()); + assert!( + session + .push_body(b"hello".to_vec()) + .await + .expect("buffer mixed response") + .is_empty() + ); + let finish = session + .finish(Vec::new()) + .await + .expect("finish mixed chain"); + assert_eq!(finish.body_units, vec![b"WHOLE:HELLO".to_vec()]); + } + + #[tokio::test] + async fn whole_body_overflow_obeys_fail_open_and_fail_closed() { + for (on_error, allowed) in [(OnError::FailOpen, true), (OnError::FailClosed, false)] { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::WholeBody, + })); + let mut outcome = runner + .preflight_http_response(&[entry(on_error)], input(200)) + .await + .expect("whole-body response preflight"); + let mut session = outcome.session.take().expect("whole-body session"); + let original = vec![b'a'; 4097]; + let pushed = session.push_body(original.clone()).await; + assert_eq!(pushed.is_ok(), allowed); + if allowed { + assert_eq!(pushed.unwrap(), vec![original]); + assert!(!session.requires_whole_body()); + for fill in [b'b', b'c'] { + let unit = vec![fill; MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES]; + assert_eq!( + session + .push_body(unit.clone()) + .await + .expect("fail-open stage must release later units"), + vec![unit] + ); + } + let finish = session.finish(Vec::new()).await.expect("fail-open finish"); + assert!(finish.body_units.is_empty()); + } + } + } + + #[tokio::test] + async fn response_body_timeout_obeys_fail_open_and_fail_closed() { + for (on_error, allowed) in [(OnError::FailOpen, true), (OnError::FailClosed, false)] { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::HangBody, + })); + let mut outcome = runner + .preflight_http_response(&[entry(on_error)], input(200)) + .await + .expect("timed response preflight"); + let mut session = outcome.session.take().expect("timed response session"); + let result = session.push_body(b"unchanged".to_vec()).await; + assert_eq!(result.is_ok(), allowed); + if let Ok(units) = result { + assert_eq!(units, vec![b"unchanged".to_vec()]); + } + } + } + + #[tokio::test] + async fn stream_unit_limit_never_exceeds_platform_cap() { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::LargeStream, + })); + let mut outcome = runner + .preflight_http_response(&[entry(OnError::FailClosed)], input(200)) + .await + .expect("large stream preflight"); + let mut session = outcome.session.take().expect("large stream session"); + assert_eq!( + session.stream_unit_limit(), + MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES + ); + let maximum_unit = vec![b'A'; MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES]; + assert_eq!( + session + .push_body(maximum_unit.clone()) + .await + .expect("maximum stream unit"), + vec![maximum_unit] + ); + assert_eq!( + session + .push_body(vec![b'b'; MAX_HTTP_RESPONSE_STREAM_UNIT_BYTES + 1]) + .await + .expect_err("oversized stream unit") + .reason, + "response_stream_unit_over_capacity" + ); + session + .finish(Vec::new()) + .await + .expect("finish large stream"); + } + + #[tokio::test] + async fn skip_reason_code_is_retained_and_oversized_reason_obeys_on_error() { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::Skip, + })); + let outcome = runner + .preflight_http_response(&[entry(OnError::FailClosed)], input(200)) + .await + .expect("skip response preflight"); + assert!(outcome.allowed); + assert!(outcome.session.is_none()); + assert_eq!( + outcome.invocations[0].reason_code.as_deref(), + Some("path_not_selected") + ); + + for (on_error, allowed) in [(OnError::FailOpen, true), (OnError::FailClosed, false)] { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::InvalidSkipReason, + })); + let outcome = runner + .preflight_http_response(&[entry(on_error)], input(200)) + .await + .expect("invalid skip response preflight"); + assert_eq!(outcome.allowed, allowed); + assert!(outcome.session.is_none()); + } + } + + #[tokio::test] + async fn response_trailers_are_mutated_by_body_stage() { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::TrailerMutation, + })); + let mut outcome = runner + .preflight_http_response(&[entry(OnError::FailClosed)], input(200)) + .await + .expect("trailer response preflight"); + let mut session = outcome.session.take().expect("trailer response session"); + session + .push_body(b"body".to_vec()) + .await + .expect("transform response body"); + let trailers = vec![HttpHeader { + name: "x-upstream".into(), + value: "retained".into(), + }]; + let finish = session + .finish(trailers.clone()) + .await + .expect("finish response"); + assert_eq!( + finish.trailers, + vec![HttpHeader { + name: "x-upstream".into(), + value: "changed".into(), + }] + ); + } + + #[tokio::test] + async fn invalid_trailer_mutations_are_atomic_and_keep_failure_diagnostics() { + let trailers = vec![HttpHeader { + name: "x-upstream".into(), + value: "retained".into(), + }]; + for on_error in [OnError::FailOpen, OnError::FailClosed] { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::InvalidTrailerMutation, + })); + let mut outcome = runner + .preflight_http_response(&[entry(on_error)], input(200)) + .await + .expect("invalid trailer response preflight"); + let mut session = outcome.session.take().expect("trailer response session"); + session + .push_body(b"body".to_vec()) + .await + .expect("response body exchange"); + session.take_diagnostics(); + + match session.finish(trailers.clone()).await { + Ok(finish) => { + assert_eq!(on_error, OnError::FailOpen); + assert_eq!(finish.trailers, trailers); + assert_eq!( + finish.invocations.last().map(|entry| entry.outcome), + Some(HttpResponseInvocationOutcome::FailOpen) + ); + } + Err(failure) => { + assert_eq!(on_error, OnError::FailClosed); + assert_eq!( + failure + .diagnostics + .invocations + .last() + .map(|entry| entry.outcome), + Some(HttpResponseInvocationOutcome::FailClosed) + ); + } + } + } + } + + #[tokio::test] + async fn invalid_sequence_obeys_fail_open_and_fail_closed() { + for (on_error, allowed) in [(OnError::FailOpen, true), (OnError::FailClosed, false)] { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::InvalidSequence, + })); + let mut outcome = runner + .preflight_http_response(&[entry(on_error)], input(200)) + .await + .expect("response preflight"); + let mut session = outcome.session.take().expect("stream session"); + let result = session.push_body(b"unchanged".to_vec()).await; + assert_eq!(result.is_ok(), allowed); + if let Ok(units) = result { + assert_eq!(units, vec![b"unchanged".to_vec()]); + } + } + } + + #[tokio::test] + async fn body_inspection_restrictions_obey_fail_open_and_fail_closed() { + let mut cases = Vec::new(); + cases.push(input(206)); + for (name, value) in [ + ("content-range", "bytes 0-3/10"), + ("content-type", "multipart/byteranges; boundary=test"), + ("cache-control", "private, no-transform"), + ("content-encoding", "gzip"), + ] { + let mut candidate = input(200); + candidate.headers.push(HttpHeader { + name: name.into(), + value: value.into(), + }); + cases.push(candidate); + } + for status in [204, 304] { + cases.push(input(status)); + } + let mut head = input(200); + head.target.method = "HEAD".into(); + cases.push(head); + + for candidate in cases { + for (on_error, allowed) in [(OnError::FailOpen, true), (OnError::FailClosed, false)] { + let runner = ChainRunner::new(Arc::new(ResponseService { + script: Script::Stream, + })); + let outcome = runner + .preflight_http_response(&[entry(on_error)], candidate.clone()) + .await + .expect("restricted response preflight"); + assert_eq!(outcome.allowed, allowed); + assert!(outcome.session.is_none()); + } + } + } + + #[tokio::test] + async fn remote_service_executes_through_http_response_pre_return_rpc() { + use openshell_core::proto::middleware::v1::http_response_pre_return_server::HttpResponsePreReturnServer; + use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddlewareServer; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind response middleware"); + let address = listener.local_addr().expect("response middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let (session_end_tx, mut session_end_rx) = mpsc::unbounded_channel(); + let service = RemoteResponseService { + session_end_tx: Some(session_end_tx), + }; + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new(service.clone())) + .add_service(HttpResponsePreReturnServer::new(service)) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + let registry = super::super::MiddlewareRegistry::connect_services( + Vec::new(), + vec![openshell_core::proto::SupervisorMiddlewareService { + name: "remote-response".into(), + grpc_endpoint: format!("http://{address}"), + max_payload_bytes: 4096, + allow_insecure_transport: true, + ..Default::default() + }], + ) + .await + .expect("connect remote response middleware"); + let runner = ChainRunner::from_registry(registry); + let outcome = runner + .preflight_http_response( + &[ChainEntry { + name: "response".into(), + implementation: "remote-response".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }], + input(200), + ) + .await + .expect("remote response preflight"); + + assert!(outcome.allowed); + assert_eq!( + outcome + .headers + .iter() + .find(|header| header.name == "cache-control") + .map(|header| header.value.as_str()), + Some("remote") + ); + assert!(outcome.session.is_none()); + assert_eq!( + tokio::time::timeout(Duration::from_secs(1), session_end_rx.recv()) + .await + .expect("bounded session end delivery"), + Some(MiddlewareSessionEndReason::Normal) + ); + assert!(session_end_rx.try_recv().is_err()); + + let _ = shutdown_tx.send(()); + tokio::time::timeout(Duration::from_secs(2), server_task) + .await + .expect("bounded server shutdown") + .expect("join response middleware server") + .expect("serve response middleware"); + } +} diff --git a/crates/openshell-supervisor-middleware/src/response/preflight.rs b/crates/openshell-supervisor-middleware/src/response/preflight.rs new file mode 100644 index 0000000000..e2e53e9bbe --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/response/preflight.rs @@ -0,0 +1,427 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! HTTP response preflight and stage selection. + +use super::validation::{ + body_restriction, permitted_body_modes, strip_stale_integrity, validate_diagnostics, + validate_inspect, validate_preflight_input, +}; +use super::*; + +impl ChainRunner { + /// Apply selected stages' failure policies when valid HTTP cannot be encoded + /// in the middleware protocol. The caller must validate HTTP safety first. + pub fn http_response_input_unrepresentable( + &self, + entries: &[DescribedChainEntry], + ) -> HttpResponsePreflightOutcome { + response_preflight_input_failure(entries, Vec::new(), "response_input_unrepresentable") + } + + pub async fn preflight_http_response( + &self, + entries: &[ChainEntry], + input: HttpResponsePreflightInput, + ) -> miette::Result { + let described = self.describe_http_response_chain(entries).await?; + self.preflight_described_http_response(described, input) + .await + } + + /// Run preflight with a response-filtered chain that the caller already + /// described. This keeps response parsing and binding selection on one + /// snapshot without repeating remote capability discovery. + pub async fn preflight_described_http_response( + &self, + described: Vec, + input: HttpResponsePreflightInput, + ) -> miette::Result { + if described.is_empty() { + return Ok(empty_preflight_outcome(input.headers)); + } + if validate_preflight_input(&input).is_err() { + return Ok(response_preflight_input_failure( + &described, + input.headers, + "response_input_over_capacity", + )); + } + let session_admission = match self.try_reserve_middleware_session() { + MiddlewareSessionAdmission::Admitted(admission) => admission, + MiddlewareSessionAdmission::AtCapacity => { + return Ok(response_session_capacity_exhausted( + described, + input.headers, + )); + } + }; + let _work = self.reserve_middleware_work_admission().await?; + let original_restriction = body_restriction(&input); + let mut headers = input.headers.clone(); + let mut stages = Vec::new(); + let mut findings = Vec::new(); + let mut metadata = BTreeMap::new(); + let mut invocations = Vec::new(); + + for entry in described { + let Some(service) = entry.service.as_ref() else { + if let Some(reason) = + collect_preflight_failure(&entry, "binding_not_described", &mut invocations) + { + end_stages(&mut stages, MiddlewareSessionEndReason::MiddlewareFailure).await; + return Ok(failed_preflight_outcome( + headers, + reason, + findings, + metadata, + invocations, + )); + } + continue; + }; + let (sender, receiver) = mpsc::channel(STREAM_CHANNEL_CAPACITY); + let preflight = HttpResponsePreflight { + context: Some(input.context.clone()), + target: Some(input.target.clone()), + status_code: u32::from(input.status_code), + headers: headers.clone(), + middleware_name: entry.entry.implementation.clone(), + config: Some(entry.entry.config.clone()), + max_payload_bytes: entry.max_payload_bytes as u64, + permitted_body_modes: permitted_body_modes( + &input, + &entry, + original_restriction.as_deref(), + ), + }; + let timeout = entry.timeout; + let opened = tokio::time::timeout(timeout, async { + sender + .send(HttpResponseEvent { + event: Some(http_response_event::Event::Preflight(preflight)), + }) + .await + .map_err(|_| tonic::Status::unavailable("middleware request stream closed"))?; + let mut responses = service + .service + .open_http_response_pre_return(receiver) + .await?; + let response = responses.next().await.ok_or_else(|| { + tonic::Status::unavailable("middleware result stream closed") + })??; + Ok::<_, tonic::Status>((responses, response)) + }) + .await; + let (responses, response) = match opened { + Ok(Ok(opened)) => opened, + Ok(Err(error)) => { + let reason = if error.code() == tonic::Code::DeadlineExceeded { + "middleware_timeout".to_string() + } else { + service.diagnostic_policy.error_reason(&error) + }; + if let Some(reason) = + collect_preflight_failure(&entry, &reason, &mut invocations) + { + end_stages(&mut stages, MiddlewareSessionEndReason::MiddlewareFailure) + .await; + return Ok(failed_preflight_outcome( + headers, + reason, + findings, + metadata, + invocations, + )); + } + continue; + } + Err(_) => { + if let Some(reason) = + collect_preflight_failure(&entry, "middleware_timeout", &mut invocations) + { + end_stages(&mut stages, MiddlewareSessionEndReason::MiddlewareFailure) + .await; + return Ok(failed_preflight_outcome( + headers, + reason, + findings, + metadata, + invocations, + )); + } + continue; + } + }; + let mut current_stage = HttpResponseStage { + entry: entry.clone(), + transport: Some(HttpResponseStageTransport { sender, responses }), + mode: StageMode::HeadersOnly, + next_sequence: 1, + whole_body: Vec::new(), + }; + let Some(http_response_event_result::Result::PreflightResult(decision)) = + response.result + else { + if let Some(reason) = handle_opened_preflight_failure( + &entry, + &mut current_stage, + &mut stages, + "unexpected_response_result", + &mut invocations, + ) + .await + { + return Ok(failed_preflight_outcome( + headers, + reason, + findings, + metadata, + invocations, + )); + } + continue; + }; + if let Err(reason) = validate_diagnostics( + &decision.reason, + &decision.reason_code, + &decision.findings, + &decision.metadata, + ) { + if let Some(reason) = handle_opened_preflight_failure( + &entry, + &mut current_stage, + &mut stages, + reason, + &mut invocations, + ) + .await + { + return Ok(failed_preflight_outcome( + headers, + reason, + findings, + metadata, + invocations, + )); + } + continue; + } + let reason_code = + (!decision.reason_code.is_empty()).then(|| decision.reason_code.clone()); + let decision_findings = decision.findings; + let decision_metadata = decision.metadata; + match decision.action { + Some(http_response_preflight_result::Action::Skip(_)) => { + collect_preflight_diagnostics( + &entry, + decision_findings, + decision_metadata, + &mut findings, + &mut metadata, + ); + invocations.push(HttpResponseInvocation { + config_name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + outcome: HttpResponseInvocationOutcome::Skip, + sequence: None, + input_size: 0, + output_size: None, + failed: false, + stage_disabled: false, + reason_code, + failure_category: None, + }); + current_stage + .end(MiddlewareSessionEndReason::StageSkipped) + .await; + } + Some(http_response_preflight_result::Action::Inspect(inspect)) => { + let permitted_modes = + permitted_body_modes(&input, &entry, original_restriction.as_deref()); + let mode = match validate_inspect(&entry, &inspect, &permitted_modes) { + Ok(mode) => mode, + Err(reason) => { + if let Some(reason) = handle_opened_preflight_failure( + &entry, + &mut current_stage, + &mut stages, + &reason, + &mut invocations, + ) + .await + { + return Ok(failed_preflight_outcome( + headers, + reason, + findings, + metadata, + invocations, + )); + } + continue; + } + }; + let updated = match headers::apply( + headers::HeaderAuthority::Response, + &headers, + &input.connection_nominated_headers, + &inspect.header_mutations, + ) { + Ok(updated) => updated, + Err(error) => { + let reason = service + .diagnostic_policy + .header_mutation_error_reason(&error); + if let Some(reason) = handle_opened_preflight_failure( + &entry, + &mut current_stage, + &mut stages, + &reason, + &mut invocations, + ) + .await + { + return Ok(failed_preflight_outcome( + headers, + reason, + findings, + metadata, + invocations, + )); + } + continue; + } + }; + headers = updated; + if mode == StageMode::Stream { + strip_stale_integrity(&mut headers); + } + collect_preflight_diagnostics( + &entry, + decision_findings, + decision_metadata, + &mut findings, + &mut metadata, + ); + invocations.push(HttpResponseInvocation { + config_name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + outcome: match mode { + StageMode::HeadersOnly => HttpResponseInvocationOutcome::HeadersOnly, + StageMode::WholeBody => HttpResponseInvocationOutcome::WholeBody, + StageMode::Stream => HttpResponseInvocationOutcome::Stream, + }, + sequence: None, + input_size: 0, + output_size: None, + failed: false, + stage_disabled: false, + reason_code, + failure_category: None, + }); + current_stage.mode = mode; + if mode == StageMode::HeadersOnly { + current_stage.end(MiddlewareSessionEndReason::Normal).await; + } else { + stages.push(current_stage); + } + } + Some(http_response_preflight_result::Action::BlockDelivery(_)) => { + collect_preflight_diagnostics( + &entry, + decision_findings, + decision_metadata, + &mut findings, + &mut metadata, + ); + invocations.push(HttpResponseInvocation { + config_name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + outcome: HttpResponseInvocationOutcome::BlockDelivery, + sequence: None, + input_size: 0, + output_size: None, + failed: false, + stage_disabled: false, + reason_code: reason_code.clone(), + failure_category: None, + }); + stages.push(current_stage); + end_stages(&mut stages, MiddlewareSessionEndReason::MiddlewareDenial).await; + return Ok(blocked_preflight_outcome( + headers, + crate::MiddlewareDenial { + config_name: entry.entry.name.clone(), + reason_code, + }, + findings, + metadata, + invocations, + )); + } + None => { + if let Some(reason) = handle_opened_preflight_failure( + &entry, + &mut current_stage, + &mut stages, + "invalid_preflight_decision", + &mut invocations, + ) + .await + { + return Ok(failed_preflight_outcome( + headers, + reason, + findings, + metadata, + invocations, + )); + } + } + } + } + + if stages.is_empty() { + drop(session_admission); + return Ok(HttpResponsePreflightOutcome { + allowed: true, + reason: String::new(), + denial: None, + headers, + session: None, + findings, + metadata, + invocations, + session_capacity_exhausted: false, + }); + } + let defer_output_until_finish = stages + .iter() + .any(|stage| stage.is_active() && stage.mode == StageMode::WholeBody); + Ok(HttpResponsePreflightOutcome { + allowed: true, + reason: String::new(), + denial: None, + headers, + session: Some(HttpResponseSession { + runner: self.clone(), + stages, + findings: Vec::new(), + metadata: BTreeMap::new(), + invocations: Vec::new(), + session_admission: Some(session_admission), + body_transformed: false, + retained_body_bytes: 0, + defer_output_until_finish, + deferred_output: Vec::new(), + connection_nominated_headers: input.connection_nominated_headers, + whole_body_deadline: None, + }), + findings, + metadata, + invocations, + session_capacity_exhausted: false, + }) + } +} diff --git a/crates/openshell-supervisor-middleware/src/response/validation.rs b/crates/openshell-supervisor-middleware/src/response/validation.rs new file mode 100644 index 0000000000..03febd4479 --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/response/validation.rs @@ -0,0 +1,328 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! HTTP response middleware protocol and payload validation. + +use super::*; + +pub(super) enum BodyAction { + PassThrough, + Transform(Vec), + BlockDelivery, + SkipRemaining(CurrentBodyAction), +} + +pub(super) enum CurrentBodyAction { + PassThrough, + Transform(Vec), +} + +pub(super) struct BodyDecision { + pub(super) action: BodyAction, + pub(super) reason_code: String, + pub(super) findings: Vec, + pub(super) metadata: std::collections::HashMap, +} + +pub(super) struct TrailersDecision { + pub(super) headers: Vec, + pub(super) reason_code: String, + pub(super) findings: Vec, + pub(super) metadata: std::collections::HashMap, +} + +pub(super) fn validate_trailers_result( + result: HttpResponseEventResult, + trailers: &[HttpHeader], + entry: &DescribedChainEntry, + connection_nominated_headers: &[String], +) -> Result { + let Some(http_response_event_result::Result::TrailersResult(result)) = result.result else { + return Err("unexpected_response_result".into()); + }; + validate_diagnostics( + &result.reason, + &result.reason_code, + &result.findings, + &result.metadata, + ) + .map_err(str::to_string)?; + if result.trailer_mutations.len() > headers::MAX_HEADER_MUTATIONS { + return Err("header_mutation_count_over_capacity".into()); + } + let encoded_mutations = result + .trailer_mutations + .iter() + .fold(0usize, |total, mutation| { + total.saturating_add(mutation.encoded_len()) + }); + if encoded_mutations > MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES { + return Err("header_mutation_bytes_over_capacity".into()); + } + let headers = headers::apply( + headers::HeaderAuthority::ResponseTrailers, + trailers, + connection_nominated_headers, + &result.trailer_mutations, + ) + .map_err(|error| { + entry.service.as_ref().map_or_else( + || error.to_string(), + |service| { + service + .diagnostic_policy + .header_mutation_error_reason(&error) + }, + ) + })?; + Ok(TrailersDecision { + headers, + reason_code: result.reason_code, + findings: result.findings, + metadata: result.metadata, + }) +} + +pub(super) fn encoded_header_bytes(headers: &[HttpHeader]) -> usize { + headers.iter().fold(0usize, |total, header| { + total.saturating_add(header.encoded_len()) + }) +} + +pub(super) fn validate_body_result( + result: HttpResponseEventResult, + sequence: u64, + max_payload_bytes: usize, +) -> Result { + let Some(http_response_event_result::Result::BodyResult(body)) = result.result else { + return Err("unexpected_response_result"); + }; + if body.sequence != sequence { + return Err("response_body_sequence_mismatch"); + } + validate_diagnostics( + &body.reason, + &body.reason_code, + &body.findings, + &body.metadata, + )?; + let action = match body.action { + Some(http_response_body_result::Action::PassThrough(HttpResponseBodyPassThrough {})) => { + BodyAction::PassThrough + } + Some(http_response_body_result::Action::Transform(transform)) => BodyAction::Transform( + validate_replacement(transform.replacement, max_payload_bytes)?, + ), + Some(http_response_body_result::Action::BlockDelivery(_)) => BodyAction::BlockDelivery, + Some(http_response_body_result::Action::SkipRemaining(skip)) => { + let current = match skip.current { + Some(http_response_body_skip_remaining::Current::PassThrough( + HttpResponseBodyPassThrough {}, + )) => CurrentBodyAction::PassThrough, + Some(http_response_body_skip_remaining::Current::Transform(transform)) => { + CurrentBodyAction::Transform(validate_replacement( + transform.replacement, + max_payload_bytes, + )?) + } + None => return Err("invalid_response_body_skip_remaining_action"), + }; + BodyAction::SkipRemaining(current) + } + None => return Err("invalid_response_body_decision"), + }; + Ok(BodyDecision { + action, + reason_code: body.reason_code, + findings: body.findings, + metadata: body.metadata, + }) +} + +fn validate_replacement( + replacement: Option, + max_payload_bytes: usize, +) -> Result, &'static str> { + let Some(http_response_body_transform::Replacement::Data(replacement)) = replacement else { + return Err("response_body_replacement_missing"); + }; + if replacement.len() > max_payload_bytes { + return Err("response_body_replacement_over_capacity"); + } + Ok(replacement) +} + +pub(super) fn validate_inspect( + entry: &DescribedChainEntry, + inspect: &openshell_core::proto::HttpResponsePreflightInspect, + permitted_modes: &[i32], +) -> Result { + let mode = match HttpResponseBodyMode::try_from(inspect.body_mode) { + Ok(HttpResponseBodyMode::HeadersOnly) => StageMode::HeadersOnly, + Ok(HttpResponseBodyMode::WholeBodyBytes) => StageMode::WholeBody, + Ok(HttpResponseBodyMode::StreamBytes) => StageMode::Stream, + Ok(HttpResponseBodyMode::Unspecified) | Err(_) => { + return Err("invalid_response_body_mode".into()); + } + }; + if !permitted_modes.contains(&inspect.body_mode) { + return Err("response_body_mode_not_permitted".into()); + } + if inspect.header_mutations.len() > headers::MAX_HEADER_MUTATIONS { + return Err("header_mutation_count_over_capacity".into()); + } + let encoded_mutations = inspect + .header_mutations + .iter() + .fold(0usize, |total, mutation| { + total.saturating_add(mutation.encoded_len()) + }); + if encoded_mutations > MAX_MIDDLEWARE_HEADER_MUTATION_WIRE_BYTES { + return Err("header_mutation_bytes_over_capacity".into()); + } + if entry.max_payload_bytes == 0 && mode != StageMode::HeadersOnly { + return Err("response_payload_limit_invalid".into()); + } + Ok(mode) +} + +pub(super) fn validate_preflight_input(input: &HttpResponsePreflightInput) -> miette::Result<()> { + if input.context.encoded_len() > MAX_MIDDLEWARE_CONTEXT_BYTES { + return Err(miette::miette!("response context exceeds platform limit")); + } + if input.target.encoded_len() > MAX_MIDDLEWARE_TARGET_BYTES { + return Err(miette::miette!("response target exceeds platform limit")); + } + if input.headers.len() > MAX_MIDDLEWARE_HEADERS { + return Err(miette::miette!( + "response header count exceeds platform limit" + )); + } + if input.headers.iter().fold(0usize, |total, header| { + total.saturating_add(header.encoded_len()) + }) > MAX_MIDDLEWARE_HEADER_BYTES + { + return Err(miette::miette!("response headers exceed platform limit")); + } + Ok(()) +} + +pub(super) fn validate_diagnostics( + reason: &str, + reason_code: &str, + findings: &[Finding], + metadata: &std::collections::HashMap, +) -> Result<(), &'static str> { + if reason.len() > MAX_MIDDLEWARE_REASON_BYTES { + return Err("response_reason_over_capacity"); + } + if !reason_code.is_empty() + && (reason_code.len() > MAX_MIDDLEWARE_REASON_CODE_BYTES + || !is_stable_reason_code(reason_code)) + { + return Err("response_reason_code_invalid"); + } + if findings.len() > MAX_MIDDLEWARE_FINDINGS_PER_STAGE { + return Err("response_findings_over_capacity"); + } + if findings + .iter() + .any(|finding| finding.encoded_len() > MAX_MIDDLEWARE_FINDING_BYTES) + { + return Err("response_finding_over_capacity"); + } + if metadata.len() > MAX_MIDDLEWARE_METADATA_ENTRIES { + return Err("response_metadata_count_over_capacity"); + } + if metadata.iter().fold(0usize, |total, (key, value)| { + total.saturating_add(key.len()).saturating_add(value.len()) + }) > MAX_MIDDLEWARE_METADATA_BYTES + { + return Err("response_metadata_bytes_over_capacity"); + } + Ok(()) +} + +pub(super) fn body_restriction(input: &HttpResponsePreflightInput) -> Option { + if input.target.method.eq_ignore_ascii_case("HEAD") + || input.status_code == 204 + || input.status_code == 304 + { + return Some("bodyless_response".into()); + } + if input.status_code == 206 + || input + .headers + .iter() + .any(|header| header.name.eq_ignore_ascii_case("content-range")) + || input.headers.iter().any(|header| { + header.name.eq_ignore_ascii_case("content-type") + && header + .value + .split(';') + .next() + .is_some_and(|value| value.trim().eq_ignore_ascii_case("multipart/byteranges")) + }) + { + return Some("unsupported_partial_response".into()); + } + if input.headers.iter().any(|header| { + header.name.eq_ignore_ascii_case("cache-control") + && header.value.split(',').any(|directive| { + directive + .split('=') + .next() + .is_some_and(|name| name.trim().eq_ignore_ascii_case("no-transform")) + }) + }) { + return Some("response_no_transform".into()); + } + if input.headers.iter().any(|header| { + header.name.eq_ignore_ascii_case("content-encoding") + && header + .value + .split(',') + .any(|coding| !coding.trim().eq_ignore_ascii_case("identity")) + }) { + return Some("unsupported_content_encoding".into()); + } + None +} + +pub(super) fn permitted_body_modes( + input: &HttpResponsePreflightInput, + entry: &DescribedChainEntry, + body_restriction: Option<&str>, +) -> Vec { + let mut modes = vec![HttpResponseBodyMode::HeadersOnly as i32]; + if body_restriction.is_some() { + return modes; + } + if input + .declared_body_length + .is_none_or(|length| length <= entry.max_payload_bytes as u64) + && !is_open_ended_response(input) + { + modes.push(HttpResponseBodyMode::WholeBodyBytes as i32); + } + if entry.max_payload_bytes > 0 { + modes.push(HttpResponseBodyMode::StreamBytes as i32); + } + modes +} + +fn is_open_ended_response(input: &HttpResponsePreflightInput) -> bool { + input.headers.iter().any(|header| { + header.name.eq_ignore_ascii_case("content-type") + && matches!( + header.value.split(';').next().map(str::trim), + Some(value) + if value.eq_ignore_ascii_case("text/event-stream") + || value.eq_ignore_ascii_case("multipart/x-mixed-replace") + ) + }) +} + +pub(super) fn strip_stale_integrity(headers: &mut Vec) { + headers.retain(|header| !is_stale_http_response_integrity_header(&header.name)); +} diff --git a/crates/openshell-supervisor-network/src/l7/middleware.rs b/crates/openshell-supervisor-network/src/l7/middleware.rs index f2df288019..c469ab5233 100644 --- a/crates/openshell-supervisor-network/src/l7/middleware.rs +++ b/crates/openshell-supervisor-network/src/l7/middleware.rs @@ -26,6 +26,89 @@ pub enum MiddlewareApplyResult { AdmissionExhausted, } +/// One destination-selected middleware chain shared by an HTTP request and +/// its matching response. The request and response phases filter bindings +/// independently, so the full chain must remain available until relay ends. +#[derive(Clone)] +pub struct HttpMiddlewareExchange { + request_id: String, + chain: Vec, + runner: openshell_supervisor_middleware::ChainRunner, + generation_guard: PolicyGenerationGuard, +} + +impl HttpMiddlewareExchange { + pub fn new( + request_id: String, + chain: Vec, + runner: openshell_supervisor_middleware::ChainRunner, + generation_guard: PolicyGenerationGuard, + ) -> Self { + Self { + request_id, + chain, + runner, + generation_guard, + } + } + + pub async fn apply_request( + &self, + request: crate::l7::provider::L7Request, + client: &mut C, + ctx: &L7EvalContext, + scheme: &str, + transformed_body_policy: openshell_supervisor_middleware::TransformedBodyPolicy<'_>, + ) -> Result + where + C: AsyncRead + AsyncWrite + Unpin + Send, + { + apply_middleware_chain_for_scheme_with_request_id( + request, + client, + ctx, + scheme, + self.chain.clone(), + &self.runner, + &self.generation_guard, + transformed_body_policy, + &self.request_id, + ) + .await + } + + pub fn response_relay<'a>( + &'a self, + request: &crate::l7::provider::L7Request, + ctx: &'a L7EvalContext, + scheme: &str, + ) -> crate::l7::rest::HttpResponseMiddlewareRelay<'a> { + let sandbox = openshell_ocsf::ctx::ctx(); + crate::l7::rest::HttpResponseMiddlewareRelay { + chain: &self.chain, + runner: &self.runner, + request_context: openshell_core::proto::RequestContext { + request_id: self.request_id.clone(), + sandbox_id: sandbox.sandbox_id.clone(), + sandbox_name: sandbox.sandbox_name.clone(), + workspace: ctx.workspace.clone(), + originating_process: None, + }, + target: openshell_core::proto::HttpRequestTarget { + scheme: scheme.to_string(), + host: ctx.host.clone(), + port: u32::from(ctx.port), + method: request.action.clone(), + path: request.target.clone(), + query: super::relay::policy_safe_response_query(&request.query_params), + }, + policy_name: &ctx.policy_name, + generation_guard: Some(&self.generation_guard), + whole_body_timeout: super::rest::DEFAULT_HTTP_RESPONSE_WHOLE_BODY_TIMEOUT, + } + } +} + /// How traffic a middleware chain can never inspect (h2c, non-HTTP TCP, /// protocols without an L7 relay) must be handled for a matching chain. /// @@ -197,7 +280,7 @@ pub(super) fn websocket_message_finding_events( middleware_finding_events(&outcome.findings) } -fn middleware_finding_events( +pub(super) fn middleware_finding_events( findings: &[openshell_supervisor_middleware::NamespacedFinding], ) -> Vec { findings @@ -423,7 +506,8 @@ pub(super) fn middleware_chain_body_limit( .max() } -pub async fn apply_middleware_chain( +#[allow(clippy::too_many_arguments)] +pub async fn apply_middleware_chain_with_request_id( req: crate::l7::provider::L7Request, client: &mut C, ctx: &L7EvalContext, @@ -431,8 +515,9 @@ pub async fn apply_middleware_chain( runner: &openshell_supervisor_middleware::ChainRunner, generation_guard: &PolicyGenerationGuard, transformed_body_policy: openshell_supervisor_middleware::TransformedBodyPolicy<'_>, + request_id: &str, ) -> Result { - apply_middleware_chain_for_scheme( + apply_middleware_chain_for_scheme_with_request_id( req, client, ctx, @@ -441,12 +526,15 @@ pub async fn apply_middleware_chain( runner, generation_guard, transformed_body_policy, + request_id, ) .await } #[allow(clippy::too_many_arguments)] -pub async fn apply_middleware_chain_for_scheme( +pub async fn apply_middleware_chain_for_scheme_with_request_id< + C: AsyncRead + AsyncWrite + Unpin + Send, +>( req: crate::l7::provider::L7Request, client: &mut C, ctx: &L7EvalContext, @@ -455,6 +543,7 @@ pub async fn apply_middleware_chain_for_scheme, + request_id: &str, ) -> Result { if chain.is_empty() { return Ok(MiddlewareApplyResult::Allowed(req)); @@ -479,7 +568,7 @@ pub async fn apply_middleware_chain_for_scheme, query: String, body: Vec, + request_id: &str, ) -> openshell_supervisor_middleware::HttpRequestInput { openshell_supervisor_middleware::HttpRequestInput { - request_id: uuid::Uuid::new_v4().to_string(), + request_id: request_id.to_string(), sandbox_id: sandbox.sandbox_id.clone(), sandbox_name: sandbox.sandbox_name.clone(), workspace: ctx.workspace.clone(), @@ -637,6 +729,32 @@ pub(super) fn middleware_request_input( } } +#[cfg(test)] +#[allow(clippy::too_many_arguments)] +pub(super) fn middleware_request_input( + sandbox: &openshell_ocsf::EventContext, + scheme: &str, + req: &crate::l7::provider::L7Request, + ctx: &L7EvalContext, + headers: Vec<(String, String)>, + connection_nominated_headers: Vec, + query: String, + body: Vec, +) -> openshell_supervisor_middleware::HttpRequestInput { + let request_id = uuid::Uuid::new_v4().to_string(); + middleware_request_input_with_id( + sandbox, + scheme, + req, + ctx, + headers, + connection_nominated_headers, + query, + body, + &request_id, + ) +} + pub(super) fn raw_query_from_request_headers(headers: &[u8]) -> Result { let header_str = std::str::from_utf8(headers).map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; @@ -1116,7 +1234,7 @@ mod tests { body_length: crate::l7::provider::BodyLength::None, }; - let input = super::middleware_request_input( + let input = super::middleware_request_input_with_id( &sandbox, "https", &req, @@ -1125,11 +1243,13 @@ mod tests { Vec::new(), String::new(), Vec::new(), + "exchange-123", ); assert_eq!(input.sandbox_name, "nightly-build"); assert_eq!(input.sandbox_id, "sbx-123"); assert_eq!(input.workspace, "wrks-default"); + assert_eq!(input.request_id, "exchange-123"); } #[tokio::test] diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index 9b97b4605e..2842562d90 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -8,7 +8,7 @@ //! and either forwards or denies the request. use crate::l7::middleware::{ - MiddlewareApplyResult, UninspectableTrafficGate, apply_middleware_chain, + MiddlewareApplyResult, UninspectableTrafficGate, apply_middleware_chain_with_request_id, emit_middleware_uninspectable, middleware_network_input, uninspectable_traffic_gate, }; #[cfg(test)] @@ -446,13 +446,20 @@ async fn relay_http_request_with_credential_rejection( upstream: &mut U, options: crate::l7::rest::RelayRequestOptions<'_>, ctx: &L7EvalContext, + response_middleware: Option>, ) -> Result> where C: AsyncRead + AsyncWrite + Unpin, U: AsyncRead + AsyncWrite + Unpin, { relay_http_request_with_credential_rejection_observed( - request, client, upstream, options, ctx, None, + request, + client, + upstream, + options, + ctx, + response_middleware, + None, ) .await } @@ -463,14 +470,22 @@ async fn relay_http_request_with_credential_rejection_observed( upstream: &mut U, options: crate::l7::rest::RelayRequestOptions<'_>, ctx: &L7EvalContext, + response_middleware: Option>, observer: Option<&EndpointObserver>, ) -> Result> where C: AsyncRead + AsyncWrite + Unpin, U: AsyncRead + AsyncWrite + Unpin, { - match crate::l7::rest::relay_http_request_with_options_guarded_observed( - request, client, upstream, options, observer, + match Box::pin( + crate::l7::rest::relay_http_request_with_response_middleware_guarded_observed( + request, + client, + upstream, + options, + response_middleware, + observer, + ), ) .await { @@ -508,6 +523,90 @@ where } } +pub(crate) fn http_response_middleware_relay<'a>( + request: &crate::l7::provider::L7Request, + ctx: &'a L7EvalContext, + scheme: &str, + request_id: &str, + chain: &'a [openshell_supervisor_middleware::ChainEntry], + runner: &'a openshell_supervisor_middleware::ChainRunner, + generation_guard: Option<&'a PolicyGenerationGuard>, +) -> crate::l7::rest::HttpResponseMiddlewareRelay<'a> { + let sandbox = openshell_ocsf::ctx::ctx(); + crate::l7::rest::HttpResponseMiddlewareRelay { + chain, + runner, + request_context: openshell_core::proto::RequestContext { + request_id: request_id.to_string(), + sandbox_id: sandbox.sandbox_id.clone(), + sandbox_name: sandbox.sandbox_name.clone(), + workspace: ctx.workspace.clone(), + originating_process: None, + }, + target: openshell_core::proto::HttpRequestTarget { + scheme: scheme.to_string(), + host: ctx.host.clone(), + port: u32::from(ctx.port), + method: request.action.clone(), + path: request.target.clone(), + query: policy_safe_response_query(&request.query_params), + }, + policy_name: &ctx.policy_name, + generation_guard, + whole_body_timeout: super::rest::DEFAULT_HTTP_RESPONSE_WHOLE_BODY_TIMEOUT, + } +} + +pub(super) fn policy_safe_response_query( + query_params: &std::collections::HashMap>, +) -> String { + let mut parameters: Vec<_> = query_params.iter().collect(); + parameters.sort_by_key(|(name, _)| *name); + let mut output = String::new(); + for (name, values) in parameters { + let empty_value = String::new(); + let values = if values.is_empty() { + std::slice::from_ref(&empty_value) + } else { + values.as_slice() + }; + for value in values { + if !output.is_empty() { + output.push('&'); + } + let name = if secrets::contains_reserved_credential_marker(name) { + "[REDACTED]" + } else { + name + }; + let value = if secrets::contains_reserved_credential_marker(value) { + "[REDACTED]" + } else { + value + }; + push_form_component(&mut output, name); + output.push('='); + push_form_component(&mut output, value); + } + } + output +} + +fn push_form_component(output: &mut String, value: &str) { + const HEX: &[u8; 16] = b"0123456789ABCDEF"; + for byte in value.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + output.push(char::from(byte)); + } else if byte == b' ' { + output.push('+'); + } else { + output.push('%'); + output.push(char::from(HEX[usize::from(byte >> 4)])); + output.push(char::from(HEX[usize::from(byte & 0x0f)])); + } + } +} + #[derive(Default)] pub(crate) struct UpgradeRelayOptions<'a> { pub(crate) websocket_request: bool, @@ -967,13 +1066,15 @@ where if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + let response_chain = chain.clone(); + let request_id = uuid::Uuid::new_v4().to_string(); let websocket_chain = websocket_request.then(|| chain.clone()); // Route selection resolved `config` per request, so re-check the // body against that protocol's policy after every transforming // stage (a no-op for REST and websocket, whose policy inputs the // chain cannot mutate). let validate = transformed_body_validator(config, &engine, ctx, &request_info); - let middleware_result = apply_middleware_chain( + let middleware_result = apply_middleware_chain_with_request_id( req, client, ctx, @@ -981,6 +1082,7 @@ where engine.middleware_runner(), engine.generation_guard(), openshell_supervisor_middleware::TransformedBodyPolicy::Reevaluate(&validate), + &request_id, ) .await; let req = match middleware_result? { @@ -1105,6 +1207,15 @@ where port: ctx.port, }, ctx, + Some(http_response_middleware_relay( + &req, + ctx, + "https", + &request_id, + &response_chain, + engine.middleware_runner(), + Some(engine.generation_guard()), + )), observer.as_ref(), ) .await; @@ -1722,11 +1833,13 @@ where if allowed || config.enforcement == EnforcementMode::Audit { let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + let response_chain = chain.clone(); + let request_id = uuid::Uuid::new_v4().to_string(); let websocket_chain = websocket_request.then(|| chain.clone()); // REST and websocket-upgrade policy evaluates only the method, // path, and query, which a middleware result cannot mutate, so no // per-stage body re-check is needed. - let middleware_result = apply_middleware_chain( + let middleware_result = apply_middleware_chain_with_request_id( req, client, ctx, @@ -1734,6 +1847,7 @@ where engine.middleware_runner(), engine.generation_guard(), openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, + &request_id, ) .await; let req = match middleware_result? { @@ -1849,6 +1963,15 @@ where port: ctx.port, }, ctx, + Some(http_response_middleware_relay( + &req_with_auth, + ctx, + "https", + &request_id, + &response_chain, + engine.middleware_runner(), + Some(engine.generation_guard()), + )), ) .await; let outcome_result = match outcome_result { @@ -2166,12 +2289,14 @@ where if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + let response_chain = chain.clone(); + let request_id = uuid::Uuid::new_v4().to_string(); // Policy admitted the original body above; re-check the body // against the same body-aware policy after every transforming // stage so a middleware cannot smuggle a denied operation to the // upstream or the next stage. let validate = transformed_body_validator(config, engine, ctx, &request_info); - let req = match apply_middleware_chain( + let req = match apply_middleware_chain_with_request_id( req, client, ctx, @@ -2179,6 +2304,7 @@ where engine.middleware_runner(), engine.generation_guard(), openshell_supervisor_middleware::TransformedBodyPolicy::Reevaluate(&validate), + &request_id, ) .await? { @@ -2263,6 +2389,15 @@ where ..Default::default() }, ctx, + Some(http_response_middleware_relay( + &req, + ctx, + "https", + &request_id, + &response_chain, + engine.middleware_runner(), + Some(engine.generation_guard()), + )), observer.as_ref(), ) .await? @@ -2436,12 +2571,14 @@ where if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + let response_chain = chain.clone(); + let request_id = uuid::Uuid::new_v4().to_string(); // Policy admitted the original body above; re-check the body // against the same body-aware policy after every transforming // stage so a middleware cannot smuggle a denied operation to the // upstream or the next stage. let validate = transformed_body_validator(config, engine, ctx, &request_info); - let req = match apply_middleware_chain( + let req = match apply_middleware_chain_with_request_id( req, client, ctx, @@ -2449,6 +2586,7 @@ where engine.middleware_runner(), engine.generation_guard(), openshell_supervisor_middleware::TransformedBodyPolicy::Reevaluate(&validate), + &request_id, ) .await? { @@ -2503,6 +2641,15 @@ where ..Default::default() }, ctx, + Some(http_response_middleware_relay( + &req, + ctx, + "https", + &request_id, + &response_chain, + engine.middleware_runner(), + Some(engine.generation_guard()), + )), ) .await? else { @@ -3055,6 +3202,8 @@ where ocsf_emit!(event); } + let request_id = uuid::Uuid::new_v4().to_string(); + let mut response_selection = None; let req = if let Some(engine) = middleware_engine { let input = middleware_network_input(ctx); let (chain, generation) = engine.query_middleware_chain_with_generation(&input)?; @@ -3062,19 +3211,24 @@ where return Ok(()); } let runner = engine.middleware_runner()?; + let exchange = crate::l7::middleware::HttpMiddlewareExchange::new( + request_id.clone(), + chain, + runner, + generation_guard.clone(), + ); // The passthrough path enforces no L7 policy, so there is no // body-aware decision to re-check after a transformation. - match apply_middleware_chain( - req, - client, - ctx, - chain, - &runner, - generation_guard, - openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, - ) - .await? - { + let result = exchange + .apply_request( + req, + client, + ctx, + "http", + openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, + ) + .await?; + let request = match result { MiddlewareApplyResult::Allowed(request) => request, MiddlewareApplyResult::Denied { denial, .. } => { let denied_request = crate::l7::provider::L7Request { @@ -3111,7 +3265,9 @@ where .await?; return Ok(()); } - } + }; + response_selection = Some(exchange); + request } else { req }; @@ -3133,6 +3289,9 @@ where let scoped_ctx = scoped_context_for_request(ctx, &req_with_auth); let ctx = scoped_ctx.as_ref().unwrap_or(ctx); let resolver = ctx.secret_resolver.as_deref(); + let response_middleware = response_selection + .as_ref() + .map(|exchange| exchange.response_relay(&req_with_auth, ctx, "http")); // Forward request with credential rewriting and relay the response. // relay_http_request_with_resolver handles both directions: it sends @@ -3148,6 +3307,7 @@ where ..Default::default() }, ctx, + response_middleware, ) .await? else { @@ -3219,6 +3379,7 @@ mod tests { ..Default::default() }, &L7EvalContext::default(), + None, ) .await .unwrap(); @@ -3306,6 +3467,7 @@ mod tests { ..Default::default() }, &L7EvalContext::default(), + None, Some(&observer), ) .await; @@ -3662,6 +3824,7 @@ mod tests { ..options }, &ctx, + None, ) .await .expect("typed credential denial"); @@ -6591,7 +6754,7 @@ network_policies: let (mut app, mut relay_client) = tokio::io::duplex(8192); app.write_all(&body).await.unwrap(); - let result = crate::l7::middleware::apply_middleware_chain_for_scheme( + let result = crate::l7::middleware::apply_middleware_chain_for_scheme_with_request_id( req, &mut relay_client, &ctx, @@ -6600,6 +6763,7 @@ network_policies: &runner, tunnel_engine.generation_guard(), openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, + "test-request-id", ) .await .expect("apply middleware chain"); @@ -6727,6 +6891,50 @@ network_policies: assert_eq!(input.scheme, "http"); } + #[test] + fn response_middleware_context_reuses_exchange_request_id() { + let req = crate::l7::provider::L7Request { + action: "GET".into(), + target: "/v1/data".into(), + query_params: std::collections::HashMap::from([ + ("cursor".into(), vec!["next page".into()]), + ( + "token".into(), + vec!["openshell:resolve:env:API_TOKEN".into()], + ), + ]), + raw_header: b"GET /v1/data?cursor=next+page&token=sk-live-secret HTTP/1.1\r\nHost: api.example.test\r\n\r\n".to_vec(), + body_length: crate::l7::provider::BodyLength::None, + }; + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + workspace: "workspace-1".into(), + policy_name: "api".into(), + ..Default::default() + }; + let runner = openshell_supervisor_middleware::ChainRunner::default(); + let chain = Vec::new(); + let response = http_response_middleware_relay( + &req, + &ctx, + "https", + "exchange-123", + &chain, + &runner, + None, + ); + + assert_eq!(response.request_context.request_id, "exchange-123"); + assert_eq!( + response.target.query, + "cursor=next+page&token=%5BREDACTED%5D" + ); + assert!(!response.target.query.contains("sk-live-secret")); + assert!(!response.target.query.contains("API_TOKEN")); + assert_eq!(response.target.scheme, "https"); + } + #[test] fn middleware_ocsf_events_are_audit_safe() { use openshell_supervisor_middleware::{ diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index bf5c99e140..4c65c983e6 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -7,6 +7,19 @@ //! policy, and relays allowed requests to upstream. Handles Content-Length //! and chunked transfer encoding for body framing. +mod http_response; + +pub(crate) use http_response::{ + DEFAULT_HTTP_RESPONSE_WHOLE_BODY_TIMEOUT, HttpResponseMiddlewareRelay, +}; +use http_response::{RelayResponseOptions, relay_response}; +#[cfg(test)] +use http_response::{ + http_response_middleware_fail_open_finding_event, http_response_middleware_invocation_events, + parse_connection_close, parse_status_code, response_is_event_stream, + strip_response_integrity_headers, +}; + use crate::l7::EndpointObserver; use crate::l7::provider::{BodyLength, L7Provider, L7Request, RelayOutcome}; use crate::opa::PolicyGenerationGuard; @@ -14,7 +27,10 @@ use aws_sigv4::http_request::SignableBody; use base64::Engine as _; use miette::{IntoDiagnostic, Result, miette}; use openshell_core::endpoint_status::EndpointResult; -use openshell_core::proto::{ExistingHeaderAction, HeaderMutation, header_mutation}; +use openshell_core::proto::{ + ExistingHeaderAction, HeaderMutation, HttpHeader, HttpRequestTarget, RequestContext, + header_mutation, +}; use openshell_core::secrets::{ SecretResolver, contains_reserved_credential_marker, contains_reserved_credential_marker_bytes, rewrite_http_header_block, @@ -22,7 +38,7 @@ use openshell_core::secrets::{ use openshell_ocsf::ctx::ctx as ocsf_ctx; use sha1::{Digest, Sha1}; use std::collections::{HashMap, HashSet}; -use std::fmt; +use std::fmt::{self, Write as _}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; use tracing::debug; @@ -51,6 +67,7 @@ async fn max_middleware_body_bytes() -> usize { chain[0].max_payload_bytes() } const RELAY_BUF_SIZE: usize = 8192; +const RESPONSE_UNIT_COALESCE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(2); const HTTP_METHOD_PREFIXES: &[&[u8]] = &[ b"GET ", b"HEAD ", @@ -831,37 +848,26 @@ where C: AsyncRead + AsyncWrite + Unpin, U: AsyncRead + AsyncWrite + Unpin, { - relay_http_request_with_options_guarded_observed(req, client, upstream, options, None).await -} - -/// Relay one request while attributing only terminal, privacy-safe MCP outcomes. -pub(crate) async fn relay_http_request_with_options_guarded_observed( - req: &L7Request, - client: &mut C, - upstream: &mut U, - options: RelayRequestOptions<'_>, - observer: Option<&EndpointObserver>, -) -> Result -where - C: AsyncRead + AsyncWrite + Unpin, - U: AsyncRead + AsyncWrite + Unpin, -{ - let mut upstream = ObservedUpstream { upstream, observer }; - relay_http_request_with_options_guarded_inner(req, client, &mut upstream, options, observer) - .await + relay_http_request_with_response_middleware_guarded_observed( + req, client, upstream, options, None, None, + ) + .await } -async fn relay_http_request_with_options_guarded_inner( +pub(crate) async fn relay_http_request_with_response_middleware_guarded_observed( req: &L7Request, client: &mut C, upstream: &mut U, options: RelayRequestOptions<'_>, + response_middleware: Option>, observer: Option<&EndpointObserver>, ) -> Result where C: AsyncRead + AsyncWrite + Unpin, U: AsyncRead + AsyncWrite + Unpin, { + let mut observed_upstream = ObservedUpstream { upstream, observer }; + let upstream = &mut observed_upstream; ensure_credential_generation_current(options)?; let header_end = req .raw_header @@ -1213,6 +1219,7 @@ where client_requested_upgrade, observer, }, + response_middleware, ) .await?; @@ -3233,314 +3240,6 @@ fn find_crlf(buf: &[u8], start: usize) -> Option { .map(|offset| start + offset) } -#[derive(Clone)] -struct RelayResponseOptions<'a> { - websocket_extensions: WebSocketExtensionMode, - client_requested_upgrade: bool, - websocket: Option, - observer: Option<&'a EndpointObserver>, -} - -impl Default for RelayResponseOptions<'_> { - fn default() -> Self { - Self { - websocket_extensions: WebSocketExtensionMode::Preserve, - client_requested_upgrade: true, - websocket: None, - observer: None, - } - } -} - -async fn relay_response( - request_method: &str, - upstream: &mut U, - client: &mut C, - options: RelayResponseOptions<'_>, -) -> Result -where - U: AsyncRead + Unpin, - C: AsyncWrite + Unpin, -{ - let started_at = std::time::Instant::now(); - let mut buf = Vec::with_capacity(4096); - let mut tmp = [0u8; 1024]; - - let mut informational_header_bytes = 0; - let header_end = loop { - let header_end = buf - .windows(4) - .position(|w| w == b"\r\n\r\n") - .map(|end| end + 4); - let remaining_header_bytes = MAX_HEADER_BYTES - informational_header_bytes; - if header_end.is_some_and(|end| end > remaining_header_bytes) - || (header_end.is_none() && buf.len() >= remaining_header_bytes) - { - if let Some(observer) = options.observer.as_ref() { - observer.observe(EndpointResult::TransportFailed); - } - return Err(miette!("HTTP response headers exceed limit")); - } - - if let Some(header_end) = header_end { - let header_str = String::from_utf8_lossy(&buf[..header_end]); - if matches!( - parse_observed_http_status_code(&header_str), - Some(100 | 102..=199) - ) { - // Informational responses keep this exchange and its observation - // pending. Preserve any coalesced final response, and charge every - // header block to one budget so repeated 1xx frames stay bounded. - informational_header_bytes += header_end; - client - .write_all(&buf[..header_end]) - .await - .into_diagnostic()?; - client.flush().await.into_diagnostic()?; - buf.drain(..header_end); - continue; - } - // A 101 response transfers ownership to the upgrade handler below. - break header_end; - } - - let n = upstream.read(&mut tmp).await.into_diagnostic()?; - if n == 0 { - if let Some(observer) = options.observer.as_ref() { - observer.observe(EndpointResult::TransportFailed); - } - // Upstream closed — forward whatever we have - if !buf.is_empty() { - client.write_all(&buf).await.into_diagnostic()?; - } - return Ok(RelayOutcome::Consumed); - } - buf.extend_from_slice(&tmp[..n]); - }; - - // Parse response framing - let header_str = String::from_utf8_lossy(&buf[..header_end]); - let observed_status = parse_observed_http_status_code(&header_str); - if let Some(observer) = options.observer.as_ref() { - match observed_status { - Some(status_code) if status_code < 400 => { - observer.observe(EndpointResult::HttpResponseReceived); - } - Some(_) => observer.observe(EndpointResult::UpstreamRejected), - None => { - observer.observe(EndpointResult::TransportFailed); - } - } - } - // Preserve the relay's legacy framing fallback for non-MCP traffic and - // malformed upstream responses. Endpoint status uses the strict parser above, - // so this fallback can never become a false successful observation. - let status_code = parse_status_code(&header_str).unwrap_or(200); - let server_wants_close = parse_connection_close(&header_str); - let http_10_closes_by_default = - response_is_http_10(&header_str) && !parse_connection_keep_alive(&header_str); - let event_stream = response_is_event_stream(&header_str); - let body_length = parse_body_length(&header_str)?; - - debug!( - status_code, - ?body_length, - server_wants_close, - request_method, - overflow_bytes = buf.len() - header_end, - "relay_response framing" - ); - - // 101 Switching Protocols: the connection has been upgraded (e.g. to - // WebSocket). Forward the 101 headers to the client and signal the - // caller to switch to raw bidirectional TCP relay. Any bytes read - // from upstream beyond the headers are overflow that belong to the - // upgraded protocol and must be forwarded before switching. - if status_code == 101 { - if !options.client_requested_upgrade { - return Ok(RelayOutcome::Consumed); - } - let (websocket_permessage_deflate, websocket_subprotocol) = validate_websocket_response( - &header_str, - options.websocket_extensions, - options.websocket.as_ref(), - )?; - client - .write_all(&buf[..header_end]) - .await - .into_diagnostic()?; - client.flush().await.into_diagnostic()?; - let overflow = buf[header_end..].to_vec(); - debug!( - request_method, - overflow_bytes = overflow.len(), - "101 Switching Protocols — signaling protocol upgrade" - ); - return Ok(RelayOutcome::Upgraded { - overflow, - websocket_permessage_deflate, - websocket_subprotocol, - }); - } - - // Bodiless responses (HEAD, 1xx, 204, 304): forward headers only, skip body - if is_bodiless_response(request_method, status_code) { - client - .write_all(&buf[..header_end]) - .await - .into_diagnostic()?; - client.flush().await.into_diagnostic()?; - return if server_wants_close { - Ok(RelayOutcome::Consumed) - } else { - Ok(RelayOutcome::Reusable) - }; - } - - // No explicit framing (no Content-Length, no Transfer-Encoding). - // Per RFC 7230 §3.3.3 the body is delimited by connection close. - if matches!(body_length, BodyLength::None) { - if server_wants_close || http_10_closes_by_default || event_stream { - // Server indicated it will close, or this is a streaming response - // such as SSE where the body is intentionally delimited by EOF. - let before_end = &buf[..header_end - 2]; - client.write_all(before_end).await.into_diagnostic()?; - if server_wants_close || http_10_closes_by_default { - client - .write_all(b"Connection: close\r\n\r\n") - .await - .into_diagnostic()?; - } else { - client.write_all(b"\r\n").await.into_diagnostic()?; - } - let overflow = &buf[header_end..]; - if !overflow.is_empty() { - client.write_all(overflow).await.into_diagnostic()?; - client.flush().await.into_diagnostic()?; - } - if event_stream { - relay_until_eof_without_idle_timeout(upstream, client).await?; - } else { - relay_until_eof(upstream, client).await?; - } - client.flush().await.into_diagnostic()?; - client.shutdown().await.into_diagnostic()?; - return Ok(RelayOutcome::Consumed); - } - // No Connection: close — an HTTP/1.1 keep-alive server that omits - // framing headers has an empty body. Forward headers and continue - // the relay loop instead of blocking on relay_until_eof. - debug!("BodyLength::None without Connection: close — treating body as empty"); - client - .write_all(&buf[..header_end]) - .await - .into_diagnostic()?; - client.flush().await.into_diagnostic()?; - return Ok(RelayOutcome::Reusable); - } - - // Forward response headers + any overflow body bytes - client.write_all(&buf).await.into_diagnostic()?; - let overflow_len = (buf.len() - header_end) as u64; - - // Forward remaining response body - match body_length { - BodyLength::ContentLength(len) => { - let remaining = len.saturating_sub(overflow_len); - if remaining > 0 { - relay_fixed(upstream, client, remaining, None).await?; - } - } - BodyLength::Chunked => { - relay_chunked(upstream, client, &buf[header_end..], None).await?; - } - BodyLength::None => unreachable!(), - } - client.flush().await.into_diagnostic()?; - debug!( - request_method, - elapsed_ms = started_at.elapsed().as_millis(), - "relay_response complete (explicit framing)" - ); - - // When body framing is explicit (Content-Length / Chunked), always report - // the connection as reusable so the relay loop continues. If the server - // sent `Connection: close`, the *next* upstream write will fail and the - // loop will exit via the normal error path. Exiting early here would - // tear down the CONNECT tunnel before the client can detect the close, - // causing ~30 s retry delays in clients like `gh`. - Ok(RelayOutcome::Reusable) -} - -/// Parse the HTTP status code from a response status line. -/// -/// Expects the first line to look like `HTTP/1.1 200 OK`. -fn parse_status_code(headers: &str) -> Option { - let status_line = headers.lines().next()?; - let code_str = status_line.split_whitespace().nth(1)?; - code_str.parse().ok() -} - -/// Parse a syntactically valid HTTP/1.x response status for endpoint reporting. -fn parse_observed_http_status_code(headers: &str) -> Option { - let status_line = headers.lines().next()?; - let mut fields = status_line.split_whitespace(); - match fields.next()? { - "HTTP/1.0" | "HTTP/1.1" => {} - _ => return None, - } - let code = fields.next()?; - if code.len() != 3 || !code.bytes().all(|byte| byte.is_ascii_digit()) { - return None; - } - code.parse() - .ok() - .filter(|status| (100..=999).contains(status)) -} - -/// Check if the response headers contain `Connection: close`. -fn parse_connection_close(headers: &str) -> bool { - for line in headers.lines().skip(1) { - let lower = line.to_ascii_lowercase(); - if lower.starts_with("connection:") { - let val = lower.split_once(':').map_or("", |(_, v)| v.trim()); - return val.contains("close"); - } - } - false -} - -/// Check if an HTTP/1.0 response opts into a persistent connection. -fn parse_connection_keep_alive(headers: &str) -> bool { - headers.lines().skip(1).any(|line| { - let lower = line.to_ascii_lowercase(); - lower - .strip_prefix("connection:") - .is_some_and(|value| value.split(',').any(|token| token.trim() == "keep-alive")) - }) -} - -fn response_is_http_10(headers: &str) -> bool { - headers - .lines() - .next() - .and_then(|line| line.split_whitespace().next()) - == Some("HTTP/1.0") -} - -fn response_is_event_stream(headers: &str) -> bool { - headers.lines().skip(1).any(|line| { - let lower = line.to_ascii_lowercase(); - let Some(value) = lower.strip_prefix("content-type:") else { - return false; - }; - value - .split(';') - .next() - .is_some_and(|mime| mime.trim() == "text/event-stream") - }) -} - fn validate_websocket_response( headers: &str, mode: WebSocketExtensionMode, @@ -3839,17 +3538,287 @@ mod tests { use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; use openshell_core::endpoint_status::{EndpointStatusCommand, EndpointStatusReceiver}; use openshell_core::proposals::AgentProposals; + use openshell_core::proto::{ + Decision, HttpRequestResult, HttpResponseBlockDelivery, HttpResponseBodyMode, + HttpResponseBodyResult, HttpResponseBodyTransform, HttpResponseEvent, + HttpResponseEventResult, HttpResponsePreflightInspect, HttpResponsePreflightResult, + HttpResponseTrailersResult, MiddlewareBinding, MiddlewareManifest, + SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, http_response_body_result, + http_response_body_transform, http_response_body_unit, http_response_event, + http_response_event_result, http_response_preflight_result, + }; use openshell_core::secrets::SecretResolver; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use tokio::io::ReadBuf; + use tokio::sync::mpsc; + use tokio_stream::wrappers::ReceiverStream; const TEST_POLICY: &str = include_str!("../../data/sandbox-policy.rego"); const VALID_WS_KEY: &str = "dGhlIHNhbXBsZSBub25jZQ=="; const VALID_WS_ACCEPT: &str = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="; const TEXT_OPCODE: u8 = 0x1; + #[derive(Clone, Copy)] + enum ResponseRelayScript { + HeadersOnly, + WholeBody, + WholeBodyWithTrailer, + Stream, + BlockPreflight, + BlockWholeBody, + BlockStream, + SlowWholeBody, + SlowStream, + InvalidBodySequence, + InvalidWholeBodySequence, + } + + struct ResponseRelayService { + script: ResponseRelayScript, + request_only: bool, + body_gate: Option, + captured_preflight_headers: Option>>>, + } + + #[derive(Clone)] + struct ResponseBodyGate { + entered: Arc, + release: Arc, + } + + #[tonic::async_trait] + impl openshell_supervisor_middleware::InProcessMiddleware for ResponseRelayService { + async fn describe(&self) -> MiddlewareManifest { + MiddlewareManifest { + name: "test/response-relay".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: if self.request_only { + SupervisorMiddlewareOperation::HttpRequest + } else { + SupervisorMiddlewareOperation::HttpResponse + } as i32, + phase: if self.request_only { + SupervisorMiddlewarePhase::PreCredentials + } else { + SupervisorMiddlewarePhase::PreReturn + } as i32, + max_payload_bytes: 4096, + request_timeout: None, + }], + expected_audience: String::new(), + } + } + + async fn validate_config( + &self, + _middleware_name: &str, + _config: &prost_types::Struct, + ) -> Result<()> { + Ok(()) + } + + async fn evaluate_http_request( + &self, + _request: openshell_supervisor_middleware::HttpRequestView<'_>, + ) -> Result { + Ok(HttpRequestResult { + decision: Decision::Allow as i32, + ..Default::default() + }) + } + + async fn open_http_response_pre_return( + &self, + mut requests: mpsc::Receiver, + ) -> std::result::Result< + openshell_supervisor_middleware::HttpResponseResultStream, + tonic::Status, + > { + assert!( + !self.request_only, + "request-only service received a response" + ); + let mut script = self.script; + let body_gate = self.body_gate.clone(); + let captured_preflight_headers = self.captured_preflight_headers.clone(); + let (sender, receiver) = mpsc::channel(4); + tokio::spawn(async move { + while let Some(event) = requests.recv().await { + let Some(event) = event.event else { + break; + }; + let result = match event { + http_response_event::Event::Preflight(preflight) => { + if let Some(captured) = &captured_preflight_headers { + *captured.lock().expect("preflight capture lock") = + preflight.headers.clone(); + } + if preflight + .config + .as_ref() + .is_some_and(|config| config.fields.contains_key("whole_body")) + { + script = ResponseRelayScript::WholeBody; + } + if matches!(script, ResponseRelayScript::BlockPreflight) { + HttpResponseEventResult { + result: Some( + http_response_event_result::Result::PreflightResult( + HttpResponsePreflightResult { + action: Some( + http_response_preflight_result::Action::BlockDelivery( + HttpResponseBlockDelivery {}, + ), + ), + reason_code: "content_match".into(), + ..Default::default() + }, + ), + ), + } + } else { + let (body_mode, header_mutations) = match script { + ResponseRelayScript::HeadersOnly => ( + HttpResponseBodyMode::HeadersOnly, + vec![write_header( + "cache-control", + "private", + ExistingHeaderAction::Overwrite, + )], + ), + ResponseRelayScript::WholeBody + | ResponseRelayScript::BlockWholeBody + | ResponseRelayScript::SlowWholeBody + | ResponseRelayScript::InvalidWholeBodySequence + | ResponseRelayScript::WholeBodyWithTrailer => { + (HttpResponseBodyMode::WholeBodyBytes, Vec::new()) + } + ResponseRelayScript::Stream + | ResponseRelayScript::SlowStream + | ResponseRelayScript::BlockStream + | ResponseRelayScript::InvalidBodySequence => { + (HttpResponseBodyMode::StreamBytes, Vec::new()) + } + ResponseRelayScript::BlockPreflight => unreachable!(), + }; + HttpResponseEventResult { + result: Some( + http_response_event_result::Result::PreflightResult( + HttpResponsePreflightResult { + action: Some( + http_response_preflight_result::Action::Inspect( + HttpResponsePreflightInspect { + body_mode: body_mode as i32, + header_mutations, + }, + ), + ), + ..Default::default() + }, + ), + ), + } + } + } + http_response_event::Event::Body(body) => { + if let Some(gate) = &body_gate { + gate.entered.notify_one(); + gate.release.notified().await; + } + let Some(http_response_body_unit::Payload::Data(data)) = body.payload + else { + break; + }; + let replacement = match script { + ResponseRelayScript::WholeBody + | ResponseRelayScript::BlockWholeBody + | ResponseRelayScript::SlowWholeBody + | ResponseRelayScript::WholeBodyWithTrailer + | ResponseRelayScript::InvalidWholeBodySequence => { + [b"whole:".as_slice(), &data].concat() + } + ResponseRelayScript::Stream + | ResponseRelayScript::SlowStream + | ResponseRelayScript::BlockStream + | ResponseRelayScript::InvalidBodySequence => { + data.to_ascii_uppercase() + } + ResponseRelayScript::HeadersOnly + | ResponseRelayScript::BlockPreflight => break, + }; + if matches!( + script, + ResponseRelayScript::SlowWholeBody + | ResponseRelayScript::SlowStream + ) { + tokio::time::sleep(std::time::Duration::from_millis(75)).await; + } + HttpResponseEventResult { + result: Some(http_response_event_result::Result::BodyResult( + HttpResponseBodyResult { + sequence: if matches!( + script, + ResponseRelayScript::InvalidBodySequence + | ResponseRelayScript::InvalidWholeBodySequence + ) { + body.sequence + 1 + } else { + body.sequence + }, + action: Some( + if matches!( + script, + ResponseRelayScript::BlockWholeBody + | ResponseRelayScript::BlockStream + ) { + http_response_body_result::Action::BlockDelivery( + HttpResponseBlockDelivery {}, + ) + } else { + http_response_body_result::Action::Transform( + HttpResponseBodyTransform { + replacement: Some( + http_response_body_transform::Replacement::Data( + replacement, + ), + ), + }, + ) + }, + ), + reason_code: if matches!( + script, + ResponseRelayScript::BlockWholeBody + | ResponseRelayScript::BlockStream + ) { + "content_match".into() + } else { + String::new() + }, + ..Default::default() + }, + )), + } + } + http_response_event::Event::Trailers(_) => HttpResponseEventResult { + result: Some(http_response_event_result::Result::TrailersResult( + HttpResponseTrailersResult::default(), + )), + }, + http_response_event::Event::SessionEnd(_) => break, + }; + if sender.send(Ok(result)).await.is_err() { + break; + } + } + }); + Ok(Box::pin(ReceiverStream::new(receiver))) + } + } + struct CountingReader { bytes: Vec, position: usize, @@ -5732,6 +5701,7 @@ mod tests { observer: Some(&observer), ..Default::default() }, + None, ) .await .expect("relay observed response"); @@ -5777,6 +5747,7 @@ mod tests { observer: Some(&observer), ..Default::default() }, + None, ) .await .expect("relay informational and final responses"); @@ -5814,6 +5785,7 @@ mod tests { observer: Some(&observer), ..Default::default() }, + None, ) .await .expect("relay split informational and final responses"); @@ -5856,6 +5828,7 @@ mod tests { observer: Some(&observer), ..Default::default() }, + None, ) .await .expect_err("informational headers must share a bounded exchange budget"); @@ -5913,6 +5886,7 @@ mod tests { observer: Some(&observer), ..Default::default() }, + None, ) .await .expect_err("response body read must fail"); @@ -5958,6 +5932,7 @@ mod tests { observer: Some(&observer), ..Default::default() }, + None, ); let assertion = async { let command = receiver.recv().await.expect("SSE endpoint observation"); @@ -5993,17 +5968,6 @@ mod tests { )); } - #[test] - fn test_http_10_connection_persistence() { - let default_close = "HTTP/1.0 200 OK\r\nServer: test\r\n\r\n"; - assert!(response_is_http_10(default_close)); - assert!(!parse_connection_keep_alive(default_close)); - - let keep_alive = "HTTP/1.0 200 OK\r\nConnection: keep-alive\r\n\r\n"; - assert!(response_is_http_10(keep_alive)); - assert!(parse_connection_keep_alive(keep_alive)); - } - #[test] fn test_response_is_event_stream() { assert!(response_is_event_stream( @@ -6029,61 +5993,1219 @@ mod tests { } #[tokio::test] - async fn relay_response_no_framing_with_connection_close_reads_until_eof() { - // Response with Connection: close but no Content-Length/TE: body is - // delimited by connection close — relay_until_eof should forward it. - let response = b"HTTP/1.1 200 OK\r\nConnection: close\r\nServer: test\r\n\r\nhello world"; + async fn response_middleware_unbound_chains_preserve_ordinary_headers() { + let mut many_headers = b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n".to_vec(); + for _ in 0..129 { + many_headers.extend_from_slice(b"Set-Cookie: a=b\r\n"); + } + many_headers.extend_from_slice(b"\r\n"); + let opaque_headers = + b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nX-Opaque: \xff\xfe\r\n\r\nabc".to_vec(); + let (_, chain) = response_middleware_fixture(ResponseRelayScript::HeadersOnly); + let request_only_runner = + openshell_supervisor_middleware::ChainRunner::new(Arc::new(ResponseRelayService { + script: ResponseRelayScript::HeadersOnly, + request_only: true, + body_gate: None, + captured_preflight_headers: None, + })); + let empty_runner = openshell_supervisor_middleware::ChainRunner::default(); + for response in [many_headers, opaque_headers] { + assert!(response.len() < MAX_HEADER_BYTES); + for context in [ + None, + Some(response_middleware_context(&empty_runner, &[], "GET")), + Some(response_middleware_context( + &request_only_runner, + &chain, + "GET", + )), + ] { + let mut upstream = response.as_slice(); + let mut delivered = Vec::new(); + let outcome = relay_response( + "GET", + &mut upstream, + &mut delivered, + RelayResponseOptions::default(), + context, + ) + .await + .unwrap(); + assert!(matches!(outcome, RelayOutcome::Reusable)); + assert_eq!(delivered, response); + } + } + } - let (mut upstream_read, mut upstream_write) = tokio::io::duplex(4096); - let (mut client_read, mut client_write) = tokio::io::duplex(4096); + #[tokio::test] + async fn response_middleware_selected_hook_enforces_header_limits() { + let mut response = b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n".to_vec(); + for _ in 0..129 { + response.extend_from_slice(b"X-Ordinary: value\r\n"); + } + response.extend_from_slice(b"\r\n"); + let (runner, chain) = response_middleware_fixture(ResponseRelayScript::HeadersOnly); + let mut upstream = response.as_slice(); + let mut delivered = Vec::new(); + let outcome = relay_response( + "GET", + &mut upstream, + &mut delivered, + RelayResponseOptions::default(), + Some(response_middleware_context(&runner, &chain, "GET")), + ) + .await + .unwrap(); + assert!(matches!(outcome, RelayOutcome::Consumed)); + assert!(delivered.starts_with(b"HTTP/1.1 502 ")); + } - tokio::spawn(async move { - upstream_write.write_all(response).await.unwrap(); - upstream_write.shutdown().await.unwrap(); - }); + #[tokio::test] + async fn response_middleware_omits_credentials_and_preserves_downstream_fields() { + let captured = Arc::new(std::sync::Mutex::new(Vec::new())); + let runner = + openshell_supervisor_middleware::ChainRunner::new(Arc::new(ResponseRelayService { + script: ResponseRelayScript::HeadersOnly, + request_only: false, + body_gate: None, + captured_preflight_headers: Some(Arc::clone(&captured)), + })); + let chain = vec![openshell_supervisor_middleware::ChainEntry { + name: "response".into(), + implementation: "test/response-relay".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }]; + let response = b"HTTP/1.1 200 OK\r\n\ + Content-Length: 5\r\n\ + Cache-Control: public\r\n\ + Set-Cookie: session=secret; HttpOnly\r\n\ + WWW-Authenticate: Bearer realm=private\r\n\ + Authentication-Info: nextnonce=secret\r\n\ + Proxy-Authenticate: Basic realm=proxy\r\n\ + Proxy-Authentication-Info: nextnonce=proxy-secret\r\n\ + Proxy-Authorization: Basic proxy-secret\r\n\ + X-OpenShell-Credential-Token: injected-secret\r\n\r\nhello"; + let mut upstream = response.as_slice(); + let mut delivered = Vec::new(); - let result = tokio::time::timeout( - std::time::Duration::from_secs(2), - relay_response( - "GET", - &mut upstream_read, - &mut client_write, - RelayResponseOptions::default(), - ), + let outcome = relay_response( + "GET", + &mut upstream, + &mut delivered, + RelayResponseOptions::default(), + Some(response_middleware_context(&runner, &chain, "GET")), ) .await - .expect("relay_response should not deadlock"); - - let outcome = result.expect("relay_response should succeed"); - assert!( - matches!(outcome, RelayOutcome::Consumed), - "connection consumed by read-until-EOF" - ); + .expect("response relay"); - client_write.shutdown().await.unwrap(); - let mut received = Vec::new(); - client_read.read_to_end(&mut received).await.unwrap(); - let received_str = String::from_utf8_lossy(&received); - assert!( - received_str.contains("Connection: close"), - "should preserve Connection: close" - ); - assert!( - received_str.contains("hello world"), - "body should be forwarded" - ); + assert!(matches!(outcome, RelayOutcome::Reusable)); + let observed = captured.lock().expect("preflight capture lock"); + assert_eq!( + observed + .iter() + .map(|header| header.name.as_str()) + .collect::>(), + vec!["content-length", "cache-control"] + ); + drop(observed); + + let delivered = String::from_utf8(delivered).expect("UTF-8 response"); + for credential_field in [ + "Set-Cookie: session=secret; HttpOnly\r\n", + "WWW-Authenticate: Bearer realm=private\r\n", + "Authentication-Info: nextnonce=secret\r\n", + "Proxy-Authenticate: Basic realm=proxy\r\n", + "Proxy-Authentication-Info: nextnonce=proxy-secret\r\n", + "Proxy-Authorization: Basic proxy-secret\r\n", + "X-OpenShell-Credential-Token: injected-secret\r\n", + ] { + assert!(delivered.contains(credential_field), "{delivered}"); + } + assert!(delivered.contains("cache-control: private\r\n")); + assert!(delivered.ends_with("\r\n\r\nhello")); } #[tokio::test] - async fn relay_response_http_10_without_framing_reads_until_eof() { - let response = b"HTTP/1.0 200 OK\r\nContent-Type: application/json\r\n\r\n{\"ok\":true}"; - - let (mut upstream_read, mut upstream_write) = tokio::io::duplex(4096); - let (mut client_read, mut client_write) = tokio::io::duplex(4096); - - tokio::spawn(async move { - upstream_write.write_all(response).await.unwrap(); - upstream_write.shutdown().await.unwrap(); + async fn response_middleware_flushes_partial_framed_payload_promptly() { + for chunked in [false, true] { + let (runner, chain) = response_middleware_fixture(ResponseRelayScript::Stream); + let (mut upstream_read, mut upstream_write) = tokio::io::duplex(8192); + // Small capacity forces the relay to complete partial downstream writes. + let (mut client_read, mut client_write) = tokio::io::duplex(7); + let head = if chunked { + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: text/event-stream\r\n\r\n1000\r\nabc".as_slice() + } else { + b"HTTP/1.1 200 OK\r\nContent-Length: 4096\r\nContent-Type: text/event-stream\r\n\r\nabc".as_slice() + }; + upstream_write.write_all(head).await.unwrap(); + let task = tokio::spawn(async move { + relay_response( + "GET", + &mut upstream_read, + &mut client_write, + RelayResponseOptions::default(), + Some(response_middleware_context(&runner, &chain, "GET")), + ) + .await + }); + let result = tokio::time::timeout(std::time::Duration::from_secs(2), async { + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") { + head.push(client_read.read_u8().await.unwrap()); + } + let mut first = [0; 8]; + client_read.read_exact(&mut first).await.unwrap(); + assert_eq!(&first, b"3\r\nABC\r\n"); + // Complete the same framed payload only after its first transformed + // bytes have reached the consumer. + upstream_write.write_all(&vec![b'd'; 4093]).await.unwrap(); + if chunked { + for fragment in [b"\r".as_slice(), b"\n0\r", b"\n\r", b"\n"] { + upstream_write.write_all(fragment).await.unwrap(); + tokio::task::yield_now().await; + } + } + drop(upstream_write); + let mut rest = Vec::new(); + client_read.read_to_end(&mut rest).await.unwrap(); + assert!(rest.ends_with(b"0\r\n\r\n")); + let body = collect_chunked_body(&mut tokio::io::empty(), &rest, None, None) + .await + .unwrap(); + assert_eq!(body, vec![b'D'; 4093]); + }) + .await; + if result.is_err() { + task.abort(); + } + let relay = task.await; + assert!(result.is_ok(), "partial payload stalled, chunked={chunked}"); + assert!(relay.unwrap().is_ok()); + } + } + + fn response_middleware_fixture( + script: ResponseRelayScript, + ) -> ( + openshell_supervisor_middleware::ChainRunner, + Vec, + ) { + response_middleware_fixture_with_error( + script, + openshell_supervisor_middleware::OnError::FailClosed, + ) + } + + fn response_middleware_fixture_with_error( + script: ResponseRelayScript, + on_error: openshell_supervisor_middleware::OnError, + ) -> ( + openshell_supervisor_middleware::ChainRunner, + Vec, + ) { + let runner = + openshell_supervisor_middleware::ChainRunner::new(Arc::new(ResponseRelayService { + script, + request_only: false, + body_gate: None, + captured_preflight_headers: None, + })); + let chain = vec![openshell_supervisor_middleware::ChainEntry { + name: "response".into(), + implementation: "test/response-relay".into(), + order: 0, + config: prost_types::Struct::default(), + on_error, + }]; + (runner, chain) + } + + fn response_middleware_context<'a>( + runner: &'a openshell_supervisor_middleware::ChainRunner, + chain: &'a [openshell_supervisor_middleware::ChainEntry], + method: &str, + ) -> HttpResponseMiddlewareRelay<'a> { + HttpResponseMiddlewareRelay { + chain, + runner, + request_context: RequestContext { + request_id: "request-1".into(), + sandbox_id: "sandbox-1".into(), + ..Default::default() + }, + target: HttpRequestTarget { + scheme: "https".into(), + host: "example.test".into(), + port: 443, + method: method.into(), + path: "/data".into(), + query: String::new(), + }, + policy_name: "test-policy", + generation_guard: None, + whole_body_timeout: DEFAULT_HTTP_RESPONSE_WHOLE_BODY_TIMEOUT, + } + } + + async fn run_response_middleware_relay( + response: &[u8], + method: &str, + script: ResponseRelayScript, + ) -> (Result, Vec) { + run_response_middleware_relay_with_error( + response, + method, + script, + openshell_supervisor_middleware::OnError::FailClosed, + ) + .await + } + + async fn run_response_middleware_relay_with_error( + response: &[u8], + method: &str, + script: ResponseRelayScript, + on_error: openshell_supervisor_middleware::OnError, + ) -> (Result, Vec) { + run_response_middleware_relay_with_timeout( + response, + method, + script, + on_error, + std::time::Duration::from_mins(2), + ) + .await + } + + async fn run_response_middleware_relay_with_timeout( + response: &[u8], + method: &str, + script: ResponseRelayScript, + on_error: openshell_supervisor_middleware::OnError, + whole_body_timeout: std::time::Duration, + ) -> (Result, Vec) { + let (runner, chain) = response_middleware_fixture_with_error(script, on_error); + let (mut upstream_read, mut upstream_write) = tokio::io::duplex(16 * 1024); + let (mut client_read, mut client_write) = tokio::io::duplex(16 * 1024); + let response = response.to_vec(); + tokio::spawn(async move { + upstream_write.write_all(&response).await.unwrap(); + upstream_write.shutdown().await.unwrap(); + }); + let mut middleware = response_middleware_context(&runner, &chain, method); + middleware.whole_body_timeout = whole_body_timeout; + let outcome = relay_response( + method, + &mut upstream_read, + &mut client_write, + RelayResponseOptions::default(), + Some(middleware), + ) + .await; + drop(client_write); + let mut delivered = Vec::new(); + client_read.read_to_end(&mut delivered).await.unwrap(); + (outcome, delivered) + } + + #[tokio::test] + async fn response_middleware_headers_only_mutates_head_and_preserves_framing() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nCache-Control: public\r\n\r\nhello", + "GET", + ResponseRelayScript::HeadersOnly, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.contains("cache-control: private\r\n"), + "{delivered}" + ); + assert!(delivered.contains("Content-Length: 5\r\n"), "{delivered}"); + assert!( + !delivered.to_ascii_lowercase().contains("transfer-encoding"), + "{delivered}" + ); + assert!(delivered.ends_with("\r\n\r\nhello"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_headers_only_preserves_chunked_and_close_delimited_bodies() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2;ext=yes\r\nhe\r\n3\r\nllo\r\n0\r\n\r\n", + "GET", + ResponseRelayScript::HeadersOnly, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.contains("Transfer-Encoding: chunked\r\n"), + "{delivered}" + ); + assert!( + delivered.ends_with("2;ext=yes\r\nhe\r\n3\r\nllo\r\n0\r\n\r\n"), + "{delivered}" + ); + + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nhello", + "GET", + ResponseRelayScript::HeadersOnly, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + assert!( + String::from_utf8(delivered) + .unwrap() + .ends_with("\r\n\r\nhello") + ); + } + + #[tokio::test] + async fn response_middleware_whole_body_delays_commit_and_sets_length() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nETag: stale\r\n\r\nhello", + "GET", + ResponseRelayScript::WholeBody, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!(delivered.contains("Content-Length: 11\r\n"), "{delivered}"); + assert!( + !delivered.to_ascii_lowercase().contains("etag:"), + "{delivered}" + ); + assert!(delivered.ends_with("\r\n\r\nwhole:hello"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_preflight_block_returns_canonical_403() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", + "GET", + ResponseRelayScript::BlockPreflight, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.starts_with("HTTP/1.1 403 Forbidden\r\n"), + "{delivered}" + ); + assert!( + delivered.contains("\"error\":\"middleware_denied\""), + "{delivered}" + ); + assert!( + delivered.contains("\"reason_code\":\"content_match\""), + "{delivered}" + ); + assert!(delivered.contains("Connection: close\r\n"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_head_block_reports_length_without_body() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n", + "HEAD", + ResponseRelayScript::BlockPreflight, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + let header_end = delivered + .windows(4) + .position(|window| window == b"\r\n\r\n") + .unwrap() + + 4; + let head = String::from_utf8(delivered[..header_end].to_vec()).unwrap(); + assert!(head.starts_with("HTTP/1.1 403 Forbidden\r\n"), "{head}"); + assert!(head.contains("Content-Length: "), "{head}"); + assert_eq!(delivered.len(), header_end); + } + + #[tokio::test] + async fn response_middleware_whole_body_block_returns_403_before_commit() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", + "GET", + ResponseRelayScript::BlockWholeBody, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.starts_with("HTTP/1.1 403 Forbidden\r\n"), + "{delivered}" + ); + assert!(!delivered.contains("HTTP/1.1 200 OK"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_stream_block_aborts_after_commit_without_error_bytes() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", + "GET", + ResponseRelayScript::BlockStream, + ) + .await; + assert!(outcome.is_err()); + let delivered = String::from_utf8(delivered).unwrap(); + assert!(delivered.starts_with("HTTP/1.1 200 OK\r\n"), "{delivered}"); + assert!(!delivered.contains("middleware_denied"), "{delivered}"); + assert!( + !delivered.contains("response_delivery_failed"), + "{delivered}" + ); + } + + async fn run_response_relay_across_policy_reload( + script: ResponseRelayScript, + ) -> (Result, Vec) { + let entered = Arc::new(tokio::sync::Notify::new()); + let release = Arc::new(tokio::sync::Notify::new()); + let runner = + openshell_supervisor_middleware::ChainRunner::new(Arc::new(ResponseRelayService { + script, + request_only: false, + body_gate: Some(ResponseBodyGate { + entered: Arc::clone(&entered), + release: Arc::clone(&release), + }), + captured_preflight_headers: None, + })); + let chain = vec![openshell_supervisor_middleware::ChainEntry { + name: "response".into(), + implementation: "test/response-relay".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }]; + let engine = OpaEngine::from_strings(TEST_POLICY, "network_policies: {}\n").unwrap(); + let guard = engine + .generation_guard(engine.current_generation()) + .expect("initial generation guard"); + let mut middleware = response_middleware_context(&runner, &chain, "GET"); + middleware.generation_guard = Some(&guard); + let mut upstream = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello".as_slice(); + let mut delivered = Vec::new(); + let relay = relay_response( + "GET", + &mut upstream, + &mut delivered, + RelayResponseOptions::default(), + Some(middleware), + ); + let reload = async { + entered.notified().await; + engine + .reload(TEST_POLICY, "network_policies: {}\n") + .expect("policy reload"); + release.notify_one(); + }; + let (outcome, ()) = tokio::join!(relay, reload); + (outcome, delivered) + } + + #[tokio::test] + async fn response_middleware_rechecks_generation_after_stream_exchange() { + let (outcome, delivered) = + run_response_relay_across_policy_reload(ResponseRelayScript::Stream).await; + + let error = outcome.expect_err("stale stream output must not be delivered"); + assert!(error.to_string().contains("policy generation is stale")); + assert!(delivered.ends_with(b"\r\n\r\n")); + assert!(!delivered.windows(5).any(|window| window == b"HELLO")); + } + + #[tokio::test] + async fn response_middleware_rechecks_generation_after_whole_body_finish() { + let (outcome, delivered) = + run_response_relay_across_policy_reload(ResponseRelayScript::WholeBody).await; + + let error = outcome.expect_err("stale whole-body output must not be delivered"); + assert!(error.to_string().contains("policy generation is stale")); + assert!(delivered.is_empty()); + } + + #[tokio::test] + async fn response_middleware_whole_body_timeout_obeys_failure_policy() { + let response = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello"; + let (outcome, delivered) = run_response_middleware_relay_with_timeout( + response, + "GET", + ResponseRelayScript::SlowWholeBody, + openshell_supervisor_middleware::OnError::FailOpen, + std::time::Duration::from_millis(15), + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + assert!( + String::from_utf8(delivered) + .unwrap() + .ends_with("\r\n\r\nhello") + ); + + let (outcome, delivered) = run_response_middleware_relay_with_timeout( + response, + "GET", + ResponseRelayScript::SlowWholeBody, + openshell_supervisor_middleware::OnError::FailClosed, + std::time::Duration::from_millis(15), + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + assert!( + String::from_utf8(delivered) + .unwrap() + .contains("response_delivery_failed") + ); + } + + #[tokio::test] + async fn response_middleware_whole_body_timeout_does_not_reset_for_trickle_input() { + let (runner, chain) = response_middleware_fixture_with_error( + ResponseRelayScript::WholeBody, + openshell_supervisor_middleware::OnError::FailOpen, + ); + let (mut upstream_read, mut upstream_write) = tokio::io::duplex(16 * 1024); + let (mut client_read, mut client_write) = tokio::io::duplex(16 * 1024); + tokio::spawn(async move { + upstream_write + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nh") + .await + .unwrap(); + for byte in b"ello" { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + upstream_write.write_all(&[*byte]).await.unwrap(); + } + upstream_write.shutdown().await.unwrap(); + }); + let mut middleware = response_middleware_context(&runner, &chain, "GET"); + middleware.whole_body_timeout = std::time::Duration::from_millis(20); + let outcome = relay_response( + "GET", + &mut upstream_read, + &mut client_write, + RelayResponseOptions::default(), + Some(middleware), + ) + .await; + drop(client_write); + let mut delivered = Vec::new(); + client_read.read_to_end(&mut delivered).await.unwrap(); + + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + let delivered = String::from_utf8(delivered).unwrap(); + let (_, body) = delivered.split_once("\r\n\r\n").unwrap(); + let decoded = collect_chunked_body(&mut tokio::io::empty(), body.as_bytes(), None, None) + .await + .unwrap(); + assert_eq!(decoded, b"hello"); + assert!(!delivered.contains("whole:hello"), "{delivered}"); + } + + #[tokio::test(start_paused = true)] + async fn response_middleware_expiry_preserves_bytes_through_slow_stream_and_client() { + for chunked in [true, false] { + let (runner, mut chain) = response_middleware_fixture_with_error( + ResponseRelayScript::SlowStream, + openshell_supervisor_middleware::OnError::FailOpen, + ); + let mut whole_body = chain[0].clone(); + whole_body.name = "whole-body".into(); + whole_body + .config + .fields + .insert("whole_body".into(), prost_types::Value::default()); + chain[0].order = 1; + chain.insert(0, whole_body); + let (mut upstream_read, mut upstream_write) = tokio::io::duplex(8192); + // Force write_all to make partial progress before each wait. + let (mut client_read, mut client_write) = tokio::io::duplex(7); + let producer = async move { + let head = if chunked { + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n800\r\n".as_slice() + } else { + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".as_slice() + }; + upstream_write.write_all(head).await.unwrap(); + upstream_write.write_all(&vec![b'a'; 2048]).await.unwrap(); + if chunked { + upstream_write.write_all(b"\r\n").await.unwrap(); + } + // The first coalesced unit belongs to the whole-body stage. A new + // partial unit starts coalescing just before its deadline. + tokio::time::sleep(std::time::Duration::from_millis(9)).await; + upstream_write + .write_all(if chunked { b"1\r\nb\r\n" } else { b"b" }) + .await + .unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + if chunked { + upstream_write.write_all(b"0\r\n\r\n").await.unwrap(); + } + upstream_write.shutdown().await.unwrap(); + }; + let relay = async { + let mut context = response_middleware_context(&runner, &chain, "GET"); + context.whole_body_timeout = std::time::Duration::from_millis(10); + let outcome = relay_response( + "GET", + &mut upstream_read, + &mut client_write, + RelayResponseOptions::default(), + Some(context), + ) + .await; + drop(client_write); + outcome + }; + let consumer = async move { + let mut delivered = Vec::new(); + let mut bytes = [0; 7]; + loop { + let count = client_read.read(&mut bytes).await.unwrap(); + if count == 0 { + break; + } + delivered.extend_from_slice(&bytes[..count]); + tokio::time::sleep(std::time::Duration::from_millis(1)).await; + } + delivered + }; + let ((), outcome, delivered) = tokio::time::timeout( + std::time::Duration::from_secs(3), + Box::pin(async { tokio::join!(producer, relay, consumer) }), + ) + .await + .expect("response relay stalled"); + assert!(outcome.is_ok(), "{outcome:?}"); + assert!(delivered.starts_with(b"HTTP/1.1 200 OK\r\n")); + let head_end = delivered + .windows(4) + .position(|bytes| bytes == b"\r\n\r\n") + .unwrap() + + 4; + let mut wire = &delivered[head_end..]; + let mut body = Vec::new(); + loop { + let end = wire.windows(2).position(|bytes| bytes == b"\r\n").unwrap(); + let size = + usize::from_str_radix(std::str::from_utf8(&wire[..end]).unwrap(), 16).unwrap(); + wire = &wire[end + 2..]; + if size == 0 { + assert_eq!(wire, b"\r\n"); + break; + } + body.extend_from_slice(&wire[..size]); + assert_eq!(&wire[size..size + 2], b"\r\n"); + wire = &wire[size + 2..]; + } + let mut expected = vec![b'A'; 2048]; + expected.push(b'B'); + assert_eq!(body, expected, "chunked={chunked}"); + } + } + + #[tokio::test] + async fn response_middleware_streams_normalized_chunks_and_preserves_trailers() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nTrailer: x-upstream\r\n\r\n2;ext=yes\r\nhe\r\n3\r\nllo\r\n0\r\nX-Upstream: kept\r\n\r\n", + "GET", + ResponseRelayScript::Stream, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!(delivered.contains("Trailer: x-upstream\r\n"), "{delivered}"); + assert!(delivered.contains("5\r\nHELLO\r\n"), "{delivered}"); + assert!(delivered.contains("x-upstream: kept\r\n"), "{delivered}"); + assert!(!delivered.contains("digest:"), "{delivered}"); + assert!(!delivered.contains("ext=yes"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_rejects_malformed_response_fields_before_commit() { + for response in [ + b"HTTP/1.1 200 OK\r\nBad Name: value\r\nContent-Length: 0\r\n\r\n".as_slice(), + b"HTTP/1.1 200 OK\r\nTrailer: content-length\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n".as_slice(), + b"HTTP/1.1 200 OK\r\nConnection: x-private\r\nTrailer: x-private\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n".as_slice(), + ] { + let (outcome, delivered) = run_response_middleware_relay( + response, + "GET", + ResponseRelayScript::WholeBody, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.starts_with("HTTP/1.1 502 Bad Gateway\r\n"), + "{delivered}" + ); + } + } + + #[tokio::test] + async fn response_middleware_rejects_malformed_or_protected_upstream_trailers_atomically() { + for response in [ + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nBad Name: value\r\n\r\n".as_slice(), + b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nContent-Length: 7\r\n\r\n".as_slice(), + ] { + let (outcome, delivered) = run_response_middleware_relay( + response, + "GET", + ResponseRelayScript::WholeBody, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.starts_with("HTTP/1.1 502 Bad Gateway\r\n"), + "{delivered}" + ); + assert!(!delivered.contains("whole:hello"), "{delivered}"); + } + } + + #[tokio::test] + async fn response_middleware_never_uses_chunked_framing_for_http_10() { + for (script, expected_body) in [ + (ResponseRelayScript::HeadersOnly, "hello"), + (ResponseRelayScript::Stream, "HELLO"), + (ResponseRelayScript::WholeBodyWithTrailer, "whole:hello"), + ] { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.0 200 OK\r\nContent-Length: 5\r\n\r\nhello", + "GET", + script, + ) + .await; + assert!(outcome.is_ok()); + let delivered = String::from_utf8(delivered).unwrap(); + assert!(delivered.starts_with("HTTP/1.0 200 OK\r\n"), "{delivered}"); + assert!( + !delivered.to_ascii_lowercase().contains("transfer-encoding"), + "{delivered}" + ); + assert!( + !delivered.to_ascii_lowercase().contains("trailer:"), + "{delivered}" + ); + assert!(delivered.ends_with(expected_body), "{delivered}"); + } + } + + #[tokio::test] + async fn response_middleware_preserves_baseline_connection_outcomes() { + let (outcome, _) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\nhello", + "GET", + ResponseRelayScript::HeadersOnly, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\n\r\n", + "GET", + ResponseRelayScript::HeadersOnly, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + assert!(String::from_utf8(delivered).unwrap().ends_with("\r\n\r\n")); + } + + #[tokio::test] + async fn response_middleware_forwards_interim_head_before_final_preflight() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 100 Continue\r\nX-Interim: yes\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok", + "GET", + ResponseRelayScript::WholeBody, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!(delivered.starts_with("HTTP/1.1 100 Continue\r\nX-Interim: yes\r\n\r\n")); + assert!(delivered.ends_with("whole:ok"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_handles_bodyless_responses_without_body_events() { + for response in [ + b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n".as_slice(), + b"HTTP/1.1 304 Not Modified\r\nContent-Length: 5\r\n\r\n".as_slice(), + ] { + let (outcome, delivered) = + run_response_middleware_relay(response, "GET", ResponseRelayScript::HeadersOnly) + .await; + assert!(outcome.is_ok()); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.contains("cache-control: private\r\n"), + "{delivered}" + ); + assert!(delivered.ends_with("\r\n\r\n"), "{delivered}"); + } + + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n", + "HEAD", + ResponseRelayScript::HeadersOnly, + ) + .await; + assert!(outcome.is_ok()); + let split = delivered + .windows(4) + .position(|window| window == b"\r\n\r\n") + .unwrap() + + 4; + assert_eq!(&delivered[split..], b""); + } + + #[tokio::test] + async fn response_middleware_bypasses_protocol_upgrades() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n\x81\x02ok", + "GET", + ResponseRelayScript::HeadersOnly, + ) + .await; + assert!(matches!( + outcome.unwrap(), + RelayOutcome::Upgraded { ref overflow, .. } if overflow == b"\x81\x02ok" + )); + let delivered = String::from_utf8(delivered).unwrap(); + assert!(!delivered.contains("cache-control: private"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_fail_closed_before_commit_returns_canonical_502() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", + "GET", + ResponseRelayScript::InvalidWholeBodySequence, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.starts_with("HTTP/1.1 502 Bad Gateway\r\n"), + "{delivered}" + ); + assert!(delivered.contains("\"error\":\"response_delivery_failed\"")); + assert!(delivered.contains( + "The upstream request may have completed, but OpenShell could not deliver its response. Retrying may repeat upstream side effects." + )); + assert!(!delivered.contains("invalid_body_sequence"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_head_failure_reports_body_length_without_body() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n", + "HEAD", + ResponseRelayScript::WholeBody, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + let split = delivered + .windows(4) + .position(|window| window == b"\r\n\r\n") + .unwrap() + + 4; + let head = String::from_utf8(delivered[..split].to_vec()).unwrap(); + assert!(head.starts_with("HTTP/1.1 502 Bad Gateway\r\n"), "{head}"); + assert!(head.contains("Content-Length: "), "{head}"); + assert_eq!(&delivered[split..], b""); + } + + #[tokio::test] + async fn response_middleware_fail_closed_after_commit_aborts_without_replacement() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", + "GET", + ResponseRelayScript::InvalidBodySequence, + ) + .await; + assert!(outcome.is_err()); + let delivered = String::from_utf8(delivered).unwrap(); + assert!(delivered.starts_with("HTTP/1.1 200 OK\r\n"), "{delivered}"); + assert!(!delivered.contains("502 Bad Gateway"), "{delivered}"); + } + + #[tokio::test] + async fn response_middleware_unrepresentable_input_obeys_failure_policy() { + let mut many_headers = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n".to_vec(); + for _ in 0..=openshell_supervisor_middleware::MAX_MIDDLEWARE_HEADERS { + many_headers.extend_from_slice(b"X-Extra: value\r\n"); + } + many_headers.extend_from_slice(b"\r\nok"); + for response in [ + b"HTTP/1.1 200 OK\r\nX-Legacy: \xff\r\nContent-Length: 2\r\n\r\nok".as_slice(), + many_headers.as_slice(), + ] { + for on_error in [ + openshell_supervisor_middleware::OnError::FailOpen, + openshell_supervisor_middleware::OnError::FailClosed, + ] { + let (outcome, delivered) = run_response_middleware_relay_with_error( + response, + "GET", + ResponseRelayScript::HeadersOnly, + on_error, + ) + .await; + if on_error == openshell_supervisor_middleware::OnError::FailOpen { + assert!(matches!(outcome.unwrap(), RelayOutcome::Reusable)); + assert_eq!(delivered, response); + } else { + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + assert!(delivered.starts_with(b"HTTP/1.1 502 Bad Gateway\r\n")); + assert!( + String::from_utf8(delivered) + .unwrap() + .contains("response_delivery_failed") + ); + } + } + } + } + + #[tokio::test] + async fn response_middleware_obs_text_does_not_bypass_unsafe_headers() { + for response in [ + b"HTTP/1.1 200 OK\r\nX-Legacy: \xff\r\nBad Name: value\r\nContent-Length: 2\r\n\r\nok".as_slice(), + b"HTTP/1.1 200 OK\r\nX-Legacy: \xff\x00\r\nContent-Length: 2\r\n\r\nok".as_slice(), + b"HTTP/1.1 200 OK\r\nX-Legacy: \xff\r\nTrailer: content-length\r\nContent-Length: 2\r\n\r\nok".as_slice(), + ] { + let (outcome, delivered) = run_response_middleware_relay_with_error( + response, "GET", ResponseRelayScript::HeadersOnly, + openshell_supervisor_middleware::OnError::FailOpen, + ).await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + assert!(delivered.starts_with(b"HTTP/1.1 502 Bad Gateway\r\n")); + } + } + + #[tokio::test] + async fn response_middleware_fail_open_preserves_input_before_and_after_commit() { + for (script, expected_framing) in [ + ( + ResponseRelayScript::InvalidWholeBodySequence, + "Content-Length: 5\r\n", + ), + ( + ResponseRelayScript::InvalidBodySequence, + "Transfer-Encoding: chunked\r\n", + ), + ] { + let (outcome, delivered) = run_response_middleware_relay_with_error( + b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello", + "GET", + script, + openshell_supervisor_middleware::OnError::FailOpen, + ) + .await; + assert!(outcome.is_ok()); + let delivered = String::from_utf8(delivered).unwrap(); + assert!(delivered.contains(expected_framing), "{delivered}"); + assert!(delivered.contains("hello"), "{delivered}"); + assert!(!delivered.contains("502 Bad Gateway"), "{delivered}"); + } + } + + #[tokio::test] + async fn response_middleware_stale_policy_generation_aborts_before_preflight() { + 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 (runner, chain) = response_middleware_fixture(ResponseRelayScript::Stream); + let (mut upstream_read, mut upstream_write) = tokio::io::duplex(4096); + let (mut client_read, mut client_write) = tokio::io::duplex(4096); + upstream_write + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello") + .await + .unwrap(); + upstream_write.shutdown().await.unwrap(); + let mut context = response_middleware_context(&runner, &chain, "GET"); + context.generation_guard = Some(&guard); + let outcome = relay_response( + "GET", + &mut upstream_read, + &mut client_write, + RelayResponseOptions::default(), + Some(context), + ) + .await; + assert!(outcome.is_err()); + drop(client_write); + let mut delivered = Vec::new(); + client_read.read_to_end(&mut delivered).await.unwrap(); + assert!(delivered.is_empty()); + } + + #[tokio::test] + async fn response_middleware_client_disconnect_aborts_stream_delivery() { + let (runner, chain) = response_middleware_fixture(ResponseRelayScript::Stream); + let (mut upstream_read, mut upstream_write) = tokio::io::duplex(4096); + let (client_read, mut client_write) = tokio::io::duplex(4096); + drop(client_read); + upstream_write + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello") + .await + .unwrap(); + upstream_write.shutdown().await.unwrap(); + let outcome = relay_response( + "GET", + &mut upstream_read, + &mut client_write, + RelayResponseOptions::default(), + Some(response_middleware_context(&runner, &chain, "GET")), + ) + .await; + assert!(outcome.is_err()); + } + + #[tokio::test] + async fn response_middleware_streams_close_delimited_body_with_owned_framing() { + let (outcome, delivered) = run_response_middleware_relay( + b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nhello", + "GET", + ResponseRelayScript::Stream, + ) + .await; + assert!(matches!(outcome.unwrap(), RelayOutcome::Consumed)); + let delivered = String::from_utf8(delivered).unwrap(); + assert!( + delivered.contains("Transfer-Encoding: chunked\r\n"), + "{delivered}" + ); + assert!(delivered.contains("5\r\nHELLO\r\n"), "{delivered}"); + } + + #[test] + fn response_middleware_ocsf_events_omit_content_headers_and_free_form_reasons() { + let target = HttpRequestTarget { + scheme: "https".into(), + host: "example.test".into(), + port: 443, + method: "GET".into(), + path: "/safe".into(), + query: String::new(), + }; + let events = http_response_middleware_invocation_events( + "policy", + &target, + 200, + &[openshell_supervisor_middleware::HttpResponseInvocation { + config_name: "scan".into(), + implementation: "example/scan".into(), + outcome: openshell_supervisor_middleware::HttpResponseInvocationOutcome::FailOpen, + sequence: Some(1), + input_size: 19, + output_size: None, + failed: true, + stage_disabled: true, + reason_code: Some("stable_reason".into()), + failure_category: Some("timeout".into()), + }], + ); + let json = events[0].to_json().unwrap().to_string(); + for forbidden in [ + "secret-response-body", + "authorization", + "content-length", + "middleware said secret", + "stable_reason", + ] { + assert!(!json.contains(forbidden), "{json}"); + } + assert!( + json.to_ascii_lowercase() + .contains("http_response_middleware"), + "{json}" + ); + assert!(json.contains("example/scan"), "{json}"); + } + + #[test] + fn response_middleware_fail_open_dual_emits_sanitized_findings() { + let target = HttpRequestTarget { + scheme: "https".into(), + host: "example.test".into(), + port: 443, + method: "GET".into(), + path: "/safe".into(), + query: String::new(), + }; + for category in [ + "invalid_result", + "timeout", + "payload_capacity", + "session_capacity", + ] { + let invocation = openshell_supervisor_middleware::HttpResponseInvocation { + config_name: "scan".into(), + implementation: "example/scan".into(), + outcome: openshell_supervisor_middleware::HttpResponseInvocationOutcome::FailOpen, + sequence: Some(1), + input_size: 19, + output_size: None, + failed: true, + stage_disabled: true, + reason_code: None, + failure_category: Some(category.into()), + }; + assert_eq!( + http_response_middleware_invocation_events( + "policy", + &target, + 200, + std::slice::from_ref(&invocation), + ) + .len(), + 1 + ); + let finding = + http_response_middleware_fail_open_finding_event("policy", &target, &invocation) + .expect("fail-open failure must create a detection finding") + .to_json() + .unwrap() + .to_string(); + for expected in [ + "openshell.middleware.http_response_fail_open", + "example.test", + "pre_return", + category, + ] { + assert!(finding.contains(expected), "{finding}"); + } + assert!(!finding.contains("stable_reason"), "{finding}"); + } + } + + #[tokio::test] + async fn relay_response_no_framing_with_connection_close_reads_until_eof() { + // Response with Connection: close but no Content-Length/TE: body is + // delimited by connection close — relay_until_eof should forward it. + let response = b"HTTP/1.1 200 OK\r\nConnection: close\r\nServer: test\r\n\r\nhello world"; + + let (mut upstream_read, mut upstream_write) = tokio::io::duplex(4096); + let (mut client_read, mut client_write) = tokio::io::duplex(4096); + + tokio::spawn(async move { + upstream_write.write_all(response).await.unwrap(); + upstream_write.shutdown().await.unwrap(); }); let result = tokio::time::timeout( @@ -6093,21 +7215,30 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await .expect("relay_response should not deadlock"); - assert!(matches!( - result.expect("relay_response should succeed"), - RelayOutcome::Consumed - )); + let outcome = result.expect("relay_response should succeed"); + assert!( + matches!(outcome, RelayOutcome::Consumed), + "connection consumed by read-until-EOF" + ); + client_write.shutdown().await.unwrap(); let mut received = Vec::new(); client_read.read_to_end(&mut received).await.unwrap(); - let received = String::from_utf8_lossy(&received); - assert!(received.contains("Connection: close")); - assert!(received.contains("{\"ok\":true}")); + let received_str = String::from_utf8_lossy(&received); + assert!( + received_str.contains("Connection: close"), + "should preserve Connection: close" + ); + assert!( + received_str.contains("hello world"), + "body should be forwarded" + ); } #[tokio::test] @@ -6130,6 +7261,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6180,6 +7312,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6224,6 +7357,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6265,6 +7399,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6303,6 +7438,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6343,6 +7479,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6387,6 +7524,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6430,6 +7568,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6466,6 +7605,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6512,6 +7652,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -6559,6 +7700,7 @@ mod tests { &mut upstream_read, &mut client_write, RelayResponseOptions::default(), + None, ), ) .await @@ -8645,4 +9787,35 @@ mod tests { SigV4PayloadMode::UnsignedPayload ); } + + #[test] + fn response_body_transform_strips_stale_integrity_headers() { + let mut headers = [ + "accept-ranges", + "etag", + "content-md5", + "digest", + "content-digest", + "repr-digest", + "signature", + "signature-input", + "content-type", + ] + .into_iter() + .map(|name| HttpHeader { + name: name.to_string(), + value: "value".to_string(), + }) + .collect(); + + strip_response_integrity_headers(&mut headers); + + assert_eq!( + headers, + vec![HttpHeader { + name: "content-type".to_string(), + value: "value".to_string(), + }] + ); + } } diff --git a/crates/openshell-supervisor-network/src/l7/rest/http_response.rs b/crates/openshell-supervisor-network/src/l7/rest/http_response.rs new file mode 100644 index 0000000000..9a04244282 --- /dev/null +++ b/crates/openshell-supervisor-network/src/l7/rest/http_response.rs @@ -0,0 +1,2169 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! HTTP response relay and pre-return middleware integration. + +use super::*; + +/// Default wall-clock bound shared by whole-body stages in one response. +pub const DEFAULT_HTTP_RESPONSE_WHOLE_BODY_TIMEOUT: std::time::Duration = + std::time::Duration::from_mins(2); + +/// Context retained from request evaluation for the matching response hook. +pub struct HttpResponseMiddlewareRelay<'a> { + pub(crate) chain: &'a [openshell_supervisor_middleware::ChainEntry], + pub(crate) runner: &'a openshell_supervisor_middleware::ChainRunner, + pub(crate) request_context: RequestContext, + pub(crate) target: HttpRequestTarget, + pub(crate) policy_name: &'a str, + pub(crate) generation_guard: Option<&'a PolicyGenerationGuard>, + pub(crate) whole_body_timeout: std::time::Duration, +} + +#[derive(Clone)] +pub(super) struct RelayResponseOptions<'a> { + pub(super) websocket_extensions: WebSocketExtensionMode, + pub(super) client_requested_upgrade: bool, + pub(super) websocket: Option, + pub(super) observer: Option<&'a EndpointObserver>, +} + +impl Default for RelayResponseOptions<'_> { + fn default() -> Self { + Self { + websocket_extensions: WebSocketExtensionMode::Preserve, + client_requested_upgrade: true, + websocket: None, + observer: None, + } + } +} + +pub(super) async fn relay_response( + request_method: &str, + upstream: &mut U, + client: &mut C, + options: RelayResponseOptions<'_>, + response_middleware: Option>, +) -> Result +where + U: AsyncRead + Unpin, + C: AsyncWrite + Unpin, +{ + let started_at = std::time::Instant::now(); + let mut buf = Vec::with_capacity(4096); + let mut tmp = [0u8; 1024]; + + // Forward interim responses unchanged, but retain the final response head + // until response middleware preflight completes. + let mut informational_header_bytes = 0; + let header_end = loop { + let header_end = buf + .windows(4) + .position(|w| w == b"\r\n\r\n") + .map(|end| end + 4); + let remaining_header_bytes = MAX_HEADER_BYTES - informational_header_bytes; + if header_end.is_some_and(|end| end > remaining_header_bytes) + || (header_end.is_none() && buf.len() >= remaining_header_bytes) + { + if let Some(observer) = options.observer.as_ref() { + observer.observe(EndpointResult::TransportFailed); + } + return Err(miette!("HTTP response headers exceed limit")); + } + + if let Some(header_end) = header_end { + let header_str = String::from_utf8_lossy(&buf[..header_end]); + if matches!( + parse_observed_http_status_code(&header_str), + Some(100 | 102..=199) + ) { + informational_header_bytes += header_end; + client + .write_all(&buf[..header_end]) + .await + .into_diagnostic()?; + client.flush().await.into_diagnostic()?; + buf.drain(..header_end); + continue; + } + break header_end; + } + + let n = upstream.read(&mut tmp).await.into_diagnostic()?; + if n == 0 { + if let Some(observer) = options.observer.as_ref() { + observer.observe(EndpointResult::TransportFailed); + } + if !buf.is_empty() { + client.write_all(&buf).await.into_diagnostic()?; + } + return Ok(RelayOutcome::Consumed); + } + buf.extend_from_slice(&tmp[..n]); + }; + + // Parse response framing + let header_str = String::from_utf8_lossy(&buf[..header_end]); + let observed_status = parse_observed_http_status_code(&header_str); + if let Some(observer) = options.observer.as_ref() { + match observed_status { + Some(status_code) if status_code < 400 => { + observer.observe(EndpointResult::HttpResponseReceived); + } + Some(_) => observer.observe(EndpointResult::UpstreamRejected), + None => observer.observe(EndpointResult::TransportFailed), + } + } + let status_code = parse_status_code(&header_str).unwrap_or(200); + let server_wants_close = parse_connection_close(&header_str); + let http_10_closes_by_default = + response_is_http_10(&header_str) && !parse_connection_keep_alive(&header_str); + let event_stream = response_is_event_stream(&header_str); + let body_length = parse_body_length(&header_str)?; + + debug!( + status_code, + ?body_length, + server_wants_close, + request_method, + overflow_bytes = buf.len() - header_end, + "relay_response framing" + ); + + // 101 Switching Protocols: the connection has been upgraded (e.g. to + // WebSocket). Forward the 101 headers to the client and signal the + // caller to switch to raw bidirectional TCP relay. Any bytes read + // from upstream beyond the headers are overflow that belong to the + // upgraded protocol and must be forwarded before switching. + if status_code == 101 { + if !options.client_requested_upgrade { + return Ok(RelayOutcome::Consumed); + } + let (websocket_permessage_deflate, websocket_subprotocol) = validate_websocket_response( + &header_str, + options.websocket_extensions, + options.websocket.as_ref(), + )?; + client + .write_all(&buf[..header_end]) + .await + .into_diagnostic()?; + client.flush().await.into_diagnostic()?; + let overflow = buf[header_end..].to_vec(); + debug!( + request_method, + overflow_bytes = overflow.len(), + "101 Switching Protocols — signaling protocol upgrade" + ); + return Ok(RelayOutcome::Upgraded { + overflow, + websocket_permessage_deflate, + websocket_subprotocol, + }); + } + + if let Some(response_middleware) = response_middleware + && let Some(outcome) = Box::pin(relay_response_through_middleware( + request_method, + upstream, + client, + response_middleware, + &buf, + header_end, + status_code, + body_length, + server_wants_close || http_10_closes_by_default, + event_stream, + )) + .await? + { + return Ok(outcome); + } + + // Bodiless responses (HEAD, 1xx, 204, 304): forward headers only, skip body + if is_bodiless_response(request_method, status_code) { + client + .write_all(&buf[..header_end]) + .await + .into_diagnostic()?; + client.flush().await.into_diagnostic()?; + return if server_wants_close { + Ok(RelayOutcome::Consumed) + } else { + Ok(RelayOutcome::Reusable) + }; + } + + // No explicit framing (no Content-Length, no Transfer-Encoding). + // Per RFC 7230 §3.3.3 the body is delimited by connection close. + if matches!(body_length, BodyLength::None) { + if server_wants_close || http_10_closes_by_default || event_stream { + // Server indicated it will close, or this is a streaming response + // such as SSE where the body is intentionally delimited by EOF. + let before_end = &buf[..header_end - 2]; + client.write_all(before_end).await.into_diagnostic()?; + if server_wants_close || http_10_closes_by_default { + client + .write_all(b"Connection: close\r\n\r\n") + .await + .into_diagnostic()?; + } else { + client.write_all(b"\r\n").await.into_diagnostic()?; + } + let overflow = &buf[header_end..]; + if !overflow.is_empty() { + client.write_all(overflow).await.into_diagnostic()?; + client.flush().await.into_diagnostic()?; + } + if event_stream { + relay_until_eof_without_idle_timeout(upstream, client).await?; + } else { + relay_until_eof(upstream, client).await?; + } + client.flush().await.into_diagnostic()?; + client.shutdown().await.into_diagnostic()?; + return Ok(RelayOutcome::Consumed); + } + // No Connection: close — an HTTP/1.1 keep-alive server that omits + // framing headers has an empty body. Forward headers and continue + // the relay loop instead of blocking on relay_until_eof. + debug!("BodyLength::None without Connection: close — treating body as empty"); + client + .write_all(&buf[..header_end]) + .await + .into_diagnostic()?; + client.flush().await.into_diagnostic()?; + return Ok(RelayOutcome::Reusable); + } + + // Forward response headers + any overflow body bytes + client.write_all(&buf).await.into_diagnostic()?; + let overflow_len = (buf.len() - header_end) as u64; + + // Forward remaining response body + match body_length { + BodyLength::ContentLength(len) => { + let remaining = len.saturating_sub(overflow_len); + if remaining > 0 { + relay_fixed(upstream, client, remaining, None).await?; + } + } + BodyLength::Chunked => { + relay_chunked(upstream, client, &buf[header_end..], None).await?; + } + BodyLength::None => unreachable!(), + } + client.flush().await.into_diagnostic()?; + debug!( + request_method, + elapsed_ms = started_at.elapsed().as_millis(), + "relay_response complete (explicit framing)" + ); + + // When body framing is explicit (Content-Length / Chunked), always report + // the connection as reusable so the relay loop continues. If the server + // sent `Connection: close`, the *next* upstream write will fail and the + // loop will exit via the normal error path. Exiting early here would + // tear down the CONNECT tunnel before the client can detect the close, + // causing ~30 s retry delays in clients like `gh`. + Ok(RelayOutcome::Reusable) +} + +#[allow(clippy::too_many_arguments)] +async fn relay_response_through_middleware( + request_method: &str, + upstream: &mut U, + client: &mut C, + middleware: HttpResponseMiddlewareRelay<'_>, + buffered: &[u8], + header_end: usize, + status_code: u16, + body_length: BodyLength, + server_wants_close: bool, + event_stream: bool, +) -> Result> +where + U: AsyncRead + Unpin, + C: AsyncWrite + Unpin, +{ + if let Some(guard) = middleware.generation_guard { + guard.ensure_current()?; + } + let header_bytes = &buffered[..header_end]; + // Ordinary responses retain the HTTP parser's byte-preserving behavior. + // Response-specific normalization and limits apply only to selected hooks. + if middleware.chain.is_empty() { + return Ok(None); + } + let parsed = match middleware + .runner + .describe_http_response_chain(middleware.chain) + .await + { + Ok(described) if described.is_empty() => return Ok(None), + Ok(described) => { + parse_response_head_for_middleware(header_bytes).map(|parsed| (described, parsed)) + } + Err(error) => Err(error), + }; + if let Some(guard) = middleware.generation_guard { + guard.ensure_current()?; + } + let (described, parsed) = match parsed { + Ok(parsed) => parsed, + Err(error) => { + debug!(error = %error, "HTTP response head normalization failed"); + emit_http_response_middleware_failure( + middleware.policy_name, + &middleware.target, + status_code, + false, + ); + send_response_delivery_failure( + client, + request_method, + middleware.policy_name, + &middleware.target, + ) + .await?; + return Ok(Some(RelayOutcome::Consumed)); + } + }; + let original_headers = parsed.headers.clone(); + let preserved_credential_headers = parsed.preserved_credential_headers; + let upstream_declared_trailers = parsed.declared_trailers.clone(); + let connection_nominated_headers = parsed.connection_nominated.clone(); + let input = openshell_supervisor_middleware::HttpResponsePreflightInput { + context: middleware.request_context, + target: middleware.target.clone(), + status_code, + declared_body_length: match body_length { + BodyLength::ContentLength(length) => Some(length), + BodyLength::Chunked | BodyLength::None => None, + }, + headers: parsed.headers, + connection_nominated_headers: parsed.connection_nominated, + }; + let preflight_result = if parsed.representable { + middleware + .runner + .preflight_described_http_response(described, input) + .await + } else { + Ok(middleware + .runner + .http_response_input_unrepresentable(&described)) + }; + let mut preflight = match preflight_result { + Ok(preflight) => preflight, + Err(error) => { + debug!(error = %error, "HTTP response middleware preflight failed"); + emit_http_response_middleware_failure( + middleware.policy_name, + &middleware.target, + status_code, + false, + ); + send_response_delivery_failure( + client, + request_method, + middleware.policy_name, + &middleware.target, + ) + .await?; + return Ok(Some(RelayOutcome::Consumed)); + } + }; + if let Some(guard) = middleware.generation_guard + && let Err(error) = guard.ensure_current() + { + if let Some(session) = preflight.session.take() { + session + .end(openshell_core::proto::MiddlewareSessionEndReason::PolicyReload) + .await; + } + return Err(error); + } + debug!( + configured_stage_count = middleware.chain.len(), + active_session = preflight.session.is_some(), + allowed = preflight.allowed, + "HTTP response middleware preflight completed" + ); + for event in crate::l7::middleware::middleware_finding_events(&preflight.findings) { + openshell_ocsf::ocsf_emit!(event); + } + if !preflight.allowed { + emit_http_response_middleware_invocations( + middleware.policy_name, + &middleware.target, + status_code, + &preflight.invocations, + ); + if let Some(denial) = preflight.denial.as_ref() { + send_response_middleware_denial( + client, + request_method, + middleware.policy_name, + &middleware.target, + denial, + ) + .await?; + } else { + emit_http_response_middleware_failure( + middleware.policy_name, + &middleware.target, + status_code, + false, + ); + send_response_delivery_failure( + client, + request_method, + middleware.policy_name, + &middleware.target, + ) + .await?; + } + return Ok(Some(RelayOutcome::Consumed)); + } + emit_http_response_middleware_invocations( + middleware.policy_name, + &middleware.target, + status_code, + &preflight.invocations, + ); + + let Some(mut session) = preflight.session else { + if preflight.headers == original_headers { + return Ok(None); + } + let status_line = response_status_line(header_bytes)?; + let outcome = relay_headers_only_response( + request_method, + upstream, + client, + &status_line, + &preflight.headers, + &preserved_credential_headers, + &upstream_declared_trailers, + &buffered[header_end..], + status_code, + body_length, + server_wants_close, + event_stream, + ) + .await?; + return Ok(Some(outcome)); + }; + + let status_line = response_status_line(header_bytes)?; + let supports_chunked_response = !status_line.starts_with("HTTP/1.0 "); + let bodiless = is_bodiless_response(request_method, status_code); + if bodiless { + let finish = match session.finish(Vec::new()).await { + Ok(finish) => finish, + Err(error) => { + debug!(error = %error, "HTTP response middleware finalization failed"); + emit_http_response_diagnostics( + middleware.policy_name, + &middleware.target, + status_code, + &error.diagnostics, + ); + send_response_delivery_failure( + client, + request_method, + middleware.policy_name, + &middleware.target, + ) + .await?; + return Ok(Some(RelayOutcome::Consumed)); + } + }; + if let Some(guard) = middleware.generation_guard { + guard.ensure_current()?; + } + let mut headers = preflight.headers; + emit_http_response_middleware_invocations( + middleware.policy_name, + &middleware.target, + status_code, + &finish.invocations, + ); + for event in crate::l7::middleware::middleware_finding_events(&finish.findings) { + openshell_ocsf::ocsf_emit!(event); + } + if finish.strip_stale_integrity_headers { + strip_response_integrity_headers(&mut headers); + } + let head = serialize_response_head( + &status_line, + &headers, + &preserved_credential_headers, + ResponseFraming::Preserve(body_length), + server_wants_close, + &[], + ); + client.write_all(&head).await.into_diagnostic()?; + client.flush().await.into_diagnostic()?; + return Ok(Some(if server_wants_close { + RelayOutcome::Consumed + } else { + RelayOutcome::Reusable + })); + } + + let whole_body = session.requires_whole_body(); + if whole_body { + session.start_whole_body_deadline(middleware.whole_body_timeout); + } + let unit_limit = session.stream_unit_limit().max(1); + let chunked_output = supports_chunked_response; + let close_delimited_output = !supports_chunked_response; + let declared_trailers = upstream_declared_trailers; + let downstream_trailers = if chunked_output { + declared_trailers.as_slice() + } else { + &[] + }; + let streaming_head = serialize_response_head( + &status_line, + &preflight.headers, + &preserved_credential_headers, + if chunked_output { + ResponseFraming::Chunked + } else { + ResponseFraming::Preserve(BodyLength::None) + }, + server_wants_close || close_delimited_output, + downstream_trailers, + ); + let mut committed = !whole_body; + if committed { + if let Err(error) = client.write_all(&streaming_head).await { + session + .end(openshell_core::proto::MiddlewareSessionEndReason::DownstreamDisconnect) + .await; + return Err(error).into_diagnostic(); + } + if let Err(error) = client.flush().await { + session + .end(openshell_core::proto::MiddlewareSessionEndReason::DownstreamDisconnect) + .await; + return Err(error).into_diagnostic(); + } + } + + let mut reader = BufferedResponseReader::new(upstream, &buffered[header_end..]); + let body_result = relay_normalized_response_body( + &mut reader, + &mut session, + client, + body_length, + server_wants_close, + event_stream, + &mut committed, + chunked_output, + &streaming_head, + unit_limit, + middleware.generation_guard, + middleware.policy_name, + &middleware.target, + status_code, + &connection_nominated_headers, + ) + .await; + let trailers = match body_result { + Ok(trailers) => trailers, + Err(error) => { + let middleware_stop = error.downcast_ref::(); + let end_reason = if middleware + .generation_guard + .is_some_and(PolicyGenerationGuard::is_stale) + { + openshell_core::proto::MiddlewareSessionEndReason::PolicyReload + } else if error.downcast_ref::().is_some() { + openshell_core::proto::MiddlewareSessionEndReason::DownstreamDisconnect + } else if middleware_stop.is_some_and(|stop| stop.failure.denial.is_some()) { + openshell_core::proto::MiddlewareSessionEndReason::MiddlewareDenial + } else if middleware_stop.is_some() { + openshell_core::proto::MiddlewareSessionEndReason::MiddlewareFailure + } else { + openshell_core::proto::MiddlewareSessionEndReason::UpstreamDisconnect + }; + session.end(end_reason).await; + if committed { + emit_http_response_middleware_failure( + middleware.policy_name, + &middleware.target, + status_code, + true, + ); + return Err(error); + } + debug!(error = %error, "HTTP response processing failed before commitment"); + if let Some(denial) = middleware_stop.and_then(|stop| stop.failure.denial.as_ref()) { + send_response_middleware_denial( + client, + request_method, + middleware.policy_name, + &middleware.target, + denial, + ) + .await?; + } else { + emit_http_response_middleware_failure( + middleware.policy_name, + &middleware.target, + status_code, + false, + ); + send_response_delivery_failure( + client, + request_method, + middleware.policy_name, + &middleware.target, + ) + .await?; + } + return Ok(Some(RelayOutcome::Consumed)); + } + }; + + if let Some(guard) = middleware.generation_guard + && let Err(error) = guard.ensure_current() + { + session + .end(openshell_core::proto::MiddlewareSessionEndReason::PolicyReload) + .await; + return Err(error); + } + + let finish = match session.finish(trailers).await { + Ok(finish) => finish, + Err(error) => { + emit_http_response_diagnostics( + middleware.policy_name, + &middleware.target, + status_code, + &error.diagnostics, + ); + if committed { + emit_http_response_middleware_failure( + middleware.policy_name, + &middleware.target, + status_code, + true, + ); + return Err(miette!( + "HTTP response middleware failed after commitment: {error}" + )); + } + debug!(error = %error, "HTTP response middleware failed before commitment"); + if let Some(denial) = error.denial.as_ref() { + send_response_middleware_denial( + client, + request_method, + middleware.policy_name, + &middleware.target, + denial, + ) + .await?; + } else { + emit_http_response_middleware_failure( + middleware.policy_name, + &middleware.target, + status_code, + false, + ); + send_response_delivery_failure( + client, + request_method, + middleware.policy_name, + &middleware.target, + ) + .await?; + } + return Ok(Some(RelayOutcome::Consumed)); + } + }; + if let Some(guard) = middleware.generation_guard { + guard.ensure_current()?; + } + emit_http_response_middleware_invocations( + middleware.policy_name, + &middleware.target, + status_code, + &finish.invocations, + ); + for event in crate::l7::middleware::middleware_finding_events(&finish.findings) { + openshell_ocsf::ocsf_emit!(event); + } + + if whole_body && !committed { + let mut headers = preflight.headers; + if finish.strip_stale_integrity_headers { + strip_response_integrity_headers(&mut headers); + } + let output_length = finish + .body_units + .iter() + .try_fold(0usize, |total, unit| total.checked_add(unit.len())) + .ok_or_else(|| miette!("HTTP response middleware output length overflow"))?; + let framing = if finish.trailers.is_empty() || !supports_chunked_response { + ResponseFraming::ContentLength(output_length as u64) + } else { + ResponseFraming::Chunked + }; + let trailer_names: Vec = if supports_chunked_response { + finish + .trailers + .iter() + .map(|header| header.name.clone()) + .collect() + } else { + Vec::new() + }; + let head = serialize_response_head( + &status_line, + &headers, + &preserved_credential_headers, + framing, + server_wants_close, + &trailer_names, + ); + client.write_all(&head).await.into_diagnostic()?; + if matches!(framing, ResponseFraming::Chunked) { + for unit in &finish.body_units { + write_downstream_response_chunk(client, unit).await?; + } + write_response_trailers(client, &finish.trailers).await?; + } else { + for unit in &finish.body_units { + client.write_all(unit).await.into_diagnostic()?; + } + } + } else { + for unit in &finish.body_units { + if chunked_output { + write_downstream_response_chunk(client, unit).await?; + } else { + client.write_all(unit).await.into_diagnostic()?; + } + } + if chunked_output { + write_response_trailers(client, &finish.trailers).await?; + } + } + client.flush().await.into_diagnostic()?; + Ok(Some( + if (committed && close_delimited_output) + || (matches!(body_length, BodyLength::None) && (server_wants_close || event_stream)) + { + RelayOutcome::Consumed + } else { + RelayOutcome::Reusable + }, + )) +} + +#[allow(clippy::too_many_arguments)] +async fn relay_headers_only_response( + request_method: &str, + upstream: &mut U, + client: &mut C, + status_line: &str, + headers: &[HttpHeader], + preserved_credential_headers: &[String], + declared_trailers: &[String], + overflow: &[u8], + status_code: u16, + body_length: BodyLength, + server_wants_close: bool, + event_stream: bool, +) -> Result +where + U: AsyncRead + Unpin, + C: AsyncWrite + Unpin, +{ + let head = serialize_response_head( + status_line, + headers, + preserved_credential_headers, + ResponseFraming::Preserve(body_length), + server_wants_close, + declared_trailers, + ); + client.write_all(&head).await.into_diagnostic()?; + + if is_bodiless_response(request_method, status_code) { + client.flush().await.into_diagnostic()?; + return Ok(if server_wants_close { + RelayOutcome::Consumed + } else { + RelayOutcome::Reusable + }); + } + + client.write_all(overflow).await.into_diagnostic()?; + match body_length { + BodyLength::ContentLength(length) => { + let remaining = length.saturating_sub(overflow.len() as u64); + if remaining > 0 { + relay_fixed(upstream, client, remaining, None).await?; + } + } + BodyLength::Chunked => relay_chunked(upstream, client, overflow, None).await?, + BodyLength::None if server_wants_close || event_stream => { + if event_stream { + relay_until_eof_without_idle_timeout(upstream, client).await?; + } else { + relay_until_eof(upstream, client).await?; + } + client.flush().await.into_diagnostic()?; + return Ok(RelayOutcome::Consumed); + } + BodyLength::None => {} + } + client.flush().await.into_diagnostic()?; + Ok(RelayOutcome::Reusable) +} + +fn emit_http_response_middleware_invocations( + policy_name: &str, + target: &HttpRequestTarget, + status_code: u16, + invocations: &[openshell_supervisor_middleware::HttpResponseInvocation], +) { + for event in + http_response_middleware_invocation_events(policy_name, target, status_code, invocations) + { + openshell_ocsf::ocsf_emit!(event); + } + for invocation in invocations { + if let Some(event) = + http_response_middleware_fail_open_finding_event(policy_name, target, invocation) + { + openshell_ocsf::ocsf_emit!(event); + } + if let Some(event) = + http_response_middleware_block_finding_event(policy_name, target, invocation) + { + openshell_ocsf::ocsf_emit!(event); + } + } +} + +fn emit_http_response_diagnostics( + policy_name: &str, + target: &HttpRequestTarget, + status_code: u16, + diagnostics: &openshell_supervisor_middleware::HttpResponseDiagnostics, +) { + emit_http_response_middleware_invocations( + policy_name, + target, + status_code, + &diagnostics.invocations, + ); + for event in crate::l7::middleware::middleware_finding_events(&diagnostics.findings) { + openshell_ocsf::ocsf_emit!(event); + } +} + +pub(super) fn http_response_middleware_invocation_events( + policy_name: &str, + target: &HttpRequestTarget, + status_code: u16, + invocations: &[openshell_supervisor_middleware::HttpResponseInvocation], +) -> Vec { + invocations + .iter() + .map(|invocation| { + let outcome = format!("{:?}", invocation.outcome).to_ascii_lowercase(); + let failed = invocation.failed; + let blocked = invocation.outcome + == openshell_supervisor_middleware::HttpResponseInvocationOutcome::BlockDelivery; + openshell_ocsf::HttpActivityBuilder::new(ocsf_ctx()) + .activity(openshell_ocsf::ActivityId::Other) + .action(if blocked { + openshell_ocsf::ActionId::Denied + } else if failed { + openshell_ocsf::ActionId::Other + } else { + openshell_ocsf::ActionId::Allowed + }) + .disposition(if blocked { + openshell_ocsf::DispositionId::Blocked + } else if failed { + openshell_ocsf::DispositionId::Error + } else { + openshell_ocsf::DispositionId::Allowed + }) + .severity(if failed || blocked { + openshell_ocsf::SeverityId::Medium + } else { + openshell_ocsf::SeverityId::Informational + }) + .status(if failed || blocked { + openshell_ocsf::StatusId::Failure + } else { + openshell_ocsf::StatusId::Success + }) + .http_request(openshell_ocsf::HttpRequest::new( + &target.method, + openshell_ocsf::Url::new( + &target.scheme, + &target.host, + &target.path, + u16::try_from(target.port).unwrap_or_default(), + ), + )) + .http_response(openshell_ocsf::HttpResponse { code: status_code }) + .dst_endpoint(openshell_ocsf::Endpoint::from_domain( + &target.host, + u16::try_from(target.port).unwrap_or_default(), + )) + .firewall_rule(policy_name, "supervisor-middleware") + .unmapped("middleware_config", invocation.config_name.as_str()) + .unmapped( + "middleware_implementation", + invocation.implementation.as_str(), + ) + .unmapped("response_middleware_outcome", outcome.as_str()) + .unmapped("sequence", invocation.sequence.unwrap_or_default()) + .unmapped("input_bytes", invocation.input_size) + .unmapped("failed", failed) + .message(format!( + "HTTP_RESPONSE_MIDDLEWARE config={} implementation={} outcome={} sequence={} input_bytes={} failed={failed}", + invocation.config_name, + invocation.implementation, + outcome, + invocation.sequence.unwrap_or_default(), + invocation.input_size, + )) + .build() + }) + .collect() +} + +fn http_response_middleware_block_finding_event( + policy_name: &str, + target: &HttpRequestTarget, + invocation: &openshell_supervisor_middleware::HttpResponseInvocation, +) -> Option { + if invocation.outcome + != openshell_supervisor_middleware::HttpResponseInvocationOutcome::BlockDelivery + { + return None; + } + Some( + openshell_ocsf::DetectionFindingBuilder::new(ocsf_ctx()) + .severity(openshell_ocsf::SeverityId::Medium) + .finding_info(openshell_ocsf::FindingInfo::new( + "openshell.middleware.http_response_blocked", + "HTTP response blocked by middleware", + )) + .evidence_pairs(&[ + ("policy", policy_name), + ("middleware_config", invocation.config_name.as_str()), + ( + "middleware_implementation", + invocation.implementation.as_str(), + ), + ("host", target.host.as_str()), + ("phase", "pre_return"), + ]) + .unmapped("middleware_config", invocation.config_name.as_str()) + .unmapped( + "middleware_implementation", + invocation.implementation.as_str(), + ) + .unmapped("phase", "pre_return") + .message("HTTP response delivery blocked by middleware") + .build(), + ) +} + +pub(super) fn http_response_middleware_fail_open_finding_event( + policy_name: &str, + target: &HttpRequestTarget, + invocation: &openshell_supervisor_middleware::HttpResponseInvocation, +) -> Option { + if !invocation.failed + || invocation.outcome + != openshell_supervisor_middleware::HttpResponseInvocationOutcome::FailOpen + { + return None; + } + let failure_category = invocation + .failure_category + .as_deref() + .unwrap_or("middleware_failure"); + Some( + openshell_ocsf::DetectionFindingBuilder::new(ocsf_ctx()) + .severity(openshell_ocsf::SeverityId::Medium) + .finding_info(openshell_ocsf::FindingInfo::new( + "openshell.middleware.http_response_fail_open", + "HTTP response middleware failed open", + )) + .evidence_pairs(&[ + ("policy", policy_name), + ("middleware_config", invocation.config_name.as_str()), + ( + "middleware_implementation", + invocation.implementation.as_str(), + ), + ("host", target.host.as_str()), + ("phase", "pre_return"), + ("failure_category", failure_category), + ]) + .unmapped("middleware_config", invocation.config_name.as_str()) + .unmapped( + "middleware_implementation", + invocation.implementation.as_str(), + ) + .unmapped("phase", "pre_return") + .unmapped("failure_category", failure_category) + .message("HTTP response middleware failed and response inspection was bypassed") + .build(), + ) +} + +fn emit_http_response_middleware_failure( + policy_name: &str, + target: &HttpRequestTarget, + status_code: u16, + committed: bool, +) { + let status_code = status_code.to_string(); + let event = openshell_ocsf::DetectionFindingBuilder::new(ocsf_ctx()) + .severity(openshell_ocsf::SeverityId::High) + .finding_info(openshell_ocsf::FindingInfo::new( + "openshell.middleware.http_response_failure", + "HTTP response middleware delivery failure", + )) + .evidence_pairs(&[ + ("policy", policy_name), + ("host", target.host.as_str()), + ( + "commitment", + if committed { + "after_commit" + } else { + "before_commit" + }, + ), + ("upstream_status", status_code.as_str()), + ]) + .message(if committed { + "HTTP response middleware failed after response commitment" + } else { + "HTTP response middleware failed before response commitment" + }) + .build(); + openshell_ocsf::ocsf_emit!(event); +} + +#[derive(Debug)] +struct ParsedResponseHead { + representable: bool, + headers: Vec, + preserved_credential_headers: Vec, + connection_nominated: Vec, + declared_trailers: Vec, +} + +fn parse_response_head_for_middleware(header_bytes: &[u8]) -> Result { + // Lossy decoding preserves ASCII syntax and control bytes for validation. + // Never pass replacement text to middleware or use it for delivery. + let header = String::from_utf8_lossy(header_bytes); + let representable = std::str::from_utf8(header_bytes).is_ok(); + if parse_status_code(&header).is_none() { + return Err(miette!("HTTP response status line is malformed")); + } + let mut nominated = HashSet::new(); + let mut declared_trailers = Vec::new(); + for line in header.split("\r\n").skip(1) { + let Some((name, value)) = line.split_once(':') else { + continue; + }; + validate_http_field_name(name)?; + validate_http_field_value(value.trim())?; + if name.eq_ignore_ascii_case("connection") { + for token in value + .split(',') + .map(str::trim) + .filter(|token| !token.is_empty()) + { + nominated.insert(token.to_ascii_lowercase()); + } + } else if name.eq_ignore_ascii_case("trailer") { + for token in parse_http_token_list(value)? { + let token = token.to_ascii_lowercase(); + if !declared_trailers.contains(&token) { + declared_trailers.push(token); + } + } + } + } + for trailer in &declared_trailers { + if is_protected_response_field(trailer) || nominated.contains(trailer) { + return Err(miette!("HTTP response declares a protected trailer field")); + } + } + let mut headers = Vec::new(); + let mut preserved_credential_headers = Vec::new(); + for line in header.split("\r\n").skip(1).filter(|line| !line.is_empty()) { + let (name, value) = line + .split_once(':') + .ok_or_else(|| miette!("Malformed HTTP response header field"))?; + validate_http_field_name(name)?; + validate_http_field_value(value.trim())?; + let name = name.to_ascii_lowercase(); + if openshell_supervisor_middleware::headers::is_response_credential_header(&name) { + // Middleware must not observe credential-bearing response fields. + // Keep the original line separately so downstream delivery retains + // its exact name, whitespace, and value bytes. + preserved_credential_headers.push(line.to_string()); + continue; + } + if nominated.contains(&name) || is_hidden_response_field(&name) { + continue; + } + headers.push(HttpHeader { + name, + value: value.trim().to_string(), + }); + } + let mut connection_nominated: Vec<_> = nominated.into_iter().collect(); + connection_nominated.sort(); + Ok(ParsedResponseHead { + representable, + headers: if representable { headers } else { Vec::new() }, + preserved_credential_headers: if representable { + preserved_credential_headers + } else { + Vec::new() + }, + connection_nominated, + declared_trailers, + }) +} + +fn validate_http_field_name(name: &str) -> Result<()> { + if name.is_empty() + || !name.bytes().all(|byte| { + byte.is_ascii_alphanumeric() + || matches!( + byte, + b'!' | b'#' + | b'$' + | b'%' + | b'&' + | b'\'' + | b'*' + | b'+' + | b'-' + | b'.' + | b'^' + | b'_' + | b'`' + | b'|' + | b'~' + ) + }) + { + return Err(miette!("HTTP response field name is malformed")); + } + Ok(()) +} + +fn validate_http_field_value(value: &str) -> Result<()> { + if value + .bytes() + .any(|byte| (byte < 0x20 && byte != b'\t') || byte == 0x7f) + { + return Err(miette!("HTTP response field value contains a control byte")); + } + Ok(()) +} + +fn is_protected_response_field(name: &str) -> bool { + name.eq_ignore_ascii_case("content-length") + || is_hidden_response_field(name) + || openshell_supervisor_middleware::headers::is_response_credential_header(name) +} + +fn is_hidden_response_field(name: &str) -> bool { + matches!( + name.to_ascii_lowercase().as_str(), + "connection" + | "keep-alive" + | "proxy-authenticate" + | "proxy-authorization" + | "proxy-connection" + | "te" + | "trailer" + | "transfer-encoding" + | "upgrade" + ) +} + +fn response_status_line(header_bytes: &[u8]) -> Result { + let line_end = header_bytes + .windows(2) + .position(|window| window == b"\r\n") + .ok_or_else(|| miette!("HTTP response status line is incomplete"))?; + std::str::from_utf8(&header_bytes[..line_end]) + .map(str::to_string) + .map_err(|_| miette!("HTTP response status line contains invalid UTF-8")) +} + +#[derive(Clone, Copy)] +enum ResponseFraming { + Preserve(BodyLength), + ContentLength(u64), + Chunked, +} + +fn serialize_response_head( + status_line: &str, + headers: &[HttpHeader], + preserved_credential_headers: &[String], + framing: ResponseFraming, + connection_close: bool, + trailer_names: &[String], +) -> Vec { + let mut output = format!("{status_line}\r\n"); + for header in headers { + // Content-Length is read-only middleware metadata. The relay emits the + // final framing exactly once from `framing` below. + if header.name.eq_ignore_ascii_case("content-length") { + continue; + } + output.push_str(&header.name); + output.push_str(": "); + output.push_str(&header.value); + output.push_str("\r\n"); + } + for header in preserved_credential_headers { + output.push_str(header); + output.push_str("\r\n"); + } + match framing { + ResponseFraming::Preserve(BodyLength::ContentLength(length)) + | ResponseFraming::ContentLength(length) => { + write!(&mut output, "Content-Length: {length}\r\n") + .expect("writing to a String cannot fail"); + } + ResponseFraming::Preserve(BodyLength::Chunked) | ResponseFraming::Chunked => { + output.push_str("Transfer-Encoding: chunked\r\n"); + } + ResponseFraming::Preserve(BodyLength::None) => {} + } + if !trailer_names.is_empty() { + output.push_str("Trailer: "); + output.push_str(&trailer_names.join(", ")); + output.push_str("\r\n"); + } + if connection_close { + output.push_str("Connection: close\r\n"); + } + output.push_str("\r\n"); + output.into_bytes() +} + +pub(super) fn strip_response_integrity_headers(headers: &mut Vec) { + headers.retain(|header| { + !openshell_supervisor_middleware::is_stale_http_response_integrity_header(&header.name) + }); +} + +struct BufferedResponseReader<'a, R> { + upstream: &'a mut R, + buffered: &'a [u8], + position: usize, + exact_buffer: Vec, + exact_target: Option, + line_buffer: Vec, +} + +impl<'a, R: AsyncRead + Unpin> BufferedResponseReader<'a, R> { + fn new(upstream: &'a mut R, buffered: &'a [u8]) -> Self { + Self { + upstream, + buffered, + position: 0, + exact_buffer: Vec::new(), + exact_target: None, + line_buffer: Vec::new(), + } + } + + async fn read_some(&mut self, limit: usize) -> Result>> { + if self.position < self.buffered.len() { + let end = self.position.saturating_add(limit).min(self.buffered.len()); + let data = self.buffered[self.position..end].to_vec(); + self.position = end; + return Ok(Some(data)); + } + let mut data = vec![0u8; limit.max(1)]; + let count = self.upstream.read(&mut data).await.into_diagnostic()?; + if count == 0 { + return Ok(None); + } + data.truncate(count); + Ok(Some(data)) + } + + async fn read_exact_vec(&mut self, length: usize) -> Result> { + match self.exact_target { + Some(target) if target != length => { + return Err(miette!("HTTP response reader exact-read state mismatch")); + } + None => { + self.exact_target = Some(length); + self.exact_buffer.reserve(length); + } + Some(_) => {} + } + while self.exact_buffer.len() < length { + let remaining = length - self.exact_buffer.len(); + let Some(data) = self.read_some(remaining).await? else { + return Err(miette!("HTTP response body ended unexpectedly")); + }; + self.exact_buffer.extend_from_slice(&data); + } + self.exact_target = None; + Ok(std::mem::take(&mut self.exact_buffer)) + } + + async fn read_line(&mut self) -> Result> { + loop { + let Some(byte) = self.read_some(1).await? else { + return Err(miette!("HTTP response ended before line terminator")); + }; + self.line_buffer.push(byte[0]); + if self.line_buffer.len() > MAX_HEADER_BYTES { + return Err(miette!("HTTP response line exceeds limit")); + } + if self.line_buffer.ends_with(b"\r\n") { + self.line_buffer.truncate(self.line_buffer.len() - 2); + return Ok(std::mem::take(&mut self.line_buffer)); + } + } + } +} + +#[allow(clippy::too_many_arguments)] +async fn relay_normalized_response_body( + reader: &mut BufferedResponseReader<'_, R>, + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + body_length: BodyLength, + server_wants_close: bool, + event_stream: bool, + committed: &mut bool, + chunked_output: bool, + commit_head: &[u8], + unit_limit: usize, + generation_guard: Option<&PolicyGenerationGuard>, + policy_name: &str, + target: &HttpRequestTarget, + status_code: u16, + connection_nominated_headers: &[String], +) -> Result> +where + R: AsyncRead + Unpin, + C: AsyncWrite + Unpin, +{ + let mut pending = Vec::with_capacity(unit_limit); + let mut framing = ResponseOutputState { + committed, + chunked: chunked_output, + commit_head, + generation_guard, + policy_name, + target, + status_code, + }; + match body_length { + BodyLength::ContentLength(mut remaining) => { + while remaining > 0 { + let length = usize::try_from(remaining) + .unwrap_or(unit_limit) + .min(unit_limit); + let unit = read_response_payload_with_deadline( + reader, + length, + !pending.is_empty(), + session, + client, + &mut framing, + ) + .await?; + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } + let partial = unit.len() < length; + remaining -= unit.len() as u64; + buffer_normalized_response_bytes( + session, + client, + &mut pending, + unit, + &mut framing, + unit_limit, + ) + .await?; + if partial { + flush_normalized_response_bytes( + session, + client, + std::mem::take(&mut pending), + &mut framing, + ) + .await?; + } + } + flush_normalized_response_bytes(session, client, pending, &mut framing).await?; + Ok(Vec::new()) + } + BodyLength::Chunked => { + let mut size_line = + read_response_line_with_deadline(reader, session, client, &mut framing).await?; + loop { + let size_line_text = std::str::from_utf8(&size_line) + .map_err(|_| miette!("Invalid UTF-8 in response chunk-size line"))?; + let size_token = size_line_text + .split(';') + .next() + .map(str::trim) + .unwrap_or_default(); + let chunk_size = usize::from_str_radix(size_token, 16) + .map_err(|_| miette!("Invalid HTTP response chunk size"))?; + if chunk_size == 0 { + flush_normalized_response_bytes(session, client, pending, &mut framing).await?; + return read_response_trailers( + reader, + session, + client, + &mut framing, + connection_nominated_headers, + ) + .await; + } + let mut remaining = chunk_size; + while remaining > 0 { + let length = remaining.min(unit_limit); + let unit = read_response_payload_with_deadline( + reader, + length, + !pending.is_empty(), + session, + client, + &mut framing, + ) + .await?; + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } + let partial = unit.len() < length; + remaining -= unit.len(); + buffer_normalized_response_bytes( + session, + client, + &mut pending, + unit, + &mut framing, + unit_limit, + ) + .await?; + if partial { + flush_normalized_response_bytes( + session, + client, + std::mem::take(&mut pending), + &mut framing, + ) + .await?; + } + } + let terminator = if let Ok(result) = + tokio::time::timeout(RESPONSE_UNIT_COALESCE_TIMEOUT, reader.read_exact_vec(2)) + .await + { + result? + } else { + flush_normalized_response_bytes( + session, + client, + std::mem::take(&mut pending), + &mut framing, + ) + .await?; + read_exact_response_with_deadline(reader, 2, session, client, &mut framing) + .await? + }; + if terminator != b"\r\n" { + return Err(miette!("HTTP response chunk is missing its terminator")); + } + size_line = if let Ok(line) = + tokio::time::timeout(RESPONSE_UNIT_COALESCE_TIMEOUT, reader.read_line()).await + { + line? + } else { + flush_normalized_response_bytes( + session, + client, + std::mem::take(&mut pending), + &mut framing, + ) + .await?; + read_response_line_with_deadline(reader, session, client, &mut framing).await? + }; + } + } + BodyLength::None if server_wants_close || event_stream => loop { + // Cancel only input acquisition, never expiry or client writes. + let wait = if pending.is_empty() { + if event_stream { + None + } else { + Some(RELAY_EOF_IDLE_TIMEOUT) + } + } else { + Some(RESPONSE_UNIT_COALESCE_TIMEOUT) + }; + let read_deadline = wait.map(|wait| tokio::time::Instant::now() + wait); + let whole_deadline = session.whole_body_deadline(); + let deadline = match (read_deadline, whole_deadline) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + let next = if let Some(deadline) = deadline { + if let Ok(result) = + tokio::time::timeout_at(deadline, reader.read_some(unit_limit)).await + { + result? + } else { + if whole_deadline.is_some_and(|d| d <= tokio::time::Instant::now()) { + expire_whole_body_deadline(session, client, &mut framing).await?; + } else if pending.is_empty() { + return Ok(Vec::new()); + } else { + flush_normalized_response_bytes( + session, + client, + std::mem::take(&mut pending), + &mut framing, + ) + .await?; + } + continue; + } + } else { + reader.read_some(unit_limit).await? + }; + let Some(unit) = next else { + flush_normalized_response_bytes(session, client, pending, &mut framing).await?; + return Ok(Vec::new()); + }; + if let Some(guard) = generation_guard { + guard.ensure_current()?; + } + buffer_normalized_response_bytes( + session, + client, + &mut pending, + unit, + &mut framing, + unit_limit, + ) + .await?; + }, + BodyLength::None => { + flush_normalized_response_bytes(session, client, pending, &mut framing).await?; + Ok(Vec::new()) + } + } +} + +struct ResponseOutputState<'a> { + committed: &'a mut bool, + chunked: bool, + commit_head: &'a [u8], + generation_guard: Option<&'a PolicyGenerationGuard>, + policy_name: &'a str, + target: &'a HttpRequestTarget, + status_code: u16, +} + +#[derive(Debug)] +struct ResponseMiddlewareStop { + failure: openshell_supervisor_middleware::HttpResponseMiddlewareFailure, +} + +impl ResponseMiddlewareStop { + fn new(failure: openshell_supervisor_middleware::HttpResponseMiddlewareFailure) -> Self { + Self { failure } + } +} + +impl fmt::Display for ResponseMiddlewareStop { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "HTTP response middleware stopped delivery: {}", + self.failure + ) + } +} + +impl std::error::Error for ResponseMiddlewareStop {} + +impl miette::Diagnostic for ResponseMiddlewareStop {} + +#[derive(Debug)] +struct ResponseDownstreamWrite(std::io::Error); + +impl fmt::Display for ResponseDownstreamWrite { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "HTTP response client write failed: {}", self.0) + } +} + +impl std::error::Error for ResponseDownstreamWrite { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + Some(&self.0) + } +} + +impl miette::Diagnostic for ResponseDownstreamWrite {} + +async fn expire_whole_body_deadline( + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + framing: &mut ResponseOutputState<'_>, +) -> Result<()> { + let output = session.expire_whole_body_deadline().await; + if let Some(guard) = framing.generation_guard { + guard.ensure_current()?; + } + let diagnostics = session.take_diagnostics(); + emit_http_response_diagnostics( + framing.policy_name, + framing.target, + framing.status_code, + &diagnostics, + ); + let output = output.map_err(ResponseMiddlewareStop::new)?; + deliver_response_units(client, output, framing, session.requires_whole_body()).await +} + +// Unit size is a maximum. Coalesce available payload without waiting for +// the rest of a transfer chunk, and finish expiry outside read timeouts. +async fn read_response_payload_with_deadline( + reader: &mut BufferedResponseReader<'_, R>, + limit: usize, + has_pending: bool, + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + framing: &mut ResponseOutputState<'_>, +) -> Result> +where + R: AsyncRead + Unpin, + C: AsyncWrite + Unpin, +{ + let mut payload = Vec::new(); + let mut coalesce_deadline = + has_pending.then(|| tokio::time::Instant::now() + RESPONSE_UNIT_COALESCE_TIMEOUT); + loop { + let whole_deadline = session.whole_body_deadline(); + let deadline = match (coalesce_deadline, whole_deadline) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + let read = reader.read_some(limit - payload.len()); + let result = if let Some(deadline) = deadline { + if let Ok(result) = tokio::time::timeout_at(deadline, read).await { + result + } else { + if whole_deadline.is_some_and(|d| d <= tokio::time::Instant::now()) { + expire_whole_body_deadline(session, client, framing).await?; + } + if coalesce_deadline.is_some_and(|d| d <= tokio::time::Instant::now()) { + return Ok(payload); + } + continue; + } + } else { + read.await + }; + let data = result?.ok_or_else(|| miette!("HTTP response body ended unexpectedly"))?; + payload.extend_from_slice(&data); + if payload.len() == limit { + return Ok(payload); + } + coalesce_deadline + .get_or_insert_with(|| tokio::time::Instant::now() + RESPONSE_UNIT_COALESCE_TIMEOUT); + } +} + +async fn read_exact_response_with_deadline( + reader: &mut BufferedResponseReader<'_, R>, + length: usize, + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + framing: &mut ResponseOutputState<'_>, +) -> Result> +where + R: AsyncRead + Unpin, + C: AsyncWrite + Unpin, +{ + loop { + let Some(deadline) = session.whole_body_deadline() else { + return reader.read_exact_vec(length).await; + }; + match tokio::time::timeout_at(deadline, reader.read_exact_vec(length)).await { + Ok(result) => return result, + Err(_) => expire_whole_body_deadline(session, client, framing).await?, + } + } +} + +async fn read_response_line_with_deadline( + reader: &mut BufferedResponseReader<'_, R>, + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + framing: &mut ResponseOutputState<'_>, +) -> Result> +where + R: AsyncRead + Unpin, + C: AsyncWrite + Unpin, +{ + loop { + let Some(deadline) = session.whole_body_deadline() else { + return reader.read_line().await; + }; + match tokio::time::timeout_at(deadline, reader.read_line()).await { + Ok(result) => return result, + Err(_) => expire_whole_body_deadline(session, client, framing).await?, + } + } +} + +async fn buffer_normalized_response_bytes( + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + pending: &mut Vec, + data: Vec, + framing: &mut ResponseOutputState<'_>, + unit_limit: usize, +) -> Result<()> { + pending.extend_from_slice(&data); + while pending.len() >= unit_limit { + let remainder = pending.split_off(unit_limit); + let unit = std::mem::replace(pending, remainder); + process_response_unit(session, client, unit, framing).await?; + } + Ok(()) +} + +async fn flush_normalized_response_bytes( + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + pending: Vec, + framing: &mut ResponseOutputState<'_>, +) -> Result<()> { + if pending.is_empty() { + return Ok(()); + } + process_response_unit(session, client, pending, framing).await +} + +async fn process_response_unit( + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + unit: Vec, + framing: &mut ResponseOutputState<'_>, +) -> Result<()> { + let output = session.push_body(unit).await; + if let Some(guard) = framing.generation_guard { + guard.ensure_current()?; + } + let diagnostics = session.take_diagnostics(); + emit_http_response_diagnostics( + framing.policy_name, + framing.target, + framing.status_code, + &diagnostics, + ); + let output = output.map_err(ResponseMiddlewareStop::new)?; + deliver_response_units(client, output, framing, session.requires_whole_body()).await +} + +async fn deliver_response_units( + client: &mut C, + output: Vec>, + framing: &mut ResponseOutputState<'_>, + whole_body_pending: bool, +) -> Result<()> { + if !*framing.committed && !output.is_empty() { + if whole_body_pending { + return Err(miette!( + "whole-body response middleware released output before finalization" + )); + } + // `write_all` may return an error after a partial write. Treat the + // response as committed before the attempt so callers never append a + // canonical error response behind a partially delivered upstream head. + *framing.committed = true; + client + .write_all(framing.commit_head) + .await + .map_err(ResponseDownstreamWrite)?; + client.flush().await.map_err(ResponseDownstreamWrite)?; + } + if *framing.committed { + for unit in output { + if framing.chunked { + write_downstream_response_chunk(client, &unit).await?; + } else { + client + .write_all(&unit) + .await + .map_err(ResponseDownstreamWrite)?; + } + } + client.flush().await.map_err(ResponseDownstreamWrite)?; + } + Ok(()) +} + +async fn write_downstream_response_chunk( + client: &mut C, + payload: &[u8], +) -> Result<()> { + if payload.is_empty() { + return Ok(()); + } + client + .write_all(format!("{:X}\r\n", payload.len()).as_bytes()) + .await + .map_err(ResponseDownstreamWrite)?; + client + .write_all(payload) + .await + .map_err(ResponseDownstreamWrite)?; + client + .write_all(b"\r\n") + .await + .map_err(ResponseDownstreamWrite)?; + Ok(()) +} + +async fn read_response_trailers( + reader: &mut BufferedResponseReader<'_, R>, + session: &mut openshell_supervisor_middleware::HttpResponseSession, + client: &mut C, + framing: &mut ResponseOutputState<'_>, + connection_nominated_headers: &[String], +) -> Result> +where + R: AsyncRead + Unpin, + C: AsyncWrite + Unpin, +{ + let mut trailers = Vec::new(); + loop { + let line = read_response_line_with_deadline(reader, session, client, framing).await?; + if line.is_empty() { + return Ok(trailers); + } + let line = std::str::from_utf8(&line) + .map_err(|_| miette!("HTTP response trailer contains invalid UTF-8"))?; + let (name, value) = line + .split_once(':') + .ok_or_else(|| miette!("Malformed HTTP response trailer"))?; + validate_http_field_name(name)?; + validate_http_field_value(value.trim())?; + let name = name.to_ascii_lowercase(); + if is_protected_response_field(&name) || connection_nominated_headers.contains(&name) { + return Err(miette!("HTTP response trailer uses a protected field name")); + } + trailers.push(HttpHeader { + name, + value: value.trim().to_string(), + }); + if trailers.len() > openshell_supervisor_middleware::MAX_MIDDLEWARE_HEADERS { + return Err(miette!("HTTP response trailer count exceeds limit")); + } + } +} + +async fn write_response_trailers( + client: &mut C, + trailers: &[HttpHeader], +) -> Result<()> { + client.write_all(b"0\r\n").await.into_diagnostic()?; + for trailer in trailers { + client + .write_all(format!("{}: {}\r\n", trailer.name, trailer.value).as_bytes()) + .await + .into_diagnostic()?; + } + client.write_all(b"\r\n").await.into_diagnostic()?; + Ok(()) +} + +async fn send_response_middleware_denial( + client: &mut C, + request_method: &str, + policy_name: &str, + target: &HttpRequestTarget, + denial: &openshell_supervisor_middleware::MiddlewareDenial, +) -> Result<()> { + let mut body = serde_json::Map::new(); + body.insert("error".into(), serde_json::json!("middleware_denied")); + body.insert( + "detail".into(), + serde_json::json!("Response blocked by configured middleware"), + ); + body.insert("policy".into(), serde_json::json!(policy_name)); + body.insert("middleware".into(), serde_json::json!(denial.config_name)); + if let Some(reason_code) = &denial.reason_code { + body.insert("reason_code".into(), serde_json::json!(reason_code)); + } + body.insert( + "layer".into(), + serde_json::json!("http_response_pre_return"), + ); + body.insert("method".into(), serde_json::json!(target.method)); + body.insert("path".into(), serde_json::json!(target.path)); + body.insert("host".into(), serde_json::json!(target.host)); + body.insert("port".into(), serde_json::json!(target.port)); + let body = serde_json::to_vec(&serde_json::Value::Object(body)).into_diagnostic()?; + let head = format!( + "HTTP/1.1 403 Forbidden\r\nContent-Type: application/json\r\nContent-Length: {}\r\nX-OpenShell-Policy: {policy_name}\r\nConnection: close\r\n\r\n", + body.len() + ); + client.write_all(head.as_bytes()).await.into_diagnostic()?; + if !request_method.eq_ignore_ascii_case("HEAD") { + client.write_all(&body).await.into_diagnostic()?; + } + client.flush().await.into_diagnostic()?; + Ok(()) +} + +async fn send_response_delivery_failure( + client: &mut C, + request_method: &str, + policy_name: &str, + target: &HttpRequestTarget, +) -> Result<()> { + let body = serde_json::to_vec(&serde_json::json!({ + "error": "response_delivery_failed", + "detail": "The upstream request may have completed, but OpenShell could not deliver its response. Retrying may repeat upstream side effects.", + "policy": policy_name, + "layer": "http_response_pre_return", + "method": target.method, + "path": target.path, + "host": target.host, + "port": target.port, + })) + .into_diagnostic()?; + let head = format!( + "HTTP/1.1 502 Bad Gateway\r\nContent-Type: application/json\r\nContent-Length: {}\r\nX-OpenShell-Policy: {policy_name}\r\nConnection: close\r\n\r\n", + body.len() + ); + client.write_all(head.as_bytes()).await.into_diagnostic()?; + if !request_method.eq_ignore_ascii_case("HEAD") { + client.write_all(&body).await.into_diagnostic()?; + } + client.flush().await.into_diagnostic()?; + Ok(()) +} + +/// Parse the HTTP status code from a response status line. +/// +/// Expects the first line to look like `HTTP/1.1 200 OK`. +pub(super) fn parse_status_code(headers: &str) -> Option { + let status_line = headers.lines().next()?; + let code_str = status_line.split_whitespace().nth(1)?; + code_str.parse().ok() +} + +/// Parse a syntactically valid HTTP/1.x response status for endpoint reporting. +pub(super) fn parse_observed_http_status_code(headers: &str) -> Option { + let status_line = headers.lines().next()?; + let mut fields = status_line.split_whitespace(); + match fields.next()? { + "HTTP/1.0" | "HTTP/1.1" => {} + _ => return None, + } + let code = fields.next()?; + if code.len() != 3 || !code.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + code.parse() + .ok() + .filter(|status| (100..=999).contains(status)) +} + +/// Check if the response headers contain `Connection: close`. +pub(super) fn parse_connection_close(headers: &str) -> bool { + for line in headers.lines().skip(1) { + let lower = line.to_ascii_lowercase(); + if lower.starts_with("connection:") { + let val = lower.split_once(':').map_or("", |(_, v)| v.trim()); + return val.contains("close"); + } + } + false +} + +/// Check if an HTTP/1.0 response opts into a persistent connection. +pub(super) fn parse_connection_keep_alive(headers: &str) -> bool { + headers.lines().skip(1).any(|line| { + let lower = line.to_ascii_lowercase(); + lower + .strip_prefix("connection:") + .is_some_and(|value| value.split(',').any(|token| token.trim() == "keep-alive")) + }) +} + +pub(super) fn response_is_http_10(headers: &str) -> bool { + headers + .lines() + .next() + .and_then(|line| line.split_whitespace().next()) + == Some("HTTP/1.0") +} + +pub(super) fn response_is_event_stream(headers: &str) -> bool { + headers.lines().skip(1).any(|line| { + let lower = line.to_ascii_lowercase(); + let Some(value) = lower.strip_prefix("content-type:") else { + return false; + }; + value + .split(';') + .next() + .is_some_and(|mime| mime.trim() == "text/event-stream") + }) +} + +#[cfg(test)] +mod tests { + use super::{ + ResponseFraming, parse_connection_keep_alive, parse_response_head_for_middleware, + response_is_http_10, serialize_response_head, + }; + use crate::l7::provider::BodyLength; + use openshell_core::proto::HttpHeader; + + #[test] + fn http_10_connection_persistence() { + let default_close = "HTTP/1.0 200 OK\r\nServer: test\r\n\r\n"; + assert!(response_is_http_10(default_close)); + assert!(!parse_connection_keep_alive(default_close)); + + let keep_alive = "HTTP/1.0 200 OK\r\nConnection: keep-alive\r\n\r\n"; + assert!(response_is_http_10(keep_alive)); + assert!(parse_connection_keep_alive(keep_alive)); + } + + #[test] + fn response_middleware_preflight_keeps_read_only_content_length() { + let parsed = parse_response_head_for_middleware( + b"HTTP/1.1 206 Partial Content\r\n\ + Content-Length: 5\r\n\ + Content-Encoding: gzip\r\n\ + Content-Range: bytes 0-4/10\r\n\ + Connection: x-hop\r\n\ + X-Hop: omitted\r\n\r\n", + ) + .expect("parse response head"); + + assert_eq!( + parsed.headers, + vec![ + HttpHeader { + name: "content-length".into(), + value: "5".into(), + }, + HttpHeader { + name: "content-encoding".into(), + value: "gzip".into(), + }, + HttpHeader { + name: "content-range".into(), + value: "bytes 0-4/10".into(), + }, + ] + ); + + let nominated = parse_response_head_for_middleware( + b"HTTP/1.1 200 OK\r\nConnection: Content-Length\r\nContent-Length: 5\r\n\r\n", + ) + .expect("parse nominated response head"); + assert!(nominated.headers.is_empty()); + } + + #[test] + fn response_middleware_serializes_only_relay_owned_framing() { + let headers = vec![ + HttpHeader { + name: "content-length".into(), + value: "999".into(), + }, + HttpHeader { + name: "Content-Length".into(), + value: "998".into(), + }, + HttpHeader { + name: "content-type".into(), + value: "text/plain".into(), + }, + ]; + + for (framing, expected) in [ + ( + ResponseFraming::Preserve(BodyLength::ContentLength(5)), + Some("Content-Length: 5\r\n"), + ), + ( + ResponseFraming::ContentLength(9), + Some("Content-Length: 9\r\n"), + ), + (ResponseFraming::Chunked, None), + (ResponseFraming::Preserve(BodyLength::None), None), + ] { + let serialized = String::from_utf8(serialize_response_head( + "HTTP/1.1 200 OK", + &headers, + &[], + framing, + false, + &[], + )) + .expect("serialized response head"); + + assert_eq!( + serialized + .lines() + .filter(|line| line.to_ascii_lowercase().starts_with("content-length:")) + .count(), + usize::from(expected.is_some()) + ); + if let Some(expected) = expected { + assert!(serialized.contains(expected)); + } + if matches!(framing, ResponseFraming::Chunked) { + assert!(serialized.contains("Transfer-Encoding: chunked\r\n")); + } + } + } +} diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index a2237d5e4e..5a7056a79c 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -175,7 +175,7 @@ pub(crate) fn test_opa_query_count() -> u64 { } /// Generation guard captured when an HTTP tunnel or request path starts. -#[derive(Clone)] +#[derive(Clone, Debug)] pub struct PolicyGenerationGuard { captured_generation: u64, current_generation: Arc, @@ -714,7 +714,7 @@ impl OpaEngine { /// validation guarantees as initial load. Atomically replaces the inner /// engine on success; on failure the previous engine is untouched (LKG). pub fn reload_from_proto(&self, proto: &ProtoSandboxPolicy) -> Result<()> { - self.reload_from_proto_with_pid(proto, 0) + self.reload_from_proto_with_pid(proto, 0).map(|_| ()) } /// Reload policy from a proto with symlink resolution. @@ -722,11 +722,12 @@ impl OpaEngine { /// When `entrypoint_pid` is non-zero, binary paths that are symlinks /// inside the container filesystem are resolved and added as additional /// match entries. See [`from_proto_with_pid`] for details. + /// Returns evidence tied to the generation installed by this call. pub fn reload_from_proto_with_pid( &self, proto: &ProtoSandboxPolicy, entrypoint_pid: u32, - ) -> Result<()> { + ) -> Result { // Build a complete new engine through the same validated pipeline. let new = Self::from_proto_with_pid(proto, entrypoint_pid)?; let new_engine = new @@ -742,8 +743,10 @@ impl OpaEngine { .fail_closed_reason .write() .map_err(|_| miette::miette!("OPA fail-closed state lock poisoned"))? = None; - self.advance_generation(); - Ok(()) + let generation = self.advance_generation(); + // Capture evidence while the installation lock still excludes a + // competing reload; reading the generation later can bind the wrong policy. + self.generation_guard(generation) } /// Reload the policy and middleware registry as one runtime generation. @@ -752,12 +755,13 @@ impl OpaEngine { /// engine and runner are then swapped while holding both locks, followed by /// a single generation increment. A preparation or lock failure leaves the /// live pair and generation untouched. + /// Returns evidence tied to that combined installation. pub fn reload_policy_and_middleware_from_proto_with_pid( &self, proto: &ProtoSandboxPolicy, entrypoint_pid: u32, registry: MiddlewareRegistry, - ) -> Result<()> { + ) -> Result { let new = Self::from_proto_with_pid(proto, entrypoint_pid)?; let new_engine = new .engine @@ -780,8 +784,8 @@ impl OpaEngine { .fail_closed_reason .write() .map_err(|_| miette::miette!("OPA fail-closed state lock poisoned"))? = None; - self.advance_generation(); - Ok(()) + let generation = self.advance_generation(); + self.generation_guard(generation) } /// Publish a deny-all quarantine generation without activating any part @@ -10896,6 +10900,94 @@ network_policies: ); } + #[cfg(target_os = "linux")] + #[test] + fn exact_deny_symlink_expands_but_glob_deny_does_not() { + use std::os::unix::fs::symlink; + + if !procfs_root_accessible() { + eprintln!("Skipping: /proc//root/ not accessible in this environment"); + return; + } + + let link_dir = tempfile::tempdir().unwrap(); + let target_dir = tempfile::tempdir().unwrap(); + let target = target_dir.path().join("python3"); + let link = link_dir.path().join("python"); + std::fs::write(&target, b"python binary").unwrap(); + symlink(&target, &link).unwrap(); + + let target_path = target.to_string_lossy(); + let exact_link = link.to_string_lossy(); + let candidate_glob = format!("{}/*", link_dir.path().to_string_lossy()); + let policy = |deny_binary: &str| { + format!( + r#" +version: 1 +network_policies: + grant: + endpoints: + - host: example.com + port: 443 + protocol: rest + enforcement: enforce + rules: [{{ allow: {{ method: GET, path: "/**" }} }}] + binaries: [{{ path: "{target_path}" }}] + deny: + endpoints: + - host: example.com + port: 443 + protocol: rest + enforcement: enforce + rules: [{{ allow: {{ method: GET, path: "/**" }} }}] + deny_rules: [{{ method: "*", path: "/**" }}] + binaries: [{{ path: "{deny_binary}" }}] +filesystem_policy: + include_workdir: false + read_only: [] + read_write: [] +landlock: + compatibility: best_effort +process: + run_as_user: sandbox + run_as_group: sandbox +"# + ) + }; + + let maximum = openshell_policy::parse_sandbox_policy(&policy(&exact_link)) + .expect("maximum policy should parse"); + let candidate = openshell_policy::parse_sandbox_policy(&policy(&candidate_glob)) + .expect("candidate policy should parse"); + let pid = std::process::id(); + let maximum_engine = + OpaEngine::from_proto_with_pid(&maximum, pid).expect("maximum engine should load"); + let candidate_engine = + OpaEngine::from_proto_with_pid(&candidate, pid).expect("candidate engine should load"); + let input = serde_json::json!({ + "network": { "host": "example.com", "port": 443 }, + "exec": { + "path": target_path, + "ancestors": [], + "cmdline_paths": [] + }, + "request": { + "method": "GET", + "path": "/", + "query_params": {} + } + }); + + assert!( + eval_l7(&candidate_engine, &input), + "the candidate glob must not be resolved through the exact symlink" + ); + assert!( + !eval_l7(&maximum_engine, &input), + "the maximum exact deny must expand to the resolved target" + ); + } + #[cfg(target_os = "linux")] #[test] fn reload_from_proto_with_pid_resolves_symlinks() { diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 46c8f69cea..02206063a2 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -1530,8 +1530,7 @@ struct ForwardL7Reevaluation<'a> { struct ForwardMiddlewarePipeline<'a> { ctx: &'a crate::l7::relay::L7EvalContext, scheme: &'a str, - runner: &'a openshell_supervisor_middleware::ChainRunner, - generation_guard: &'a PolicyGenerationGuard, + exchange: &'a crate::l7::middleware::HttpMiddlewareExchange, l7_reevaluation: Option>, } @@ -1544,7 +1543,6 @@ impl ForwardMiddlewarePipeline<'_> { &self, request: crate::l7::provider::L7Request, client: &mut C, - chain: Vec, ) -> Result where C: TokioAsyncRead + TokioAsyncWrite + Unpin + Send, @@ -1563,17 +1561,15 @@ impl ForwardMiddlewarePipeline<'_> { None => openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, }; - crate::l7::middleware::apply_middleware_chain_for_scheme( - request, - client, - self.ctx, - self.scheme, - chain, - self.runner, - self.generation_guard, - transformed_body_policy, - ) - .await + self.exchange + .apply_request( + request, + client, + self.ctx, + self.scheme, + transformed_body_policy, + ) + .await } } @@ -4717,6 +4713,14 @@ struct ForwardRelayOptions<'a> { signing_region: &'a str, host: &'a str, port: u16, + response_middleware: Option>, + endpoint_observer: Option<&'a crate::l7::EndpointObserver>, +} + +struct ForwardResponseMiddleware<'a> { + ctx: &'a crate::l7::relay::L7EvalContext, + scheme: &'a str, + exchange: &'a crate::l7::middleware::HttpMiddlewareExchange, } async fn relay_rewritten_forward_request( @@ -4737,16 +4741,22 @@ where .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 (request_path, query_params) = crate::l7::rest::parse_target_query(path)?; let req = crate::l7::provider::L7Request { action: method.to_string(), - target: path.to_string(), + target: request_path, query_params, raw_header: rewritten, body_length, }; - crate::l7::rest::relay_http_request_with_options_guarded( + let response_middleware = options.response_middleware.map(|middleware| { + middleware + .exchange + .response_relay(&req, middleware.ctx, middleware.scheme) + }); + + crate::l7::rest::relay_http_request_with_response_middleware_guarded_observed( &req, client, upstream, @@ -4764,6 +4774,8 @@ where host: options.host, port: options.port, }, + response_middleware, + options.endpoint_observer, ) .await } @@ -5724,8 +5736,11 @@ async fn handle_forward_proxy( .await?; return Ok(()); } + let request_id = uuid::Uuid::new_v4().to_string(); let websocket_chain = forward_websocket_request.then(|| chain.clone()); - if !chain.is_empty() { + let response_selection = if chain.is_empty() { + None + } else { let middleware_runner = opa_engine.middleware_runner()?; let request = crate::l7::rest::request_from_buffered_http( method, @@ -5741,14 +5756,19 @@ async fn handle_forward_proxy( }), _ => None, }; + let middleware_exchange = crate::l7::middleware::HttpMiddlewareExchange::new( + request_id.clone(), + chain, + middleware_runner, + forward_generation_guard.clone(), + ); let pipeline = ForwardMiddlewarePipeline { ctx: &l7_ctx, scheme: &scheme, - runner: &middleware_runner, - generation_guard: &forward_generation_guard, + exchange: &middleware_exchange, l7_reevaluation, }; - forward_request_bytes = match pipeline.apply(request, client, chain).await? { + forward_request_bytes = match pipeline.apply(request, client).await? { crate::l7::middleware::MiddlewareApplyResult::Allowed(request) => request.raw_header, crate::l7::middleware::MiddlewareApplyResult::Denied { denial, .. } => { emit_activity_simple(activity_tx, true, "middleware"); @@ -5766,7 +5786,8 @@ async fn handle_forward_proxy( return Ok(()); } }; - } + Some(middleware_exchange) + }; let mut middleware_session = if let Some(chain) = websocket_chain.as_deref() { let request = crate::l7::rest::request_from_buffered_http( method, @@ -6103,6 +6124,14 @@ async fn handle_forward_proxy( signing_region, host: &host_lc, port, + response_middleware: response_selection.as_ref().map(|exchange| { + ForwardResponseMiddleware { + ctx: &l7_ctx, + scheme: &scheme, + exchange, + } + }), + endpoint_observer: endpoint_observer.as_ref(), }, ) .await; @@ -6731,6 +6760,118 @@ process: release: Arc, } + struct ForwardResponseHeadersMiddleware { + expected_path: String, + forbidden_path_fragment: String, + block: bool, + } + + #[tonic::async_trait] + impl openshell_core::middleware::InProcessMiddleware for ForwardResponseHeadersMiddleware { + async fn describe(&self) -> openshell_core::proto::MiddlewareManifest { + openshell_core::proto::MiddlewareManifest { + name: "test/forward-response".into(), + service_version: "test".into(), + bindings: vec![openshell_core::proto::MiddlewareBinding { + operation: openshell_core::proto::SupervisorMiddlewareOperation::HttpResponse + as i32, + phase: openshell_core::proto::SupervisorMiddlewarePhase::PreReturn as i32, + max_payload_bytes: 8192, + request_timeout: None, + }], + expected_audience: String::new(), + } + } + + async fn validate_config( + &self, + _middleware_name: &str, + _config: &prost_types::Struct, + ) -> Result<()> { + Ok(()) + } + + async fn evaluate_http_request( + &self, + _request: openshell_core::middleware::HttpRequestView<'_>, + ) -> Result { + Ok(openshell_core::proto::HttpRequestResult { + decision: openshell_core::proto::Decision::Allow as i32, + ..Default::default() + }) + } + + async fn open_http_response_pre_return( + &self, + mut requests: mpsc::Receiver, + ) -> std::result::Result + { + let (sender, receiver) = mpsc::channel(2); + let expected_path = self.expected_path.clone(); + let forbidden_path_fragment = self.forbidden_path_fragment.clone(); + let block = self.block; + tokio::spawn(async move { + while let Some(event) = requests.recv().await { + match event.event { + Some(openshell_core::proto::http_response_event::Event::Preflight( + preflight, + )) => { + let target = preflight.target.expect("response target"); + assert_eq!(target.path, expected_path); + assert!(!target.path.contains(&forbidden_path_fragment)); + let action = if block { + openshell_core::proto::http_response_preflight_result::Action::BlockDelivery( + openshell_core::proto::HttpResponseBlockDelivery {}, + ) + } else { + openshell_core::proto::http_response_preflight_result::Action::Inspect( + openshell_core::proto::HttpResponsePreflightInspect { + body_mode: openshell_core::proto::HttpResponseBodyMode::HeadersOnly as i32, + header_mutations: vec![openshell_core::proto::HeaderMutation { + operation: Some( + openshell_core::proto::header_mutation::Operation::Write( + openshell_core::proto::WriteHeader { + name: "x-forward-response-test".into(), + value: "selected".into(), + on_existing: openshell_core::proto::ExistingHeaderAction::Overwrite as i32, + }, + ), + ), + }], + }, + ) + }; + let result = openshell_core::proto::HttpResponseEventResult { + result: Some( + openshell_core::proto::http_response_event_result::Result::PreflightResult( + openshell_core::proto::HttpResponsePreflightResult { + action: Some(action), + reason_code: if block { + "query_guard".into() + } else { + String::new() + }, + ..Default::default() + }, + ), + ), + }; + if sender.send(Ok(result)).await.is_err() { + break; + } + } + Some(openshell_core::proto::http_response_event::Event::SessionEnd(_)) + | None => break, + Some(_) => panic!("headers-only response received an unexpected event"), + } + } + }); + Ok(Box::pin(tokio_stream::wrappers::ReceiverStream::new( + receiver, + ))) + } + } + #[tonic::async_trait] impl openshell_core::middleware::InProcessMiddleware for BlockingForwardMiddleware { async fn describe(&self) -> openshell_core::proto::MiddlewareManifest { @@ -6998,7 +7139,7 @@ network_policies: let mut proxy_connection: ProxyClient = tokio::io::BufReader::new(Box::new(proxy_connection)); - tokio::time::timeout( + Box::pin(tokio::time::timeout( std::time::Duration::from_secs(30), Box::pin(handle_forward_proxy( "POST", @@ -7022,7 +7163,7 @@ network_policies: None, None, )), - ) + )) .await .expect("MCP forwarding should complete") .expect("handle valid MCP request"); @@ -7993,6 +8134,7 @@ network_policies: }, ); let snapshot = ProviderCredentialSnapshot { + installation_id: String::new(), revision: 42, child_env: std::collections::HashMap::new(), dynamic_credentials, @@ -8174,28 +8316,33 @@ network_policies: .next() .expect("built-in middleware service"), ); + let chain = vec![openshell_supervisor_middleware::ChainEntry { + name: "redactor".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }]; + let exchange = crate::l7::middleware::HttpMiddlewareExchange::new( + "test-request-id".into(), + chain, + runner, + tunnel_engine.generation_guard().clone(), + ); let pipeline = ForwardMiddlewarePipeline { ctx: &ctx, scheme: "http", - runner: &runner, - generation_guard: tunnel_engine.generation_guard(), + exchange: &exchange, l7_reevaluation: Some(ForwardL7Reevaluation { config: &config, engine: &tunnel_engine, request_info: &request_info, }), }; - let chain = vec![openshell_supervisor_middleware::ChainEntry { - name: "redactor".into(), - implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), - order: 0, - config: prost_types::Struct::default(), - on_error: openshell_supervisor_middleware::OnError::FailClosed, - }]; let (_app, mut client) = tokio::io::duplex(8192); let outcome = pipeline - .apply(request, &mut client, chain) + .apply(request, &mut client) .await .expect("forward middleware pipeline"); @@ -8272,13 +8419,6 @@ network_policies: canonicalize_forward_host_header(raw, "api.example.test").unwrap(), ) .unwrap(); - let pipeline = ForwardMiddlewarePipeline { - ctx: &ctx, - scheme: "http", - runner: &runner, - generation_guard: &guard, - l7_reevaluation: None, - }; let chain = vec![openshell_supervisor_middleware::ChainEntry { name: "blocker".into(), implementation: "test/blocking-forward".into(), @@ -8286,13 +8426,25 @@ network_policies: config: prost_types::Struct::default(), on_error: openshell_supervisor_middleware::OnError::FailClosed, }]; + let exchange = crate::l7::middleware::HttpMiddlewareExchange::new( + "test-request-id".into(), + chain, + runner, + guard.clone(), + ); + let pipeline = ForwardMiddlewarePipeline { + ctx: &ctx, + scheme: "http", + exchange: &exchange, + l7_reevaluation: None, + }; let (_app, mut client) = tokio::io::duplex(8192); let revoke = async { entered.notified().await; state.revoke_static_provider_environment(2); release.notify_one(); }; - let (outcome, ()) = tokio::join!(pipeline.apply(request, &mut client, chain), revoke); + let (outcome, ()) = tokio::join!(pipeline.apply(request, &mut client), revoke); let request = match outcome.expect("middleware pipeline") { crate::l7::middleware::MiddlewareApplyResult::Allowed(request) => request, crate::l7::middleware::MiddlewareApplyResult::Denied { .. } => { @@ -8405,6 +8557,183 @@ network_policies: .unwrap() } + #[tokio::test] + async fn plaintext_forward_relay_applies_response_middleware() { + let guard = forward_test_guard(); + let ctx = crate::l7::relay::L7EvalContext { + host: "api.example.test".into(), + port: 80, + request_default_port: Some(80), + policy_name: "forward".into(), + binary_path: "/usr/bin/curl".into(), + ..Default::default() + }; + let runner = openshell_supervisor_middleware::ChainRunner::new(Arc::new( + ForwardResponseHeadersMiddleware { + expected_path: "/demo".into(), + forbidden_path_fragment: "not-present".into(), + block: false, + }, + )); + let chain = vec![openshell_supervisor_middleware::ChainEntry { + name: "response".into(), + implementation: "test/forward-response".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }]; + let exchange = crate::l7::middleware::HttpMiddlewareExchange::new( + "correlated-request-id".into(), + chain, + runner, + guard.clone(), + ); + let request = b"GET /demo HTTP/1.1\r\nHost: api.example.test\r\n\r\n".to_vec(); + let (mut proxy_to_upstream, mut upstream) = tokio::io::duplex(8192); + let (mut app, mut proxy_to_client) = tokio::io::duplex(8192); + let upstream_task = tokio::spawn(async move { + let mut request = vec![0; 1024]; + let size = upstream.read(&mut request).await.unwrap(); + assert!(request[..size].ends_with(b"\r\n\r\n")); + upstream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") + .await + .unwrap(); + }); + + let outcome = relay_rewritten_forward_request( + "GET", + "/demo", + request, + &mut proxy_to_client, + &mut proxy_to_upstream, + ForwardRelayOptions { + body_classifier: None, + generation_guard: &guard, + credential_generation: None, + websocket_extensions: crate::l7::rest::WebSocketExtensionMode::Preserve, + secret_resolver: None, + request_body_credential_rewrite: false, + deny_uninspected_credentials: false, + credential_signing: crate::l7::CredentialSigning::None, + signing_service: "", + signing_region: "", + host: "api.example.test", + port: 80, + response_middleware: Some(ForwardResponseMiddleware { + ctx: &ctx, + scheme: "http", + exchange: &exchange, + }), + endpoint_observer: None, + }, + ) + .await + .expect("plaintext forward relay"); + assert!(matches!( + outcome, + crate::l7::provider::RelayOutcome::Reusable + )); + upstream_task.await.unwrap(); + drop(proxy_to_client); + let mut response = Vec::new(); + app.read_to_end(&mut response).await.unwrap(); + let response = String::from_utf8(response).unwrap(); + assert!(response.contains("x-forward-response-test: selected\r\n")); + assert!(response.ends_with("\r\n\r\nok")); + } + + #[tokio::test] + async fn plaintext_forward_response_denial_never_echoes_query_secret() { + const SECRET: &str = "sk-forward-query-secret"; + let guard = forward_test_guard(); + let ctx = crate::l7::relay::L7EvalContext { + host: "api.example.test".into(), + port: 80, + request_default_port: Some(80), + policy_name: "forward".into(), + binary_path: "/usr/bin/curl".into(), + ..Default::default() + }; + let runner = openshell_supervisor_middleware::ChainRunner::new(Arc::new( + ForwardResponseHeadersMiddleware { + expected_path: "/demo".into(), + forbidden_path_fragment: SECRET.into(), + block: true, + }, + )); + let chain = vec![openshell_supervisor_middleware::ChainEntry { + name: "response".into(), + implementation: "test/forward-response".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }]; + let exchange = crate::l7::middleware::HttpMiddlewareExchange::new( + "correlated-request-id".into(), + chain, + runner, + guard.clone(), + ); + let target = format!("/demo?access_token={SECRET}"); + let request = + format!("GET {target} HTTP/1.1\r\nHost: api.example.test\r\n\r\n").into_bytes(); + let (mut proxy_to_upstream, mut upstream) = tokio::io::duplex(8192); + let (mut app, mut proxy_to_client) = tokio::io::duplex(8192); + let upstream_task = tokio::spawn(async move { + let mut request = vec![0; 1024]; + let size = upstream.read(&mut request).await.unwrap(); + assert!(request[..size].ends_with(b"\r\n\r\n")); + upstream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") + .await + .unwrap(); + }); + + let outcome = relay_rewritten_forward_request( + "GET", + &target, + request, + &mut proxy_to_client, + &mut proxy_to_upstream, + ForwardRelayOptions { + body_classifier: None, + generation_guard: &guard, + credential_generation: None, + websocket_extensions: crate::l7::rest::WebSocketExtensionMode::Preserve, + secret_resolver: None, + request_body_credential_rewrite: false, + deny_uninspected_credentials: false, + credential_signing: crate::l7::CredentialSigning::None, + signing_service: "", + signing_region: "", + host: "api.example.test", + port: 80, + response_middleware: Some(ForwardResponseMiddleware { + ctx: &ctx, + scheme: "http", + exchange: &exchange, + }), + endpoint_observer: None, + }, + ) + .await + .expect("plaintext forward response denial"); + assert!(matches!( + outcome, + crate::l7::provider::RelayOutcome::Consumed + )); + upstream_task.await.unwrap(); + drop(proxy_to_client); + let mut response = Vec::new(); + app.read_to_end(&mut response).await.unwrap(); + let response = String::from_utf8(response).unwrap(); + assert!(response.starts_with("HTTP/1.1 403 Forbidden\r\n")); + assert!(response.contains("\"path\":\"/demo\"")); + assert!(!response.contains(SECRET)); + assert!(!response.contains("access_token")); + } + async fn relay_forward_request_and_capture( method: &str, path: &str, @@ -8502,6 +8831,8 @@ network_policies: signing_region: "", host: "", port: 0, + response_middleware: None, + endpoint_observer: None, }, ) .await?; @@ -8767,6 +9098,8 @@ network_policies: signing_region: "", host: "", port: 0, + response_middleware: None, + endpoint_observer: None, }, ) .await?; @@ -10921,13 +11254,6 @@ network_policies: .expect("built-in middleware service"), ); let guard = forward_test_guard(); - let pipeline = ForwardMiddlewarePipeline { - ctx: &ctx, - scheme: "http", - runner: &runner, - generation_guard: &guard, - l7_reevaluation: None, - }; let chain = vec![openshell_supervisor_middleware::ChainEntry { name: "redactor".into(), implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), @@ -10935,10 +11261,22 @@ network_policies: config: prost_types::Struct::default(), on_error: openshell_supervisor_middleware::OnError::FailClosed, }]; + let exchange = crate::l7::middleware::HttpMiddlewareExchange::new( + "test-request-id".into(), + chain, + runner, + guard, + ); + let pipeline = ForwardMiddlewarePipeline { + ctx: &ctx, + scheme: "http", + exchange: &exchange, + l7_reevaluation: None, + }; let (_app, mut client) = tokio::io::duplex(8192); let allowed = pipeline - .apply(request, &mut client, chain) + .apply(request, &mut client) .await .expect("middleware pipeline"); let crate::l7::middleware::MiddlewareApplyResult::Allowed(request) = allowed else { @@ -11308,6 +11646,8 @@ network_policies: signing_region: "", host: "", port: 0, + response_middleware: None, + endpoint_observer: None, }, ) .await @@ -11390,6 +11730,8 @@ network_policies: signing_region: "us-west-2", host: "api.example.com", port: 80, + response_middleware: None, + endpoint_observer: None, }, ) .await @@ -11479,6 +11821,8 @@ network_policies: signing_region: "", host: "", port: 0, + response_middleware: None, + endpoint_observer: None, }, ) .await; @@ -11530,6 +11874,8 @@ network_policies: signing_region: "", host: "", port: 0, + response_middleware: None, + endpoint_observer: None, }, ) .await; diff --git a/crates/openshell-supervisor-network/src/run.rs b/crates/openshell-supervisor-network/src/run.rs index 024185d1ac..533ee2b2eb 100644 --- a/crates/openshell-supervisor-network/src/run.rs +++ b/crates/openshell-supervisor-network/src/run.rs @@ -274,7 +274,7 @@ pub async fn run_networking( "Container filesystem accessible, resolving policy binary symlinks" ); match resolve_engine.reload_from_proto_with_pid(&resolve_proto, pid) { - Ok(()) => { + Ok(_) => { info!( pid = pid, "Policy binary symlink resolution complete \ diff --git a/crates/openshell-supervisor-process/src/supervisor_session.rs b/crates/openshell-supervisor-process/src/supervisor_session.rs index 32cbc2d1ee..1ddfd734e3 100644 --- a/crates/openshell-supervisor-process/src/supervisor_session.rs +++ b/crates/openshell-supervisor-process/src/supervisor_session.rs @@ -394,6 +394,7 @@ async fn run_single_session( payload: Some(supervisor_message::Payload::Hello(SupervisorHello { sandbox_id: config.sandbox_id.clone(), instance_id: config.instance_id.clone(), + supports_provider_readiness: true, })), }) .await diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index e05da07067..b13849939d 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -19,6 +19,7 @@ mod activity_aggregator; mod denial_aggregator; mod endpoint_status; mod mechanistic_mapper; +mod provider_readiness; use miette::{IntoDiagnostic, Result, WrapErr}; use std::future::Future; @@ -268,10 +269,12 @@ async fn wait_for_control_shutdown_signal() { use openshell_core::denial::DenialEvent; use openshell_core::policy::{NetworkMode, NetworkPolicy, ProxyPolicy, SandboxPolicy}; use openshell_core::proposals::AgentProposals; +use openshell_core::proto::ProviderReadinessReason; use openshell_core::provider_credentials::ProviderCredentialState; -use openshell_supervisor_network::opa::OpaEngine; +use openshell_supervisor_network::opa::{OpaEngine, PolicyGenerationGuard}; use openshell_supervisor_network::proxy::ProxyHandle; use openshell_supervisor_process::skills; +use provider_readiness::{EnvironmentIdentity, Tracker as ProviderReadinessTracker}; use tokio::sync::mpsc::UnboundedSender; use tokio::time::timeout; @@ -638,18 +641,12 @@ pub async fn run_sandbox( // guest account data against the host's /etc/passwd and /etc/group. let workspace = workdir; + let provider_readiness = ProviderReadinessTracker::new(); let provider_credentials = { // Fetch provider environment variables from the server. // This is done after loading the policy so the sandbox can still start // even if provider env fetch fails (graceful degradation). - let ( - provider_env_revision, - provider_env, - provider_credential_expires_at_ms, - dynamic_credentials, - static_credential_bindings, - non_secret_environment_keys, - ) = if let (Some(id), Some(endpoint)) = (&sandbox_id, &openshell_endpoint) { + let environment = if let (Some(id), Some(endpoint)) = (&sandbox_id, &openshell_endpoint) { match openshell_core::grpc_client::fetch_provider_environment(endpoint, id).await { Ok(result) => { ocsf_emit!( @@ -663,14 +660,7 @@ pub async fn run_sandbox( )) .build() ); - ( - result.provider_env_revision, - result.environment, - result.credential_expires_at_ms, - result.dynamic_credentials, - result.static_credential_bindings, - result.non_secret_environment_keys, - ) + Some(result) } Err(e) => { ocsf_emit!( @@ -683,56 +673,24 @@ pub async fn run_sandbox( )) .build() ); - ( - 0, - std::collections::HashMap::new(), - std::collections::HashMap::new(), - std::collections::HashMap::new(), - std::collections::HashMap::new(), - Vec::new(), - ) + None } } } else { - ( - 0, - std::collections::HashMap::new(), - std::collections::HashMap::new(), - std::collections::HashMap::new(), - std::collections::HashMap::new(), - Vec::new(), - ) + None }; - let dynamic_credentials_fallback = dynamic_credentials.clone(); - match ProviderCredentialState::from_bound_environment( - provider_env_revision, - provider_env, - provider_credential_expires_at_ms, - dynamic_credentials, - static_credential_bindings, - non_secret_environment_keys, - ) { - Ok(credentials) => credentials, - Err(error) => { - ocsf_emit!( - ConfigStateChangeBuilder::new(ocsf_ctx()) - .severity(SeverityId::High) - .status(StatusId::Failure) - .state(StateId::Disabled, "fail_closed") - .message(format!( - "Rejected provider environment bindings; static provider credentials were revoked; fetched dynamic token grants remain active: {error}" - )) - .build() - ); + environment.map_or_else( + || { ProviderCredentialState::from_environment( - provider_env_revision, - std::collections::HashMap::new(), - std::collections::HashMap::new(), - dynamic_credentials_fallback, + 0, + std::collections::HashMap::default(), + std::collections::HashMap::default(), + std::collections::HashMap::default(), ) - } - } + }, + |result| initial_provider_credentials(result, &provider_readiness), + ) }; if credential_gating_unavailable( @@ -1043,6 +1001,7 @@ pub async fn run_sandbox( interval_secs: poll_interval_secs, ocsf_enabled: poll_ocsf_enabled, provider_credentials: poll_provider_credentials, + provider_readiness: provider_readiness.clone(), policy_local_ctx: poll_policy_local, agent_proposals: agent_proposals.clone(), middleware_registry_status, @@ -1057,7 +1016,7 @@ pub async fn run_sandbox( endpoint_observation_tx, endpoint_status_rx, endpoint_policy: poll_endpoint_policy, - supervisor_session_id, + supervisor_session_id: supervisor_session_id.clone(), }; tokio::spawn(async move { @@ -1111,6 +1070,19 @@ pub async fn run_sandbox( ) .await?; info!(backend = %backend_name, "Control-mode access plane started"); + let _provider_reporter = + sandbox_id + .as_ref() + .zip(openshell_endpoint.as_ref()) + .map(|(id, endpoint)| { + provider_readiness.start_reporter( + endpoint.clone(), + id.clone(), + provider_credentials.clone(), + supervisor_session_id.clone(), + running.exec(), + ) + }); let mut control_readiness = if let Some(path) = health_socket_path { Some(ControlReadiness::start( path, @@ -2579,7 +2551,7 @@ async fn reload_gateway_policy_runtime( entrypoint_pid: u32, middleware: MiddlewareReloadContext<'_>, transparent_tcp: TransparentTcpReloadState, -) -> std::result::Result<(), GatewayRuntimeReloadError> { +) -> std::result::Result { if let Some(policy) = policy && policy_contains_explicit_tcp(policy) { @@ -2815,7 +2787,7 @@ fn initial_policy_ack_candidate( } if loaded.version != canonical.version || loaded.policy_hash != canonical.policy_hash - || canonical.config_revision < loaded.config_revision + || canonical.config_revision != loaded.config_revision { return None; } @@ -2922,6 +2894,64 @@ fn report_credential_gating_unavailable() { ); } +/// Install the first gateway snapshot before passing placeholders to the workload. +/// Invalid static bindings leave only independently authorized dynamic grants active. +fn initial_provider_credentials( + result: openshell_core::grpc_client::ProviderEnvironmentResult, + readiness: &ProviderReadinessTracker, +) -> ProviderCredentialState { + let identity = EnvironmentIdentity::from_environment(&result); + let expires_at_ms = result + .credential_expires_at_ms + .values() + .copied() + .filter(|expiry| *expiry > 0) + .min(); + if result.readiness_reason != ProviderReadinessReason::Unspecified { + readiness.credentials_failed(identity, result.readiness_reason); + return ProviderCredentialState::from_environment( + result.provider_env_revision, + std::collections::HashMap::default(), + std::collections::HashMap::default(), + result.dynamic_credentials, + ); + } + let dynamic_credentials_fallback = result.dynamic_credentials.clone(); + match ProviderCredentialState::from_bound_environment( + result.provider_env_revision, + result.environment, + result.credential_expires_at_ms, + result.dynamic_credentials, + result.static_credential_bindings, + result.non_secret_environment_keys, + ) { + Ok(credentials) => { + readiness.credentials_installed(identity, &credentials, expires_at_ms); + credentials + } + Err(error) => { + readiness + .credentials_failed(identity, ProviderReadinessReason::CredentialInstallFailed); + ocsf_emit!( + ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::High) + .status(StatusId::Failure) + .state(StateId::Disabled, "fail_closed") + .message(format!( + "Rejected provider environment bindings; static provider credentials were revoked; fetched dynamic token grants remain active: {error}" + )) + .build() + ); + ProviderCredentialState::from_environment( + result.provider_env_revision, + std::collections::HashMap::new(), + std::collections::HashMap::new(), + dynamic_credentials_fallback, + ) + } + } +} + /// Deliver policy status updates independently from policy reconciliation. /// /// The channel is FIFO, so a delayed older status can never arrive after a @@ -2950,6 +2980,15 @@ trait PolicyGatewayClient: Clone + Send + Sync + 'static { Ok(()) } + /// Fetch the complete provider snapshot through the ordinary static-binding API. + async fn fetch_provider_environment( + &self, + endpoint: &str, + sandbox_id: &str, + ) -> Result { + openshell_core::grpc_client::fetch_provider_environment(endpoint, sandbox_id).await + } + async fn refresh_installed_extension_credentials(&self) -> Result<()> { Ok(()) } @@ -3160,6 +3199,7 @@ struct PolicyPollLoopContext { interval_secs: u64, ocsf_enabled: Arc, provider_credentials: ProviderCredentialState, + provider_readiness: ProviderReadinessTracker, policy_local_ctx: Option>, agent_proposals: AgentProposals, middleware_registry_status: MiddlewareRegistryStatus, @@ -3590,6 +3630,7 @@ async fn run_policy_poll_loop_with_client( let mut current_provider_env_revision: u64 = ctx.provider_credentials.snapshot().revision; let mut current_policy_version: u32 = 0; let mut current_policy_hash = String::new(); + let mut current_policy_generation = None; let mut current_endpoint_policy = ctx.endpoint_policy.clone(); let mut current_middleware_services = Vec::new(); let mut current_extension_authentication_enabled = ctx.extension_authentication_enabled; @@ -3607,6 +3648,12 @@ async fn run_policy_poll_loop_with_client( // pass through the normal reconciliation path immediately. It must never // seed the applied-state trackers before OPA actually loads it. let mut pending_result = None; + // Bind startup evidence before awaiting the gateway. A generation changed + // during that request no longer proves which policy startup installed. + let initial_generation = ctx + .opa_engine + .generation_guard(ctx.opa_engine.current_generation()) + .ok(); // Initialize revision from the first poll and acknowledge the initial // policy revision the supervisor actually loaded. A mismatched result is @@ -3614,8 +3661,20 @@ async fn run_policy_poll_loop_with_client( match client.poll_settings(&ctx.sandbox_id).await { Ok(result) => { let _ = ctx.workspace_tx.send(client.workspace()); - match initial_poll_disposition(&ctx.loaded_policy_origin, &result) { - InitialPollDisposition::Acknowledge(candidate) => { + match ( + initial_poll_disposition(&ctx.loaded_policy_origin, &result), + initial_generation.as_ref(), + ) { + (InitialPollDisposition::Acknowledge(candidate), Some(generation)) + if middleware_registry_status == MiddlewareRegistryStatus::Synchronized + && !generation.is_stale() => + { + ctx.provider_readiness.policy_activated( + &EnvironmentIdentity::from_settings(&result), + result.config_revision, + generation.clone(), + ); + current_policy_generation = Some(generation.clone()); apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); apply_agent_proposals_enabled( &ctx.agent_proposals, @@ -3648,8 +3707,12 @@ async fn run_policy_poll_loop_with_client( "Settings poll: initial policy matches loaded revision" ); } - InitialPollDisposition::Reconcile => pending_result = Some(result), - InitialPollDisposition::TrackOnly => { + (InitialPollDisposition::Acknowledge(_) | InitialPollDisposition::Reconcile, _) => { + // Matching policy bytes cannot prove an unavailable registry + // or a replaced generation. Install this snapshot immediately. + pending_result = Some(result); + } + (InitialPollDisposition::TrackOnly, _) => { apply_ocsf_json_setting(&ctx.ocsf_enabled, &result.settings); apply_agent_proposals_enabled( &ctx.agent_proposals, @@ -3723,7 +3786,9 @@ async fn run_policy_poll_loop_with_client( }; let config_changed = result.config_revision != current_config_revision; - let provider_env_changed = result.provider_env_revision != current_provider_env_revision; + let desired_identity = EnvironmentIdentity::from_settings(&result); + let provider_env_changed = result.provider_env_revision != current_provider_env_revision + || ctx.provider_readiness.needs_environment(&desired_identity); let policy_changed = result.policy_hash != current_policy_hash; let extension_authentication_changed = current_extension_authentication_enabled != result.extension_authentication_enabled; @@ -3742,6 +3807,10 @@ async fn run_policy_poll_loop_with_client( .as_ref() .is_some_and(|rejected| rejected.policy_hash != result.policy_hash); let policy_runtime_changed = recovering_rejected_policy + || (reloads_gateway_policy + && current_policy_generation + .as_ref() + .is_some_and(PolicyGenerationGuard::is_stale)) || extension_authentication_changed || gateway_policy_runtime_needs_reconciliation( reloads_gateway_policy, @@ -3841,24 +3910,38 @@ async fn run_policy_poll_loop_with_client( } if provider_env_changed { - match openshell_core::grpc_client::fetch_provider_environment( - &ctx.endpoint, - &ctx.sandbox_id, - ) - .await + ctx.provider_readiness.credentials_failed( + desired_identity.clone(), + ProviderReadinessReason::WaitingForCredentials, + ); + match client + .fetch_provider_environment(&ctx.endpoint, &ctx.sandbox_id) + .await { Ok(env_result) => { - let provider_env_revision = env_result.provider_env_revision; - let install_result = ctx.provider_credentials.install_bound_environment( - provider_env_revision, - env_result.environment, - env_result.credential_expires_at_ms, - env_result.dynamic_credentials, - env_result.static_credential_bindings, - env_result.non_secret_environment_keys, - ); - if let Err(error) = install_result { - ocsf_emit!( + let identity = EnvironmentIdentity::from_environment(&env_result); + let expires_at_ms = env_result + .credential_expires_at_ms + .values() + .copied() + .filter(|expiry| *expiry > 0) + .min(); + if env_result.readiness_reason == ProviderReadinessReason::Unspecified { + let provider_env_revision = env_result.provider_env_revision; + let install_result = ctx.provider_credentials.install_bound_environment( + provider_env_revision, + env_result.environment, + env_result.credential_expires_at_ms, + env_result.dynamic_credentials, + env_result.static_credential_bindings, + env_result.non_secret_environment_keys, + ); + if let Err(error) = install_result { + ctx.provider_readiness.credentials_failed( + identity, + ProviderReadinessReason::CredentialInstallFailed, + ); + ocsf_emit!( ConfigStateChangeBuilder::new(ocsf_ctx()) .severity(SeverityId::High) .status(StatusId::Failure) @@ -3868,11 +3951,16 @@ async fn run_policy_poll_loop_with_client( )) .build() ); - } else { - let env_count = - ctx.provider_credentials.child_env_with_gcp_resolved().len(); - current_provider_env_revision = provider_env_revision; - ocsf_emit!( + } else { + ctx.provider_readiness.credentials_installed( + identity, + &ctx.provider_credentials, + expires_at_ms, + ); + let env_count = + ctx.provider_credentials.child_env_with_gcp_resolved().len(); + current_provider_env_revision = provider_env_revision; + ocsf_emit!( ConfigStateChangeBuilder::new(ocsf_ctx()) .severity(SeverityId::Informational) .status(StatusId::Success) @@ -3886,9 +3974,19 @@ async fn run_policy_poll_loop_with_client( )) .build() ); + } + } else { + ctx.provider_credentials + .revoke_static_provider_environment(env_result.provider_env_revision); + ctx.provider_readiness + .credentials_failed(identity, env_result.readiness_reason); } } Err(e) => { + ctx.provider_readiness.credentials_failed( + desired_identity.clone(), + ProviderReadinessReason::CredentialInstallFailed, + ); ctx.provider_credentials .revoke_static_provider_environment(result.provider_env_revision); warn!( @@ -3930,8 +4028,14 @@ async fn run_policy_poll_loop_with_client( .await; match runtime_result { - Ok(()) => { + Ok(generation) => { policy_runtime_reconciled = true; + ctx.provider_readiness.policy_activated( + &desired_identity, + result.config_revision, + generation.clone(), + ); + current_policy_generation = Some(generation); let policy = result .policy .as_ref() @@ -4029,6 +4133,8 @@ async fn run_policy_poll_loop_with_client( last_failed_runtime_revision = None; } Err(failure) => { + ctx.provider_readiness + .policy_install_failed(desired_identity.clone(), result.config_revision); let failed_revision = FailedRuntimeRevision::new( result.config_revision, &result.policy_hash, @@ -4126,6 +4232,21 @@ async fn run_policy_poll_loop_with_client( current_policy_version = version; } + if reloads_gateway_policy + && !policy_runtime_changed + && let Some(generation) = current_policy_generation + .as_ref() + .filter(|generation| !generation.is_stale()) + { + // The same installed policy may serve a new attachment/configuration + // identity. Its generation is retained, never inferred from a cursor. + ctx.provider_readiness.policy_activated( + &desired_identity, + result.config_revision, + generation.clone(), + ); + } + if policy_runtime_reconciled || provider_env_changed { endpoint_status::reset( ctx.endpoint_observation_tx.as_ref(), @@ -4678,6 +4799,7 @@ network_policies: settings: std::collections::HashMap::new(), global_policy_version: 0, provider_env_revision: 0, + provider_attachment_epoch: String::new(), supervisor_middleware_services: Vec::new(), workspace: String::new(), policy_validation_failure_mode: PolicyValidationFailureMode::default(), @@ -4788,6 +4910,505 @@ network_policies: ) } + fn static_provider_environment( + revision: u64, + value: Option<&str>, + ) -> openshell_core::grpc_client::ProviderEnvironmentResult { + use openshell_core::proto::{StaticCredentialBinding, StaticCredentialEndpointBinding}; + use std::collections::HashMap; + + let mut result = openshell_core::grpc_client::ProviderEnvironmentResult { + environment: HashMap::new(), + provider_env_revision: revision, + provider_attachment_epoch: String::new(), + policy_hash: "hash-v1".to_string(), + readiness_reason: ProviderReadinessReason::Unspecified, + credential_expires_at_ms: HashMap::new(), + dynamic_credentials: HashMap::new(), + static_credential_bindings: HashMap::new(), + non_secret_environment_keys: Vec::new(), + }; + if let Some(value) = value { + result + .environment + .insert("EXTERNAL_TOKEN".into(), value.into()); + result.static_credential_bindings.insert( + "EXTERNAL_TOKEN".into(), + StaticCredentialBinding { + endpoints: vec![StaticCredentialEndpointBinding { + host: "tools.example.com".into(), + port: 443, + path: "/v1/**".into(), + }], + credential_identity: "provider-a:EXTERNAL_TOKEN".into(), + workload_credential_handle: String::new(), + }, + ); + } + result + } + + #[test] + fn initial_provider_credentials_preserve_revision_scoped_delivery() { + let readiness = ProviderReadinessTracker::new(); + let state = initial_provider_credentials( + static_provider_environment(1, Some("initial")), + &readiness, + ); + let (revision, child_env) = state.child_env_snapshot_with_gcp_resolved().unwrap(); + let reference = &child_env["EXTERNAL_TOKEN"]; + assert_eq!(revision, 1); + assert_eq!(reference, "openshell:resolve:env:v1_EXTERNAL_TOKEN"); + assert_eq!( + state + .resolver_for_endpoint("tools.example.com", 443, "/v1/chat") + .unwrap() + .resolve_placeholder(reference), + Some("initial"), + ); + assert!(readiness.observation(&state).credentials_installed); + assert!(!readiness.observation(&state).launch_environment_installed); + // The boundary receives the prepared snapshot without gaining resolver authority. + let boundary = + ProviderCredentialState::from_child_env_snapshot(revision, child_env.clone()); + assert_eq!(boundary.snapshot().child_env, child_env); + assert!(boundary.resolver().is_none()); + + let mut invalid = static_provider_environment(2, Some("invalid")); + invalid.static_credential_bindings.clear(); + let rejected = initial_provider_credentials(invalid, &readiness); + assert!(rejected.snapshot().child_env.is_empty()); + assert!(rejected.resolver().is_none()); + assert_eq!( + readiness.observation(&rejected).reason, + i32::from(ProviderReadinessReason::CredentialInstallFailed) + ); + } + + type ProviderFetchRequest = tokio::sync::oneshot::Sender< + Result, + >; + + #[derive(Clone)] + struct ScriptedProviderGateway { + policy: ScriptedPolicyGateway, + requests: UnboundedSender, + } + + #[tonic::async_trait] + impl PolicyGatewayClient for ScriptedProviderGateway { + async fn poll_settings( + &self, + sandbox_id: &str, + ) -> Result { + self.policy.poll_settings(sandbox_id).await + } + + async fn report_policy_status( + &self, + sandbox_id: &str, + version: u32, + loaded: bool, + error: &str, + ) -> Result<()> { + self.policy + .report_policy_status(sandbox_id, version, loaded, error) + .await + } + + async fn fetch_provider_environment( + &self, + _endpoint: &str, + sandbox_id: &str, + ) -> Result { + assert_eq!(sandbox_id, "sandbox-test"); + let (response, received) = tokio::sync::oneshot::channel(); + self.requests + .send(response) + .map_err(|_| miette::miette!("provider request channel closed"))?; + received + .await + .map_err(|_| miette::miette!("provider response channel closed"))? + } + + fn workspace(&self) -> String { + self.policy.workspace() + } + } + + #[tokio::test] + async fn provider_readiness_initial_poll_waits_for_middleware_reconciliation() { + let policy = proto_policy_fixture(); + let mut settings = settings_poll_result( + Some(policy.clone()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + settings.provider_attachment_epoch = "epoch".to_string(); + settings.provider_env_revision = 9; + settings.supervisor_middleware_services = + vec![openshell_core::proto::SupervisorMiddlewareService { + name: "scripted-guard".to_string(), + grpc_endpoint: "http://scripted.invalid".to_string(), + ..Default::default() + }]; + let (attempt_tx, mut attempts) = tokio::sync::mpsc::unbounded_channel(); + let (complete, completions) = tokio::sync::mpsc::unbounded_channel::(); + let completions = Arc::new(tokio::sync::Mutex::new(completions)); + let connector: MiddlewareConnector = Arc::new(move |services, _authentication| { + assert_eq!(services.len(), 1); + assert_eq!(services[0].name, "scripted-guard"); + attempt_tx.send(()).unwrap(); + let completions = completions.clone(); + Box::pin(async move { + if completions.lock().await.recv().await.unwrap() { + connect_middleware_registry(&[], &MiddlewareAuthentication::default()).await + } else { + Err(miette::miette!("scripted middleware connection failure")) + } + }) + }); + let engine = Arc::new(OpaEngine::from_proto(&policy).unwrap()); + let mut context = policy_poll_test_context( + engine.clone(), + LoadedPolicyOrigin::Gateway { + revision: Some(LoadedPolicyRevision::from_snapshot(&settings)), + has_last_valid_policy: true, + }, + connector, + ); + context.middleware_registry_status = MiddlewareRegistryStatus::NeedsReconciliation; + context.provider_credentials = ProviderCredentialState::from_child_env_snapshot( + 9, + std::collections::HashMap::default(), + ); + let credentials = context.provider_credentials.clone(); + let tracker = context.provider_readiness.clone(); + tracker.credentials_installed( + EnvironmentIdentity::from_settings(&settings), + &credentials, + None, + ); + let (gateway, polls, mut reports) = scripted_policy_gateway(); + let task = tokio::spawn(run_policy_poll_loop_with_client(context, gateway)); + polls.send(settings.clone()).unwrap(); + timeout(Duration::from_secs(1), attempts.recv()) + .await + .expect("initial snapshot must reconcile without a second poll") + .unwrap(); + let observed = tracker.observation(&credentials); + assert!(observed.credentials_installed); + assert!(!observed.policy_active); + assert!( + !observed.launch_environment_installed, + "process evidence requires its own boundary acknowledgment" + ); + expect_no_policy_report(&mut reports).await; + + complete.send(false).unwrap(); + timeout(Duration::from_secs(1), async { + while tracker.observation(&credentials).reason + != i32::from(ProviderReadinessReason::PolicyActivationFailed) + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert!(!tracker.observation(&credentials).policy_active); + assert_eq!(engine.current_generation(), 0); + expect_no_policy_report(&mut reports).await; + + polls.send(settings).unwrap(); + timeout(Duration::from_secs(1), attempts.recv()) + .await + .unwrap() + .unwrap(); + assert!(!tracker.observation(&credentials).policy_active); + complete.send(true).unwrap(); + expect_policy_report(&mut reports, 1).await; + assert!(tracker.observation(&credentials).policy_active); + assert_eq!(engine.current_generation(), 1); + task.abort(); + let _ = task.await; + } + + #[derive(Clone)] + struct GenerationChangingPolicyGateway { + inner: ScriptedPolicyGateway, + engine: Arc, + first_poll: Arc, + } + + #[tonic::async_trait] + impl PolicyGatewayClient for GenerationChangingPolicyGateway { + async fn poll_settings( + &self, + sandbox_id: &str, + ) -> Result { + let result = self.inner.poll_settings(sandbox_id).await?; + if self.first_poll.swap(false, Ordering::SeqCst) { + self.engine + .enter_fail_closed("generation replaced while first poll was pending")?; + } + Ok(result) + } + + async fn report_policy_status( + &self, + sandbox_id: &str, + version: u32, + loaded: bool, + error: &str, + ) -> Result<()> { + self.inner + .report_policy_status(sandbox_id, version, loaded, error) + .await + } + + fn workspace(&self) -> String { + self.inner.workspace() + } + } + + #[tokio::test] + async fn provider_readiness_initial_poll_reconciles_a_replaced_policy_generation() { + let policy = proto_policy_fixture(); + let settings = settings_poll_result( + Some(policy.clone()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + let engine = Arc::new(OpaEngine::from_proto(&policy).unwrap()); + let context = policy_poll_test_context( + engine.clone(), + LoadedPolicyOrigin::Gateway { + revision: Some(LoadedPolicyRevision::from_snapshot(&settings)), + has_last_valid_policy: true, + }, + default_middleware_connector(), + ); + let credentials = context.provider_credentials.clone(); + let tracker = context.provider_readiness.clone(); + tracker.credentials_installed( + EnvironmentIdentity::from_settings(&settings), + &credentials, + None, + ); + let (inner, polls, mut reports) = scripted_policy_gateway(); + let gateway = GenerationChangingPolicyGateway { + inner, + engine: engine.clone(), + first_poll: Arc::new(AtomicBool::new(true)), + }; + let task = tokio::spawn(run_policy_poll_loop_with_client(context, gateway)); + polls.send(settings).unwrap(); + expect_policy_report(&mut reports, 1).await; + assert!( + engine.fail_closed_reason().is_none(), + "the delivered policy must replace the intervening quarantine before acknowledgment" + ); + assert_eq!( + engine.current_generation(), + 2, + "generation 1 was not the policy startup installed" + ); + assert!(tracker.observation(&credentials).policy_active); + task.abort(); + let _ = task.await; + } + + #[tokio::test] + async fn provider_readiness_poll_waits_for_installation_and_retries_same_fingerprint() { + let engine = Arc::new(OpaEngine::from_proto(&proto_policy_fixture()).unwrap()); + let mut initial = settings_poll_result( + Some(proto_policy_fixture()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + initial.provider_env_revision = 6; + let ctx = policy_poll_test_context( + engine.clone(), + LoadedPolicyOrigin::Gateway { + revision: Some(LoadedPolicyRevision::from_snapshot(&initial)), + has_last_valid_policy: true, + }, + default_middleware_connector(), + ); + let credentials = ctx.provider_credentials.clone(); + let tracker = ctx.provider_readiness.clone(); + let (policy, polls, mut reports) = scripted_policy_gateway(); + let (requests, mut received) = tokio::sync::mpsc::unbounded_channel(); + polls.send(initial.clone()).unwrap(); + let task = tokio::spawn(run_policy_poll_loop_with_client( + ctx, + ScriptedProviderGateway { policy, requests }, + )); + expect_policy_report(&mut reports, 1).await; + + polls.send(initial.clone()).unwrap(); + let response = timeout(Duration::from_secs(1), received.recv()) + .await + .unwrap() + .unwrap(); + assert!( + !tracker.observation(&credentials).credentials_installed, + "fetching desired credentials does not install them" + ); + assert!(response.send(Err(miette::miette!("unavailable"))).is_ok()); + timeout(Duration::from_secs(1), async { + while tracker.observation(&credentials).reason + != i32::from(ProviderReadinessReason::CredentialInstallFailed) + { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let failed_id = credentials.snapshot().installation_id.clone(); + + polls.send(initial.clone()).unwrap(); + let response = timeout(Duration::from_secs(1), received.recv()) + .await + .unwrap() + .unwrap(); + assert!( + response + .send(Ok(static_provider_environment(6, Some("repaired")))) + .is_ok() + ); + timeout(Duration::from_secs(1), async { + while !tracker.observation(&credentials).credentials_installed { + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + let observed = tracker.observation(&credentials); + assert_ne!(failed_id, credentials.snapshot().installation_id); + assert!(observed.policy_active); + assert!( + !observed.launch_environment_installed, + "a separate boundary acknowledgment is still required" + ); + + // A policy change can preserve the provider content fingerprint while + // changing the credential authority. Fetch and install that identity too. + let mut changed = initial; + changed.version = 2; + changed.config_revision = 200; + changed.policy_hash = "hash-v2".to_string(); + polls.send(changed).unwrap(); + let response = timeout(Duration::from_secs(1), received.recv()) + .await + .unwrap() + .unwrap(); + assert!(!tracker.observation(&credentials).policy_active); + let mut environment = static_provider_environment(6, Some("repaired")); + environment.policy_hash = "hash-v2".to_string(); + assert!(response.send(Ok(environment)).is_ok()); + expect_policy_report(&mut reports, 2).await; + let observed = tracker.observation(&credentials); + assert!(observed.credentials_installed && observed.policy_active); + assert_eq!(observed.provider_env_revision, 6); + assert_eq!(observed.config_revision, 200); + assert_eq!(observed.policy_hash, "hash-v2"); + task.abort(); + let _ = task.await; + } + + #[tokio::test] + async fn provider_poll_preserves_static_references_across_rotation_failure_and_detach() { + let engine = Arc::new(OpaEngine::from_proto(&proto_policy_fixture()).unwrap()); + let initial = settings_poll_result( + Some(proto_policy_fixture()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + let ctx = policy_poll_test_context( + engine, + LoadedPolicyOrigin::Gateway { + revision: Some(LoadedPolicyRevision::from_snapshot(&initial)), + has_last_valid_policy: true, + }, + default_middleware_connector(), + ); + let state = ctx.provider_credentials.clone(); + let tracker = ctx.provider_readiness.clone(); + let (policy, polls, mut reports) = scripted_policy_gateway(); + let (requests, mut received) = tokio::sync::mpsc::unbounded_channel(); + polls.send(initial.clone()).unwrap(); + let task = tokio::spawn(run_policy_poll_loop_with_client( + ctx, + ScriptedProviderGateway { policy, requests }, + )); + expect_policy_report(&mut reports, 1).await; + + // Rotation gives future processes a new reference; the retained old + // reference continues to resolve its original value until revocation. + let old_reference = "openshell:resolve:env:v1_EXTERNAL_TOKEN"; + for (revision, value, fail) in [ + (1, Some("initial"), false), + (2, Some("rotated"), false), + (3, None, true), + (3, Some("recovered"), false), + (4, None, false), + (5, None, false), + ] { + let mut poll = initial.clone(); + poll.provider_env_revision = revision; + polls.send(poll).unwrap(); + let response = timeout(Duration::from_secs(5), received.recv()) + .await + .expect("provider refresh requested") + .expect("poll loop active"); + let result = if fail { + Err(miette::miette!("provider snapshot unavailable")) + } else { + Ok(static_provider_environment(revision, value)) + }; + assert!(response.send(result).is_ok()); + let reference = format!("openshell:resolve:env:v{revision}_EXTERNAL_TOKEN"); + timeout(Duration::from_secs(5), async { + loop { + let resolved = state + .resolver_for_endpoint("tools.example.com", 443, "/v1/chat") + .and_then(|resolver| { + resolver.resolve_placeholder(&reference).map(str::to_owned) + }); + let observed = tracker.observation(&state); + if state.revision() == revision + && resolved.as_deref() == value + && (fail || observed.credentials_installed) + { + break; + } + tokio::task::yield_now().await; + } + }) + .await + .expect("provider snapshot installed or revoked"); + if value.is_some() { + assert_eq!(state.snapshot().child_env["EXTERNAL_TOKEN"], reference); + if revision == 2 { + assert_ne!(reference, old_reference); + assert_eq!( + state + .resolver_for_endpoint("tools.example.com", 443, "/v1/chat") + .unwrap() + .resolve_placeholder(old_reference), + Some("initial") + ); + } + } else { + assert!(state.snapshot().child_env.is_empty()); + assert!(state.resolver().is_none()); + } + } + task.abort(); + let _ = task.await; + } + fn policy_poll_test_context( opa_engine: Arc, loaded_policy_origin: LoadedPolicyOrigin, @@ -4806,6 +5427,7 @@ network_policies: 0, std::collections::HashMap::new(), ), + provider_readiness: ProviderReadinessTracker::new(), policy_local_ctx: None, agent_proposals: AgentProposals::default(), middleware_registry_status: MiddlewareRegistryStatus::Synchronized, @@ -5809,6 +6431,23 @@ network_policies: )); } + #[test] + fn provider_readiness_initial_policy_requires_exact_config_identity() { + let mut canonical = settings_poll_result( + Some(proto_policy_fixture()), + 2, + openshell_core::proto::PolicySource::Sandbox, + ); + let loaded = LoadedPolicyRevision::from_snapshot(&canonical); + for revision in [1, u64::MAX] { + canonical.config_revision = revision; + assert!( + initial_policy_ack_candidate(Some(&loaded), &canonical).is_none(), + "matching policy bytes cannot acknowledge a different installed configuration" + ); + } + } + #[test] fn initial_ack_candidate_matches_sandbox_revision() { let canonical = settings_poll_result( diff --git a/crates/openshell-supervisor/src/provider_readiness.rs b/crates/openshell-supervisor/src/provider_readiness.rs new file mode 100644 index 0000000000..fae5e71455 --- /dev/null +++ b/crates/openshell-supervisor/src/provider_readiness.rs @@ -0,0 +1,837 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Installation evidence reported under the accepted supervisor session. +//! +//! Desired-state cursors never establish success. Credentials, policy, and +//! the authenticated workload boundary must acknowledge the same authority. + +use std::sync::Arc; +use std::time::Duration; + +use openshell_core::proto::{ + ProviderReadinessObservation, ProviderReadinessReason as Reason, + ReportProviderReadinessResponse, +}; +use openshell_core::provider_credentials::ProviderCredentialState; +use openshell_isolation_interface::contract::{BoundaryExec, ProviderEnvironmentInstallation}; +use openshell_supervisor_network::opa::PolicyGenerationGuard; +use tokio::sync::watch; + +/// Authority captured before consuming a provider response's credential fields. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EnvironmentIdentity { + pub(crate) attachment_epoch: String, + pub(crate) revision: u64, + pub(crate) policy_hash: String, +} + +impl EnvironmentIdentity { + /// Preserve the authority delivered with a credential snapshot before consuming it. + pub(crate) fn from_environment( + result: &openshell_core::grpc_client::ProviderEnvironmentResult, + ) -> Self { + Self { + attachment_epoch: result.provider_attachment_epoch.clone(), + revision: result.provider_env_revision, + policy_hash: result.policy_hash.clone(), + } + } + + /// Capture the requested authority without claiming that it is installed. + pub(crate) fn from_settings(result: &openshell_core::grpc_client::SettingsPollResult) -> Self { + Self { + attachment_epoch: result.provider_attachment_epoch.clone(), + revision: result.provider_env_revision, + policy_hash: result.policy_hash.clone(), + } + } +} + +#[derive(Clone, Debug)] +struct InstalledPolicy { + epoch: String, + hash: String, + config_revision: u64, + generation: PolicyGenerationGuard, +} + +#[derive(Clone, Debug)] +struct FailedPolicy { + identity: EnvironmentIdentity, + config_revision: u64, +} + +#[derive(Clone, Debug)] +struct State { + identity: EnvironmentIdentity, + installation_id: String, + credential_reason: Reason, + expires_at_ms: Option, + policy: Option, + policy_failure: Option, + process: Option, + process_reason: Reason, +} + +/// Shared installation tracker; each transition wakes the independent reporter. +#[derive(Clone, Debug)] +pub struct Tracker { + state: watch::Sender, +} + +impl Tracker { + /// Start without credential, policy, or process installation evidence. + pub(crate) fn new() -> Self { + let (state, _) = watch::channel(State { + identity: EnvironmentIdentity::default(), + installation_id: String::new(), + credential_reason: Reason::WaitingForCredentials, + expires_at_ms: None, + policy: None, + policy_failure: None, + process: None, + process_reason: Reason::WaitingForProcess, + }); + Self { state } + } + + /// Invalidate old success before a replacement or fail-closed clear begins. + pub(crate) fn credentials_failed(&self, identity: EnvironmentIdentity, reason: Reason) { + self.state.send_modify(|state| { + state.identity = identity; + state.installation_id.clear(); + state.credential_reason = reason; + state.expires_at_ms = None; + state.process = None; + state.process_reason = Reason::WaitingForProcess; + }); + } + + /// Record a completed credential installation and require a fresh process acknowledgment. + pub(crate) fn credentials_installed( + &self, + identity: EnvironmentIdentity, + credentials: &ProviderCredentialState, + expires_at_ms: Option, + ) { + let snapshot = credentials.snapshot(); + self.state.send_modify(|state| { + state.credential_reason = + if !identity.policy_hash.is_empty() && snapshot.revision == identity.revision { + Reason::Unspecified + } else { + Reason::SnapshotMismatch + }; + state.identity = identity; + state.installation_id.clone_from(&snapshot.installation_id); + state.expires_at_ms = expires_at_ms; + state.process = None; + state.process_reason = Reason::WaitingForProcess; + }); + } + + /// Retry failed installations even when the requested fingerprint is unchanged. + pub(crate) fn needs_environment(&self, identity: &EnvironmentIdentity) -> bool { + let state = self.state.borrow(); + state.credential_reason != Reason::Unspecified || state.identity != *identity + } + + /// Bind policy evidence to the exact generation returned by runtime installation. + pub(crate) fn policy_activated( + &self, + identity: &EnvironmentIdentity, + config_revision: u64, + generation: PolicyGenerationGuard, + ) { + self.state.send_modify(|state| { + state.policy = Some(InstalledPolicy { + epoch: identity.attachment_epoch.clone(), + hash: identity.policy_hash.clone(), + config_revision, + generation, + }); + state.policy_failure = None; + }); + } + + /// Report the rejected desired configuration without acknowledging its policy. + pub(crate) fn policy_install_failed( + &self, + identity: EnvironmentIdentity, + config_revision: u64, + ) { + self.state.send_modify(|state| { + // Failed desired identity must not masquerade as evidence for the + // last installed policy, even when the failure retains that policy. + state.policy_failure = Some(FailedPolicy { + identity, + config_revision, + }); + }); + } + + fn process_installed( + &self, + installed: ProviderEnvironmentInstallation, + credentials: &ProviderCredentialState, + ) { + let current = credentials.snapshot(); + self.state.send_if_modified(|state| { + if installed.installation_id != current.installation_id + || installed.installation_id != state.installation_id + || installed.revision != state.identity.revision + { + return false; + } + let changed = state.process.as_ref() != Some(&installed) + || state.process_reason != Reason::Unspecified; + state.process = Some(installed); + state.process_reason = Reason::Unspecified; + changed + }); + } + + fn process_failed(&self) { + self.state.send_if_modified(|state| { + let changed = + state.process.is_some() || state.process_reason != Reason::ProcessInstallFailed; + state.process = None; + state.process_reason = Reason::ProcessInstallFailed; + changed + }); + } + + /// Read current evidence, rechecking credential expiry and policy generation. + pub(crate) fn observation( + &self, + credentials: &ProviderCredentialState, + ) -> ProviderReadinessObservation { + let state = self.state.borrow(); + let current = credentials.snapshot(); + let identity = state + .policy_failure + .as_ref() + .map_or(&state.identity, |failure| &failure.identity); + let expired = state + .expires_at_ms + .is_some_and(|expiry| expiry <= openshell_core::time::now_ms()); + let credentials_installed = state.credential_reason == Reason::Unspecified + && !expired + && state.identity == *identity + && current.installation_id == state.installation_id; + let policy_active = state.policy_failure.is_none() + && state.policy.as_ref().is_some_and(|policy| { + !policy.hash.is_empty() + && policy.hash == identity.policy_hash + && policy.epoch == identity.attachment_epoch + && !policy.generation.is_stale() + }); + let launch_environment_installed = credentials_installed + && state.process.as_ref().is_some_and(|process| { + process.installation_id == state.installation_id + && process.revision == identity.revision + }); + let reason = if state.policy_failure.is_some() { + Reason::PolicyActivationFailed + } else if expired { + Reason::CredentialExpired + } else if state.credential_reason != Reason::Unspecified { + state.credential_reason + } else if !credentials_installed { + Reason::WaitingForCredentials + } else if !policy_active { + Reason::WaitingForPolicy + } else if !launch_environment_installed { + if state.process_reason == Reason::Unspecified { + Reason::WaitingForProcess + } else { + state.process_reason + } + } else { + Reason::Unspecified + }; + ProviderReadinessObservation { + attachment_epoch: identity.attachment_epoch.clone(), + provider_env_revision: identity.revision, + config_revision: state.policy_failure.as_ref().map_or_else( + || { + state + .policy + .as_ref() + .map_or(0, |policy| policy.config_revision) + }, + |failure| failure.config_revision, + ), + policy_hash: identity.policy_hash.clone(), + credentials_installed, + policy_active, + launch_environment_installed, + process_instance_id: state + .process + .as_ref() + .map_or_else(String::new, |process| process.session_id.to_string()), + reason: reason.into(), + ..Default::default() + } + } + + /// Report while the owner holds this handle; reconnects use the accepted session. + pub(crate) fn start_reporter( + &self, + endpoint: String, + sandbox_id: String, + credentials: ProviderCredentialState, + sessions: watch::Receiver>, + boundary: Arc, + ) -> Reporter { + let tracker = self.clone(); + Reporter(tokio::spawn(async move { + tracker + .run_reporter( + credentials, + sessions, + boundary, + GatewayReporter { + endpoint, + sandbox_id, + }, + ) + .await; + })) + } + + async fn run_reporter( + &self, + credentials: ProviderCredentialState, + mut sessions: watch::Receiver>, + boundary: Arc, + client: C, + ) { + let tracker = self; + let mut updates = tracker.state.subscribe(); + let mut active_session = None; + let mut sequence = 0_u64; + let mut interval = tokio::time::interval(Duration::from_secs(5)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + let guard = tracker + .state + .borrow() + .policy + .as_ref() + .map(|policy| policy.generation.clone()) + .filter(|guard| !guard.is_stale()); + tokio::select! { + changed = sessions.changed() => { if changed.is_err() { return; } } + changed = updates.changed() => { if changed.is_err() { return; } } + _ = interval.tick() => {} + () = async { + if let Some(guard) = guard { guard.wait_until_stale().await; } + else { std::future::pending::<()>().await; } + } => {} + } + let session = sessions.borrow_and_update().clone(); + if session != active_session { + sequence = 0; + active_session = session.clone(); + } + let Some(session) = session else { + continue; + }; + // Synchronization is also a boundary liveness check. A stopped + // boundary cannot keep renewing successful launch evidence. + let synchronization = tokio::time::timeout( + Duration::from_secs(10), + boundary.synchronize_provider_environment(), + ); + let installed = tokio::select! { + changed = sessions.changed() => { if changed.is_err() { return; } interval.reset_immediately(); continue; } + installed = synchronization => installed, + }; + match installed { + Ok(Ok(installed)) => tracker.process_installed(installed, &credentials), + _ => tracker.process_failed(), + } + let Some(next_sequence) = sequence.checked_add(1) else { + return; + }; + sequence = next_sequence; + let mut observation = tracker.observation(&credentials); + observation.session_id.clone_from(&session); + observation.sequence = sequence; + let report = tokio::time::timeout(Duration::from_secs(5), client.report(observation)); + let response = tokio::select! { + changed = sessions.changed() => { if changed.is_err() { return; } interval.reset_immediately(); continue; } + response = report => response, + }; + if let Ok(Ok(response)) = response + && !report_acknowledged(&response, sequence) + { + // A gateway rejection does not invalidate the boundary's + // installation. Retry on the normal cadence or a real state + // change without creating a self-triggered failure/retry loop. + tracing::warn!("Provider readiness report was not acknowledged"); + } + } + } +} + +/// An acknowledgment must bind this report and a valid positive evidence lease. +fn report_acknowledged(response: &ReportProviderReadinessResponse, sequence: u64) -> bool { + response.accepted_sequence == sequence + && response + .observation_ttl + .as_ref() + .and_then(|ttl| openshell_core::time::duration_to_std(ttl).ok()) + .is_some_and(|ttl| !ttl.is_zero()) +} + +#[tonic::async_trait] +trait ReportClient: Send + Sync { + async fn report( + &self, + observation: ProviderReadinessObservation, + ) -> miette::Result; +} + +struct GatewayReporter { + endpoint: String, + sandbox_id: String, +} + +#[tonic::async_trait] +impl ReportClient for GatewayReporter { + async fn report( + &self, + observation: ProviderReadinessObservation, + ) -> miette::Result { + openshell_core::grpc_client::report_provider_readiness( + &self.endpoint, + &self.sandbox_id, + observation, + ) + .await + } +} + +/// Cancels reporting before supervisor teardown can renew stale evidence. +pub struct Reporter(tokio::task::JoinHandle<()>); + +impl Drop for Reporter { + fn drop(&mut self) { + self.0.abort(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + #[test] + fn acknowledgment_requires_matching_sequence_and_valid_positive_ttl() { + let mut response = ReportProviderReadinessResponse { + accepted_sequence: 7, + ..Default::default() + }; + assert!(!report_acknowledged(&response, 7)); + for (seconds, nanos, valid) in [ + (15, 0, true), + (0, 1, true), + (0, 0, false), + (-1, 0, false), + (0, -1, false), + (1, -1, false), + (0, 1_000_000_000, false), + (315_576_000_001, 0, false), + ] { + response.observation_ttl = Some(prost_types::Duration { seconds, nanos }); + assert_eq!( + report_acknowledged(&response, 7), + valid, + "seconds={seconds}, nanos={nanos}" + ); + } + response.observation_ttl = Some(prost_types::Duration { + seconds: 15, + nanos: 0, + }); + assert!(!report_acknowledged(&response, 8)); + } + + struct CapturingReporter(tokio::sync::mpsc::UnboundedSender); + + #[tonic::async_trait] + impl ReportClient for CapturingReporter { + async fn report( + &self, + observation: ProviderReadinessObservation, + ) -> miette::Result { + let sequence = observation.sequence; + self.0.send(observation).unwrap(); + Ok(ReportProviderReadinessResponse { + accepted_sequence: sequence, + report_interval: Some( + openshell_core::time::duration_from_std(Duration::from_secs(5)).unwrap(), + ), + observation_ttl: Some( + openshell_core::time::duration_from_std(Duration::from_secs(15)).unwrap(), + ), + }) + } + } + + struct DelayedReporter( + tokio::sync::mpsc::UnboundedSender<( + ProviderReadinessObservation, + tokio::sync::oneshot::Sender, + )>, + ); + + #[tonic::async_trait] + impl ReportClient for DelayedReporter { + async fn report( + &self, + observation: ProviderReadinessObservation, + ) -> miette::Result { + let (response, received) = tokio::sync::oneshot::channel(); + self.0.send((observation, response)).unwrap(); + received + .await + .map_err(|_| miette::miette!("report response channel closed")) + } + } + + struct DelayedBoundary( + tokio::sync::mpsc::UnboundedSender< + tokio::sync::oneshot::Sender, + >, + ); + + #[tonic::async_trait] + impl BoundaryExec for DelayedBoundary { + async fn exec( + &self, + _spec: openshell_isolation_interface::contract::ExecSpec, + ) -> Result< + openshell_isolation_interface::contract::ExecSession, + openshell_isolation_interface::contract::BackendError, + > { + unreachable!("reporting must never launch a workload process") + } + + async fn synchronize_provider_environment( + &self, + ) -> Result< + ProviderEnvironmentInstallation, + openshell_isolation_interface::contract::BackendError, + > { + let (sender, receiver) = tokio::sync::oneshot::channel(); + self.0.send(sender).unwrap(); + receiver.await.map_err(|_| { + openshell_isolation_interface::contract::BackendError::Unavailable( + "boundary disconnected".into(), + ) + }) + } + } + + async fn next_installation_report( + installations: &mut tokio::sync::mpsc::UnboundedReceiver< + tokio::sync::oneshot::Sender, + >, + reports: &mut tokio::sync::mpsc::UnboundedReceiver<( + ProviderReadinessObservation, + tokio::sync::oneshot::Sender, + )>, + installed: &ProviderEnvironmentInstallation, + wait: Duration, + ) -> ( + ProviderReadinessObservation, + tokio::sync::oneshot::Sender, + ) { + tokio::time::timeout(wait, async { + installations + .recv() + .await + .unwrap() + .send(installed.clone()) + .unwrap(); + reports.recv().await.unwrap() + }) + .await + .expect("reporter did not synchronize and report before the deadline") + } + + #[tokio::test] + async fn invalid_report_acknowledgments_retry_without_installation_feedback() { + let tracker = Tracker::new(); + let credentials = ProviderCredentialState::from_child_env_snapshot(6, HashMap::new()); + tracker.credentials_installed(identity(), &credentials, None); + let policy = openshell_policy::restrictive_default_policy(); + let engine = openshell_supervisor_network::opa::OpaEngine::from_proto(&policy).unwrap(); + tracker.policy_activated(&identity(), 12, engine.generation_guard(0).unwrap()); + let mut installed = installation(&credentials); + let (sessions, receiver) = watch::channel(Some("current-session".to_string())); + let (boundary_tx, mut boundary_rx) = tokio::sync::mpsc::unbounded_channel(); + let (report_tx, mut report_rx) = tokio::sync::mpsc::unbounded_channel(); + let reporting_tracker = tracker.clone(); + let reporting_credentials = credentials.clone(); + let task = tokio::spawn(async move { + reporting_tracker + .run_reporter( + reporting_credentials, + receiver, + Arc::new(DelayedBoundary(boundary_tx)), + DelayedReporter(report_tx), + ) + .await; + }); + // The first installation changes local evidence once. Its watch update + // may cause one additional report, but an invalid gateway reply must + // not keep toggling that evidence and scheduling more installations. + for sequence in 1..=2 { + let (report, response) = next_installation_report( + &mut boundary_rx, + &mut report_rx, + &installed, + Duration::from_secs(1), + ) + .await; + assert_eq!(report.sequence, sequence); + assert!(report.launch_environment_installed); + response + .send(ReportProviderReadinessResponse::default()) + .unwrap(); + } + assert!( + tokio::time::timeout(Duration::from_millis(100), boundary_rx.recv()) + .await + .is_err(), + "invalid report replies must not repeatedly reinstall an unchanged environment" + ); + + // A real credential installation still wakes the reporter immediately. + credentials.install_child_env_snapshot(6, HashMap::new()); + tracker.credentials_installed(identity(), &credentials, None); + installed.installation_id = credentials.snapshot().installation_id.clone(); + let (report, response) = next_installation_report( + &mut boundary_rx, + &mut report_rx, + &installed, + Duration::from_secs(1), + ) + .await; + assert_eq!(report.sequence, 3); + assert!(report.launch_environment_installed); + // A policy update received while the report is pending must survive + // processing its reply and cause a report of the new configuration. + tracker.policy_activated(&identity(), 13, engine.generation_guard(0).unwrap()); + response + .send(ReportProviderReadinessResponse::default()) + .unwrap(); + let (report, response) = next_installation_report( + &mut boundary_rx, + &mut report_rx, + &installed, + Duration::from_secs(1), + ) + .await; + assert_eq!(report.sequence, 4); + assert_eq!(report.config_revision, 13); + response + .send(ReportProviderReadinessResponse::default()) + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(100), boundary_rx.recv()) + .await + .is_err() + ); + + sessions.send_replace(Some("replacement-session".to_string())); + let (report, response) = next_installation_report( + &mut boundary_rx, + &mut report_rx, + &installed, + Duration::from_secs(1), + ) + .await; + assert_eq!(report.session_id, "replacement-session"); + assert_eq!(report.sequence, 1); + response + .send(ReportProviderReadinessResponse::default()) + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(100), boundary_rx.recv()) + .await + .is_err() + ); + + // Without further state changes, the periodic liveness check retries. + let (report, response) = next_installation_report( + &mut boundary_rx, + &mut report_rx, + &installed, + Duration::from_secs(6), + ) + .await; + assert_eq!(report.session_id, "replacement-session"); + assert_eq!(report.sequence, 2); + assert!(report.launch_environment_installed); + response + .send(ReportProviderReadinessResponse::default()) + .unwrap(); + task.abort(); + let _ = task.await; + } + + #[tokio::test] + async fn reconnect_cancels_delayed_boundary_ack_and_starts_a_new_report_sequence() { + let tracker = Tracker::new(); + let credentials = ProviderCredentialState::from_child_env_snapshot(6, HashMap::new()); + tracker.credentials_installed(identity(), &credentials, None); + let installed = installation(&credentials); + let (sessions, receiver) = watch::channel(Some("old-session".to_string())); + let (boundary_tx, mut boundary_rx) = tokio::sync::mpsc::unbounded_channel(); + let (report_tx, mut report_rx) = tokio::sync::mpsc::unbounded_channel(); + let task = tokio::spawn(async move { + tracker + .run_reporter( + credentials, + receiver, + Arc::new(DelayedBoundary(boundary_tx)), + CapturingReporter(report_tx), + ) + .await; + }); + let old_ack = tokio::time::timeout(Duration::from_secs(1), boundary_rx.recv()) + .await + .unwrap() + .unwrap(); + sessions.send_replace(Some("current-session".to_string())); + let current_ack = tokio::time::timeout(Duration::from_secs(1), boundary_rx.recv()) + .await + .unwrap() + .unwrap(); + assert!( + old_ack.send(installed.clone()).is_err(), + "replaced session must cancel its pending installation" + ); + current_ack.send(installed.clone()).unwrap(); + let report = tokio::time::timeout(Duration::from_secs(1), report_rx.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(report.session_id, "current-session"); + assert_eq!(report.sequence, 1); + assert!(report.launch_environment_installed); + // The installation transition wakes a second report, whose sequence + // must advance even though its desired authority is unchanged. + let next_ack = tokio::time::timeout(Duration::from_secs(1), boundary_rx.recv()) + .await + .unwrap() + .unwrap(); + next_ack.send(installed).unwrap(); + let report = tokio::time::timeout(Duration::from_secs(1), report_rx.recv()) + .await + .unwrap() + .unwrap(); + assert_eq!(report.sequence, 2); + assert!( + tokio::time::timeout(Duration::from_millis(30), boundary_rx.recv()) + .await + .is_err(), + "an unchanged installation acknowledgment must not trigger another report" + ); + sessions.send_replace(None); + assert!( + tokio::time::timeout(Duration::from_millis(30), report_rx.recv()) + .await + .is_err() + ); + task.abort(); + let _ = task.await; + } + + fn identity() -> EnvironmentIdentity { + EnvironmentIdentity { + attachment_epoch: "epoch".into(), + revision: 6, + policy_hash: "policy".into(), + } + } + + fn installation(credentials: &ProviderCredentialState) -> ProviderEnvironmentInstallation { + ProviderEnvironmentInstallation { + installation_id: credentials.snapshot().installation_id.clone(), + revision: 6, + session_id: uuid::Uuid::new_v4().to_string().parse().unwrap(), + } + } + + #[test] + fn same_revision_repair_rejects_the_previous_boundary_acknowledgment() { + let tracker = Tracker::new(); + let credentials = ProviderCredentialState::from_child_env_snapshot(6, HashMap::new()); + tracker.credentials_installed(identity(), &credentials, None); + let old = installation(&credentials); + credentials + .install_child_env_snapshot(6, HashMap::from([("TOKEN".into(), "restored".into())])); + tracker.credentials_installed(identity(), &credentials, None); + tracker.process_installed(old, &credentials); + assert!( + !tracker + .observation(&credentials) + .launch_environment_installed + ); + tracker.process_installed(installation(&credentials), &credentials); + assert!( + tracker + .observation(&credentials) + .launch_environment_installed + ); + } + + #[test] + fn policy_failure_and_generation_change_invalidate_installed_evidence() { + let tracker = Tracker::new(); + let credentials = ProviderCredentialState::from_child_env_snapshot(6, HashMap::new()); + let policy = openshell_policy::restrictive_default_policy(); + let engine = openshell_supervisor_network::opa::OpaEngine::from_proto(&policy).unwrap(); + tracker.credentials_installed(identity(), &credentials, None); + tracker.policy_activated(&identity(), 12, engine.generation_guard(0).unwrap()); + tracker.process_installed(installation(&credentials), &credentials); + assert!(tracker.observation(&credentials).policy_active); + engine.enter_fail_closed("test quarantine").unwrap(); + assert!(!tracker.observation(&credentials).policy_active); + let mut rejected = identity(); + rejected.policy_hash = "rejected".into(); + tracker.policy_install_failed(rejected, 13); + let observed = tracker.observation(&credentials); + assert_eq!(observed.config_revision, 13); + assert_eq!(observed.policy_hash, "rejected"); + assert!(!observed.credentials_installed); + assert!(!observed.launch_environment_installed); + } + + #[test] + fn expired_credentials_and_disconnected_boundary_never_complete() { + let tracker = Tracker::new(); + let credentials = ProviderCredentialState::from_child_env_snapshot(6, HashMap::new()); + tracker.credentials_installed(identity(), &credentials, Some(1)); + tracker.process_installed(installation(&credentials), &credentials); + assert_eq!( + tracker.observation(&credentials).reason, + i32::from(Reason::CredentialExpired) + ); + tracker.credentials_installed(identity(), &credentials, None); + tracker.process_installed(installation(&credentials), &credentials); + tracker.process_failed(); + assert!( + !tracker + .observation(&credentials) + .launch_environment_installed + ); + } +} diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index 3d451e13c8..23705a24e9 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -819,6 +819,7 @@ async fn handle_sandbox_delete(app: &mut App, tx: mpsc::UnboundedSender) } let req = openshell_core::proto::DeleteSandboxRequest { + request_id: String::new(), allow_missing: true, name: sandbox_name, workspace_scope: Some(named_workspace_scope(app.selected_sandbox_workspace())), @@ -1478,6 +1479,7 @@ fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { }; let req = openshell_core::proto::CreateSandboxRequest { + request_id: String::new(), name, spec: Some(openshell_core::proto::SandboxSpec { providers: selected_providers, @@ -1752,6 +1754,7 @@ fn spawn_create_provider(app: &App, tx: mpsc::UnboundedSender) { }; let req = openshell_core::proto::CreateProviderRequest { + request_id: String::new(), provider: Some(openshell_core::proto::Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { id: String::new(), @@ -1869,6 +1872,7 @@ fn spawn_update_provider(app: &App, tx: mpsc::UnboundedSender) { } let req = openshell_core::proto::UpdateProviderRequest { + request_id: String::new(), provider: Some(openshell_core::proto::Provider { metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { id: String::new(), @@ -1919,6 +1923,7 @@ fn spawn_delete_provider(app: &App, tx: mpsc::UnboundedSender) { tokio::spawn(async move { let req = openshell_core::proto::DeleteProviderRequest { + request_id: String::new(), allow_missing: true, name, workspace_scope: Some(named_workspace_scope(workspace)), @@ -1971,6 +1976,7 @@ fn spawn_draft_approve(app: &App, tx: mpsc::UnboundedSender) { tokio::spawn(async move { let req = openshell_core::proto::ApproveDraftChunkRequest { + request_id: String::new(), name, chunk_id, workspace_scope: Some(named_workspace_scope(workspace)), @@ -2016,6 +2022,7 @@ fn spawn_draft_reject(app: &App, tx: mpsc::UnboundedSender) { tokio::spawn(async move { let req = openshell_core::proto::RejectDraftChunkRequest { + request_id: String::new(), name, chunk_id, reason: String::new(), @@ -2066,6 +2073,7 @@ fn spawn_draft_approve_all( }) .collect(); let req = openshell_core::proto::ApproveAllDraftChunksRequest { + request_id: String::new(), name, include_security_flagged: false, workspace_scope: Some(named_workspace_scope(workspace)), diff --git a/deploy/deb/control.in b/deploy/deb/control.in index 9f77f8775d..e0975d4d4d 100644 --- a/deploy/deb/control.in +++ b/deploy/deb/control.in @@ -9,8 +9,9 @@ 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. + installs the openshell CLI, standalone policy prover, 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/helm/openshell/templates/clusterrole.yaml b/deploy/helm/openshell/templates/clusterrole.yaml index 02ace73a12..e48c27cdd2 100644 --- a/deploy/helm/openshell/templates/clusterrole.yaml +++ b/deploy/helm/openshell/templates/clusterrole.yaml @@ -95,7 +95,9 @@ rules: verbs: ["create", "get"] - apiGroups: [""] resources: ["secrets"] - verbs: ["create"] + # Bootstrap Secrets are generation-scoped. Recovery lists them by label and + # deletes stale generations with UID preconditions before retrying creation. + verbs: ["create", "list", "delete"] - apiGroups: ["networking.k8s.io"] resources: ["networkpolicies"] verbs: ["create", "get"] diff --git a/deploy/helm/openshell/templates/role.yaml b/deploy/helm/openshell/templates/role.yaml index dac863b805..c781b46e3d 100644 --- a/deploy/helm/openshell/templates/role.yaml +++ b/deploy/helm/openshell/templates/role.yaml @@ -53,7 +53,9 @@ rules: verbs: ["create", "get"] - apiGroups: [""] resources: ["secrets"] - verbs: ["create"] + # Bootstrap Secrets are generation-scoped. Recovery lists them by label and + # deletes stale generations with UID preconditions before retrying creation. + verbs: ["create", "list", "delete"] - apiGroups: ["networking.k8s.io"] resources: ["networkpolicies"] verbs: ["create", "get"] diff --git a/deploy/helm/openshell/tests/clusterrole_test.yaml b/deploy/helm/openshell/tests/clusterrole_test.yaml index ec2f42082c..9639232c32 100644 --- a/deploy/helm/openshell/tests/clusterrole_test.yaml +++ b/deploy/helm/openshell/tests/clusterrole_test.yaml @@ -69,7 +69,7 @@ tests: resourceNames: ["custom-client-tls"] verbs: ["get", "patch"] - - it: limits operator bootstrap secret access to create when TLS and credential storage are disabled + - it: grants operator bootstrap secret lifecycle permissions when TLS and credential storage are disabled set: server.drivers.kubernetes.workspaceMode: operator server.disableTls: true @@ -79,7 +79,7 @@ tests: content: apiGroups: [""] resources: ["secrets"] - verbs: ["create"] + verbs: ["create", "list", "delete"] - notContains: path: rules content: @@ -107,7 +107,7 @@ tests: content: apiGroups: [""] resources: ["secrets"] - verbs: ["create"] + verbs: ["create", "list", "delete"] - it: restricts managed copies to image-pull secrets when TLS is disabled set: @@ -128,7 +128,7 @@ tests: content: apiGroups: [""] resources: ["secrets"] - verbs: ["create"] + verbs: ["create", "list", "delete"] - it: omits secrets rule entirely in shared mode set: @@ -162,7 +162,7 @@ tests: content: apiGroups: [""] resources: ["secrets"] - verbs: ["create"] + verbs: ["create", "list", "delete"] - it: grants operator sandbox-runtime companion permissions set: @@ -185,4 +185,4 @@ tests: content: apiGroups: [""] resources: ["secrets"] - verbs: ["create"] + verbs: ["create", "list", "delete"] diff --git a/deploy/helm/openshell/tests/sandbox_namespace_test.yaml b/deploy/helm/openshell/tests/sandbox_namespace_test.yaml index d02300e428..6ec7ae4d65 100644 --- a/deploy/helm/openshell/tests/sandbox_namespace_test.yaml +++ b/deploy/helm/openshell/tests/sandbox_namespace_test.yaml @@ -68,6 +68,12 @@ tests: apiGroups: [""] resources: ["services"] verbs: ["create", "get"] + - contains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + verbs: ["create", "list", "delete"] - it: uses explicit sandboxNamespace for sandbox RoleBinding template: templates/rolebinding.yaml diff --git a/docs/about/installation.mdx b/docs/about/installation.mdx index a40d908fa3..33b4dfc95f 100644 --- a/docs/about/installation.mdx +++ b/docs/about/installation.mdx @@ -16,7 +16,7 @@ Install OpenShell with a single command: curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh | sh ``` -The script detects your operating system and installs the OpenShell CLI and gateway with your native package manager. It then starts the local gateway server so you can begin creating sandboxes. +The script detects your operating system and installs the OpenShell CLI, standalone policy prover, and gateway with your native package manager. It then starts the local gateway server so you can begin creating sandboxes. You can also download release artifacts directly from the [OpenShell GitHub Releases](https://github.com/NVIDIA/OpenShell/releases) page. @@ -42,7 +42,7 @@ For detailed driver behavior, refer to [Sandbox Compute Drivers](/reference/sand ## macOS -On macOS, the install script uses Homebrew. The Homebrew package installs the `openshell` CLI, the gateway binary, and a Homebrew-managed gateway service. +On macOS, the install script uses Homebrew. The Homebrew package installs the `openshell` CLI, `openshell-prover`, the gateway binary, and a Homebrew-managed gateway service. The Homebrew service uses the gateway's built-in `127.0.0.1:17670` listener and generates a local mTLS bundle on install. The installer registers `https://localhost:17670` with the CLI so TLS uses a DNS name covered by the generated certificate. The formula creates a Homebrew prefix config, such as `/opt/homebrew/var/openshell/gateway.toml`, without overriding `bind_address`. Docker Desktop and Podman Machine reuse the primary listener for sandbox callbacks when they can reach it. The gateway reads `~/.config/openshell/gateway.toml` instead when that file exists. Homebrew upgrades migrate exact package-generated schema-v1 prefix configs, including the affected IPv6 variant. They preserve edited prefix configs and all user configs. Follow the [schema version 2 migration steps](/reference/gateway-config#migrate-to-schema-version-2) for an edited v1 file. @@ -57,9 +57,9 @@ brew services restart openshell ## Linux -On Fedora and RHEL, the install script uses RPM packages. The RPM installs the `openshell` CLI, the `openshell-gateway` daemon, and a systemd user service. +On Fedora and RHEL, the install script uses RPM packages. The RPMs install the `openshell` CLI, `openshell-prover`, the `openshell-gateway` daemon, and a systemd user service. -On Debian and Ubuntu, the install script uses a Debian package. The Debian package installs the `openshell` CLI, the `openshell-gateway` daemon, VM sandbox support, and a systemd user service. +On Debian and Ubuntu, the install script uses a Debian package. The Debian package installs the `openshell` CLI, `openshell-prover`, the `openshell-gateway` daemon, VM sandbox support, and a systemd user service. Linux packages require glibc 2.28 or newer. The installer checks libc before downloading packages and exits with an error on older glibc versions, Alpine, musl-based distributions, or unknown libc environments. diff --git a/docs/extensibility/supervisor-middleware.mdx b/docs/extensibility/supervisor-middleware.mdx index 9f3c723b16..13935436c4 100644 --- a/docs/extensibility/supervisor-middleware.mdx +++ b/docs/extensibility/supervisor-middleware.mdx @@ -22,6 +22,8 @@ For each inspected HTTP request, the supervisor: 5. Re-checks body-aware protocol policy (GraphQL, JSON-RPC, MCP) after each stage that replaces the body. Every middleware receives a payload the policy admits, and a transformation cannot smuggle a denied or unparseable operation to a later stage or the upstream. 6. Applies allowed transformations, injects provider credentials, and forwards the request. +Response middleware advertising `HTTP_RESPONSE/PRE_RETURN` inspects the final upstream response before OpenShell returns it to the workload. Its preflight includes upstream `Content-Length`, `Content-Encoding`, and `Content-Range` fields as read-only metadata, except when `Connection` nominates the field as hop-by-hop. Middleware cannot write or remove these fields. OpenShell computes downstream framing separately and emits the final `Content-Length` or `Transfer-Encoding` exactly once after middleware processing. + For an RFC 6455 upgrade over `ws://` or `wss://`, the supervisor first finds every host-matched attachment, then selects only implementations that advertise `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. It opens one ordered, phase-specific `EvaluateWebSocketSession` stream per selected stage. OpenShell sends `WebSocketSessionEvent` values, while the service returns `WebSocketSessionEventResult` values only for preflight and message events; session start and end are notifications. Future upstream-to-client inspection uses the same RPC with `PRE_RETURN`; an implementation that advertises both phases receives two independent streams for the WebSocket session. An attachment without the selected binding can still inspect the HTTP upgrade request when it advertises the HTTP binding, but it is not a failed WebSocket stage. OpenShell allows post-upgrade traffic and emits an informational `binding_not_selected` coverage event for that attachment. 1. A preflight before the upgrade is sent upstream. The stage chooses `INSPECT`, voluntary `SKIP`, or authoritative `DENY` and may return a bounded diagnostic reason, stable reason code, findings, and metadata. OpenShell runs selected preflights concurrently; any `DENY` rejects the upgrade regardless of `on_error`. @@ -144,6 +146,8 @@ See [Policy Schema](/reference/policy-schema#network-middleware) for the complet | `fail_closed` | Denies the HTTP request or closes the WebSocket when the stage fails. This is the default. | | `fail_open` | Skips the failed HTTP stage. For a broken WebSocket stage stream, disables that stage for the rest of the connection and continues the remaining chain. | +A valid upstream response can exceed the middleware envelope limits or contain header bytes that the middleware protocol cannot represent. OpenShell relays the original response when every selected response stage uses `fail_open`; any selected `fail_closed` stage causes the canonical 502 delivery failure. Malformed or unsafe HTTP does not qualify for this bypass. + Use `fail_open` only when bypassing the middleware preserves the intended security policy. OpenShell emits a detection finding when a failed stage is bypassed and a separate state-change finding when a WebSocket stage is disabled for the session. Capability coverage is separate from failure handling. A host-matched HTTP-only attachment does not join the WebSocket chain, regardless of `on_error`. Binary messages are outside the V1 text-message binding and pass through even when a selected stage is `fail_closed`. OpenShell records both states as informational coverage events so operators do not mistake pass-through traffic for inspected traffic. If a deployment requires all WebSocket message classes to be inspected, V1 cannot express that requirement. @@ -220,10 +224,16 @@ Middleware activity is emitted through OpenShell's OCSF logging: See [Logging](/observability/logging) for log access and [OCSF JSON Export](/observability/ocsf-json-export) for structured export. +## Runnable example + +The [content guard example](https://github.com/NVIDIA/OpenShell/tree/main/examples/supervisor-middleware-content-guard) matches configured literal terms in UTF-8 request bodies, complete response bodies, and client WebSocket text messages. It supports redaction and denial. Responses require whole-body inspection; unavailable inspection or invalid UTF-8 invokes the configured `on_error` policy. It is not a general PII detector. + +The example includes a policy, local fixture, and smoke launcher. + ## Current Limitations - Middleware applies only through operation bindings advertised by each implementation. For protocols that have no supported middleware operation at all, such as HTTP/2 prior knowledge or non-HTTP TCP, the existing uninspectable-traffic gate denies a host match containing `fail_closed` and relays an all-`fail_open` match with a detection finding. -- The typed operation and phase pairs are `HTTP_REQUEST/PRE_CREDENTIALS` and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. +- The typed operation and phase pairs are `HTTP_REQUEST/PRE_CREDENTIALS`, `HTTP_RESPONSE/PRE_RETURN`, and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. - A host match does not imply every advertised operation: an HTTP-only attachment can inspect the upgrade GET, then post-upgrade traffic passes with `binding_not_selected` coverage. - The V1 WebSocket binding inspects complete client text messages only. Binary messages pass with `unsupported_message_type` coverage for active stages; control frames and upstream-to-client messages remain outside the middleware operation. - Selection uses destination host include and exclude patterns. diff --git a/docs/kubernetes/sandbox-runtime.mdx b/docs/kubernetes/sandbox-runtime.mdx index 319619ee7f..aa039ad027 100644 --- a/docs/kubernetes/sandbox-runtime.mdx +++ b/docs/kubernetes/sandbox-runtime.mdx @@ -110,6 +110,13 @@ creates a new generation with new Secrets and a replacement supervisor Pod while preserving the workspace PVC. The namespace-wide workload fence remains in place across sandbox generations. +If provisioning is interrupted, recovery first confirms that the old workload +Pod is gone. It then lists generation Secrets by sandbox and component labels, +deletes each stale Secret with a UID precondition, and clears the rollback state +so the next generation can be created. The Helm chart grants the gateway +`create`, `list`, and `delete` access to Secrets for this lifecycle. Listing is +required even when no generation Secrets remain. + ## Check Cluster Requirements This architecture requires the following cluster behavior: diff --git a/docs/providers/profiles.mdx b/docs/providers/profiles.mdx index 4255a1f89b..06f17a42fb 100644 --- a/docs/providers/profiles.mdx +++ b/docs/providers/profiles.mdx @@ -40,7 +40,7 @@ Provider profiles include these user-facing features: - Provider instances whose submitted credentials can be stored by a configured gateway credential driver. - Profile-backed credential discovery for explicit `openshell provider create --from-existing` and `openshell provider update --from-existing` flows. The built-in `google-vertex-ai` profile also supplements discovery with Vertex config env vars such as `VERTEX_AI_PROJECT_ID` and `VERTEX_AI_REGION`. - Just-in-time effective policy composition from sandbox policy plus attached provider profiles. -- Runtime sandbox provider lifecycle commands under `openshell sandbox provider list|attach|detach`. +- Runtime sandbox provider commands under `openshell sandbox provider list|attach|detach|status`, with an option to wait until the sandbox applies a change. - Credential refresh configuration with `openshell provider refresh status|configure|rotate|delete`. - Credential expiry metadata with `openshell provider update --credential-expires-at`; values accept Unix epoch milliseconds or ISO/RFC3339 timestamps. - Dynamic token grants that use the sandbox's SPIFFE JWT-SVID as an OAuth2 client assertion and inject short-lived tokens into supported headers for matching profile endpoints. @@ -968,29 +968,66 @@ Composition follows these rules: ## Attach and Detach Providers -Attach an existing provider to a running sandbox: +Attach an existing provider and wait until the sandbox can use it: ```shell -openshell sandbox provider attach provider-demo work-github +openshell sandbox provider attach provider-demo work-github --wait --timeout 30 ``` -Detach a provider: +Detach a provider and wait until the sandbox stops resolving its credentials: ```shell -openshell sandbox provider detach provider-demo work-github +openshell sandbox provider detach provider-demo work-github --wait --timeout 30 ``` Attach and detach are idempotent. Attach validates that the provider exists before mutating the sandbox, and provider deletion fails while the provider is attached to any sandbox. +### Inspect Provider Readiness + +Without `--wait`, attach, detach, and update confirm that the gateway saved the change. Add `--wait` when the next step depends on that change taking effect. The command succeeds after the sandbox applies the matching credentials and policy, and updates the environment used by new processes. + +Each result includes a change record called a `receipt` in the API. Its ID lets you check the same change later, including after a timeout: + +```shell +openshell sandbox provider status provider-demo work-github --output json +openshell sandbox provider status provider-demo work-github --receipt RECEIPT_ID --wait --timeout 30 +``` + +Replace `RECEIPT_ID` with the `receipt_id` returned by attach, detach, or update. The ID always refers to the original change. If a later change replaces it, the status is `superseded` and the wait ends without reporting success. + +If attach, detach, or update reports `CONFIG_OPERATION_STORAGE_UNCERTAIN`, the change may already be saved even though the gateway could not record its readiness receipt. Do not blindly retry the mutation: inspect the provider and sandbox state and reconcile the saved change first. A receipt may be unavailable, so an error does not establish that the mutation was rolled back or that the sandbox is ready. + +Readiness states have these meanings: + +- `persisted`: the gateway saved the change; the command has not checked the sandbox yet. +- `pending`: the sandbox has not confirmed all parts of the change. +- `ready`: the sandbox applied the requested provider credentials, policy, and environment for new processes. +- `revoked`: the detached provider's credentials no longer resolve, and new processes do not receive its credential references. +- `withheld`: a credential or supervisor configuration prevents the sandbox from applying the change. +- `failed`: the sandbox could not install the credentials, policy, or process environment. +- `superseded`: a later change replaced the original request. + +The default wait is 30 seconds and the maximum is 3600 seconds. The timeout starts after the gateway saves the change and includes time spent requesting status. If time runs out, the command exits with an error and reports `wait_outcome: timed_out` with the last known state. The change remains saved and may finish applying later. Check its ID again to learn the result. + +An unavailable supervisor, an expired report, a failed installation, or a missing process-environment acknowledgment cannot produce `ready` or `revoked`. After a reconnect or restart, the current authenticated supervisor must report its installed state again. + +JSON and YAML output include change IDs, requested and installed revisions, timestamps, reason categories, and a result for each sandbox. Revision strings identify configurations; compare them for equality rather than numerical order. Status output excludes credential values, credential references, authorization headers, and raw installation errors. + +The `persisted_time`, `observed_time`, and `evaluated_time` fields use RFC 3339 timestamp strings. An absent `observed_time` means the current supervisor session has not supplied accepted evidence. API operation timestamps use protobuf `Timestamp`, and report intervals and observation lifetimes use protobuf `Duration`, following the [protobuf time representation](/reference/protobuf-time-types). + +The API's `operation` field records the common operation's historical outcome; its `operation_id` equals the receipt ID. Use the provider `state` and the wait result for current readiness. A disconnected supervisor can make the live state pending even after the operation previously applied, and a newer change can supersede the live result. Historical completion does not override those checks. + ### Runtime Limitations -Provider attach and detach update the persisted sandbox provider list. Running sandboxes poll for provider environment revisions and effective policy changes. +Running sandboxes periodically check for provider and policy changes. Use `--wait` or `sandbox provider status` to confirm when a saved change has taken effect. The policy effect applies to future effective policy reads after the sandbox observes the update. The credential environment effect applies only to new process launches after the update is observed, such as later SSH, exec, or SFTP sessions. -Already-running processes keep the placeholder environment they started with. OpenShell does not mutate a live process environment after provider attach, detach, or credential update. The proxy resolves existing placeholders against current credentials and bindings, so rotation, expiry, endpoint changes, and detach take effect without restarting the process. If a long-running process needs a newly attached provider credential placeholder, restart that process or launch a new process after the sandbox has observed the provider update. +Already-running processes keep the placeholder environment they started with. For ordinary static credentials, an existing reference retains its selected revision after a value update; readiness does not retarget that reference to the replacement value. After an update wait succeeds, launch a new process to receive the updated credential reference. Gateway-managed refresh follows its own reference lifecycle. Expiry, endpoint authorization, and acknowledged detach continue to apply when the proxy resolves retained references. + +For a static provider, the sequence is attach, wait, then launch client A; update, wait, then launch client B. B's first request uses the newly installed credential. Readiness does not establish that A has stopped using its retained revision or that an old upstream key can be retired. -Detaching a provider removes its provider policy layer from future effective policy reads, revokes resolution for its existing placeholders, and removes its credential placeholders from future process environments. It does not remove the placeholder strings from already-running process environments. +An acknowledged detachment removes its provider policy layer from the active effective policy, revokes future resolution for its existing placeholders, and removes its credential placeholders from future process environments. It does not remove strings from already-running process environments or undo requests already forwarded upstream. OpenShell rejects provider updates and refresh configuration when they would make two providers attached to the same sandbox expose the same active credential environment key. It also rejects attached provider sets with ambiguous dynamic token grants at equal host/path specificity. Use provider-specific credential names and make one dynamic grant selector more specific when one sandbox needs multiple providers with overlapping upstream concepts. diff --git a/docs/reference/api-errors.mdx b/docs/reference/api-errors.mdx index 9f77169ab0..d6c2c07788 100644 --- a/docs/reference/api-errors.mdx +++ b/docs/reference/api-errors.mdx @@ -31,6 +31,9 @@ Recognized gateway reasons include the following. | `INVALID_ARGUMENT` | `INVALID_ARGUMENT` | Correct the fields listed in `BadRequest`. | | `RESOURCE_VERSION_CONFLICT` | `ABORTED` | Read the resource again and construct a new conditional write. `metadata.recovery` is `REFRESH_STATE`; `current_resource_version` is included when known. | | `PROFILE_SOURCE_UNAVAILABLE` | `UNAVAILABLE` | Retry a profile snapshot read after at least the supplied delay. | +| `REQUEST_ID_PAYLOAD_MISMATCH` | `FAILED_PRECONDITION` | Keep the original payload for that request ID. Inspect the original operation before submitting a different one. | +| `REQUEST_OUTCOME_UNCERTAIN` | `FAILED_PRECONDITION` | An attempt is admitted but has no confirmed replayable success. Observe resource state and reconcile effects. Do not switch to a new ID to bypass the admission. | +| `REQUEST_REPLAY_UNAVAILABLE` | `FAILED_PRECONDITION` | The original scope, resource, interceptor transformation, or fingerprint key is no longer replayable. Reconcile effects; the gateway does not execute the request again. Missing private-key material can also reject admission before work starts. | ## Status and retry guidance @@ -85,6 +88,108 @@ Go and TypeScript add typed detail fields to their existing error types. No SDK automatically retries a mutation as a result of decoding these details. +## Durable request admission + +Thirty user-callable unary RPCs accept an optional `request_id` in their protobuf requests. + +| Resource | RPCs | +|---|---| +| Workspace | `CreateWorkspace`, `DeleteWorkspace` | +| Workspace member | `AddWorkspaceMember`, `RemoveWorkspaceMember` | +| Sandbox template | `CreateSandboxTemplate`, `DeleteSandboxTemplate` | +| Sandbox | `CreateSandbox`, `DeleteSandbox`, `StartSandbox`, `StopSandbox`, `AttachSandboxProvider`, `DetachSandboxProvider` | +| Service | `ExposeService`, `DeleteService` | +| Provider | `CreateProvider`, `UpdateProvider`, `DeleteProvider`, `ConfigureProviderRefresh`, `DeleteProviderRefresh`, `RotateProviderCredential` | +| Provider profile | `ImportProviderProfiles`, `UpdateProviderProfiles`, `DeleteProviderProfile` | +| Policy and config | `UpdateConfig`, `ApproveDraftChunk`, `RejectDraftChunk`, `EditDraftChunk`, `UndoDraftChunk`, `ApproveAllDraftChunks`, `ClearDraftChunks` | + +Use a nonzero, hyphenated UUID of exactly 36 characters. Uppercase and lowercase +forms identify the same request. An empty ID preserves the existing behavior +without deduplication. This ID is separate from transport correlation metadata. +The gateway scopes it to the authenticated identity provider, OIDC issuer, +subject, RPC method, and requested workspace. Use the same identity, scope, ID, +and payload when checking an admitted attempt. Map ordering does not affect the +payload fingerprint; changed values or protobuf message presence do. + +For `CreateWorkspace` and `DeleteWorkspace`, the requested workspace is the +request's `name`. The same caller can reuse an ID for the same method on different +workspace names. Within one workspace name, a changed payload still returns +`REQUEST_ID_PAYLOAD_MISMATCH`. Workspace deletion replay does not require the +deleted workspace to exist and does not delete a same-name replacement. + +Pre-release gateways that used unscoped workspace admission require reconciliation +before upgrading. Their workspace create/delete receipts do not replay under the +corrected name-scoped namespace. Do not retry those IDs after upgrading without +reconciling the original operations' effects. + +The gateway durably admits one owner before executing the mutation. Concurrent +duplicates either replay its confirmed success or return +`REQUEST_OUTCOME_UNCERTAIN`. Disconnecting or cancelling the client does not stop +admitted work. An error, interrupted process, or failed success-record write +leaves the admission unresolved. No gateway replica takes over that admission, +even after restart or after 24 hours. Status codes alone do not prove that the +attempt had no effects. + +Successful results have a 24-hour replay window, measured from durable completion. +A successful replay includes `openshell-replayed: true` response metadata and +does not extend the window. After it expires, the same ID can admit a new +execution. Do not retry an old operation after that window without reconciling +its effects. Unresolved admissions never expire. + +Every replay checks current authorization, including membership and permission +to assign workspace administrators. A replacement workspace makes workspace-scoped +replay unavailable. Target readiness, conditional-write versions, and draft review +tokens are first-execution preconditions, not conditions to execute again. + +| Result family | Replay behavior | +|---|---| +| Workspace, membership, template, provider, and profile resources | Load the original UUID at its recorded version. Missing or changed resources make replay unavailable. Provider credentials remain redacted. | +| Sandbox resources | Load the original UUID with its current state, including newer status or configuration. Attach/detach flags describe the original operation. A missing original sandbox makes replay unavailable. | +| Provider readiness receipts | Return the original attach, detach, or update receipts and mutation ID, including the original update target set. Later attachment changes do not replace these receipts. Missing operation evidence makes replay unavailable without executing the mutation again. | +| Service endpoint | Require the original endpoint version and sandbox identity. Return the recorded URL. | +| Refresh status | Return current status for the original provider, refresh record, and authorization epoch. Reconfiguration or removal makes replay unavailable. Rotation is not repeated. | +| Policy and config | Return the original versions, counts, and nonsecret annotations while the original sandbox exists. Global config has no sandbox guard. | +| Deletion | Return the original outcome without requiring the deleted target or parent to exist and without deleting a replacement. `ACCEPTED` remains an acknowledgment of the original cleanup, not proof of completion. | + +Profile imports and updates also preserve their original public diagnostics and +success flags. Profile declarations, diagnostic source labels, and annotations +must not contain secrets. + +For sandbox, service, provider, profile, and policy/config methods, fingerprints +use HMAC with domain-separated material derived from the configured gateway JWT +private key, or the primary TLS private key when JWT signing is not configured. +These methods require readable, stable private-key material when you supply an +ID. Replicas sharing a database must share that material. Changing it makes +existing protected receipts unavailable until their successful replay window +expires; unresolved admissions remain protected indefinitely. Workspace, +membership, and template methods retain their original fingerprint format. + +Gateway interceptors run their current modification and validation phases on +every attempt, including replay. They cannot add, remove, or change `request_id`. +The gateway fingerprints the original client payload and separately guards the +effective transformed payload and workspace. A changed transformation makes +replay unavailable. A current denial remains authoritative. Successful replay +does not invoke post-commit observers again. Post-commit observation remains +best-effort; this is not a durable delivery queue. + +Replay rows contain fingerprints, resource references, and explicitly selected +public diagnostic or scalar outcomes, not credential-bearing response snapshots. +Completed receipts are limited to 64 KiB. A failure to capture a bounded receipt +after execution leaves the admission unresolved. Each caller can +hold at most 1,000 durable admissions. At capacity, the gateway removes expired +successes; if no space remains, it rejects new admissions with +`RESOURCE_EXHAUSTED`. Existing records remain protected. Unresolved records +require operator investigation; there is no automatic reset or takeover API. +The gateway also limits detached admission workers to 64 per process and these +request messages to 4 MiB. + +Supply IDs through generated/raw RPC clients. Curated SDK request-ID helpers and +automatic retry policies are not part of this contract yet. Exec, SSH sessions, +rootfs staging, and supervisor-authenticated mutations do not gain deduplication +from this feature. Sandbox principals cannot opt into `UpdateConfig` admission. +Check gateway compatibility +before relying on IDs; older protobuf servers can silently ignore unknown fields. + ## Deletion outcomes Delete, membership-removal, and SSH-revocation RPCs return a typed outcome. diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index 9940f2ee2e..04890f8843 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -357,13 +357,13 @@ max_payload_bytes = 262144 timeout = "500ms" ``` -Each service implements the supervisor middleware gRPC contract and exposes bindings through `Describe`. Policies reference the operator-owned registration `name`, attaching the complete middleware and all of its bindings. Bindings are identified by operation and phase. A manifest may expose at most one binding for each operation and phase pair. V1 supports `HttpRequest/pre_credentials` and `WebSocketMessage/pre_credentials`, so a service can inspect HTTP, WebSocket, or both. Registration names must be unique, and operator-run registrations cannot claim the reserved `openshell/` namespace. The service-reported manifest name is diagnostic metadata and does not need to match the registration name. +Each service implements the supervisor middleware gRPC contract and exposes bindings through `Describe`. Policies reference the operator-owned registration `name`, attaching the complete middleware and all of its bindings. Bindings are identified by operation and phase. A manifest may expose at most one binding for each operation and phase pair. V1 supports `HttpRequest/pre_credentials`, `HttpResponse/pre_return`, and `WebSocketMessage/pre_credentials`. Registration names must be unique, and operator-run registrations cannot claim the reserved `openshell/` namespace. The service-reported manifest name is diagnostic metadata and does not need to match the registration name. The gateway connects to every registered service and validates `Describe` before it starts. The service must therefore be running before the gateway. Policy creation and full policy updates call `ValidateConfig`; an unavailable service or invalid middleware configuration rejects the policy before persistence. -`max_payload_bytes` is the shared operator limit for inspectable logical payloads across every binding exposed by the service. It caps HTTP request and replacement bodies as well as complete WebSocket text messages and replacements. The value must be greater than zero, no larger than each binding's advertised `max_payload_bytes` capability, and no larger than the 4 MiB platform maximum. OpenShell rejects oversized values instead of silently clamping them. Binary WebSocket messages are not exposed to V1 middleware, so this field does not limit binary pass-through. Middleware gRPC servers should allow messages of at least 4 MiB plus 293 KiB so a maximum-size payload and its protobuf envelope fit on the transport. +`max_payload_bytes` is the shared operator limit for inspectable logical payloads across every binding exposed by the service. It caps HTTP request and response units, replacement bodies, and complete WebSocket text messages and replacements. Whole-response inspection uses it as the stage's total body limit. Streaming response inspection applies it to each unit. The value must be greater than zero, no larger than each binding's advertised `max_payload_bytes` capability, and no larger than the 4 MiB platform maximum. OpenShell rejects oversized values instead of silently clamping them. Binary WebSocket messages are not exposed to V1 middleware, so this field does not limit binary pass-through. Middleware gRPC servers should allow messages of at least 4 MiB plus 293 KiB so a maximum-size payload and its protobuf envelope fit on the transport. -`timeout` is the operator-configured service-wide RPC timeout. It accepts the same compact duration syntax as gateway interceptors: an integer followed by `ms` or `s`, such as `500ms` or `2s`. Values must be between `10ms` and `30s`, inclusive. Omit the field to use the 500 ms platform default. A binding may advertise a shorter `timeout` in the `Describe` manifest, but it cannot extend the operator-configured deadline; OpenShell uses the smaller value. OpenShell validates both levels before accepting the service. The operator-configured service timeout applies to `Describe` and `ValidateConfig`. The effective binding timeout applies only to `EvaluateHttpRequest`, WebSocket preflight, and each WebSocket message. An accepted WebSocket stream has no connection-wide RPC deadline. +`timeout` is the operator-configured service-wide RPC timeout. It accepts the same compact duration syntax as gateway interceptors: an integer followed by `ms` or `s`, such as `500ms` or `2s`. Values must be between `10ms` and `30s`, inclusive. Omit the field to use the 500 ms platform default. A binding may advertise a shorter `timeout` in the `Describe` manifest, but it cannot extend the operator-configured deadline; OpenShell uses the smaller value. OpenShell validates both levels before accepting the service. The operator-configured service timeout applies to `Describe` and `ValidateConfig`. The effective binding timeout applies to HTTP request evaluation, HTTP response preflight and unit exchanges, WebSocket preflight, and each WebSocket message. Accepted streaming protocols have no connection-wide RPC deadline. The service `grpc_endpoint` supports plaintext `http://` and TLS `https://`. HTTPS uses the platform trust store unless `tls_ca_cert_path` names a certificate-only PEM bundle. OpenShell rejects bundles containing private keys, loads the certificates at gateway startup, and distributes only public certificates to sandbox supervisors; normal TLS hostname verification still applies. `audience` sets the exact audience for gateway-minted service tokens and defaults to `urn:openshell:extension:middleware:`. After authenticated `Describe` succeeds, OpenShell treats a non-empty manifest `expected_audience` as a consistency assertion and refuses to start when it differs from the configured audience. A strict verifier may reject an incorrect audience before returning the manifest. diff --git a/docs/reference/policy-prover.mdx b/docs/reference/policy-prover.mdx new file mode 100644 index 0000000000..4e251adc3e --- /dev/null +++ b/docs/reference/policy-prover.mdx @@ -0,0 +1,216 @@ +--- +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +title: "Standalone Policy Prover" +sidebar-title: "Policy Prover" +description: "Install and use the standalone OpenShell policy prover to check a local candidate policy against a managed boundary." +keywords: "Generative AI, Cybersecurity, Policy, Prover, Boundary, Containment, CI" +position: 4 +--- + +`openshell-prover` checks whether the authority in a local candidate policy is +contained within a local boundary policy. The command reads files from the host +and does not connect to an OpenShell gateway. + +The candidate must be the fully composed effective policy after the proposed +change, including any provider-contributed authority. The boundary is an +operator-owned ceiling. It does not grant authority by itself. + +## Install the Prover + +The standard OpenShell installer includes `openshell-prover`: + +```shell +curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh | sh +openshell-prover --version +``` + +The prover remains independent of the gateway at runtime. If you only need the +standalone binary, use the artifacts listed in the +[Support Matrix](/reference/support-matrix#standalone-policy-prover). These +artifacts and `openshell-prover-checksums-sha256.txt` are attached to +[OpenShell releases](https://github.com/NVIDIA/OpenShell/releases). + +The release archive includes the solver linkage required by the executable. +It does not require the main `openshell` command, a gateway configuration, or +a separate Z3 installation. + +## Check a Policy Boundary + +Create `boundary.yaml` with this boundary policy: + +```yaml +version: 1 +filesystem_policy: + read_only: + - /usr + - /etc +``` + +Create `candidate.yaml` with this contained candidate: + +```yaml +version: 1 +filesystem_policy: + read_only: + - /usr +``` + +Run the check: + +```shell +openshell-prover check candidate.yaml --boundary boundary.yaml +``` + +A contained candidate prints `result: within_boundary` and exits with status `0`. +To see an exceeding result and its counterexample, replace `candidate.yaml` +with a policy that grants writes to `/tmp`. The boundary grants no write +access: + +```yaml +version: 1 +filesystem_policy: + read_only: + - /usr + read_write: + - /tmp +``` + +```shell +openshell-prover check candidate.yaml --boundary boundary.yaml +``` + +To check the current effective policy of an existing sandbox, export it without +display metadata: + +```shell +openshell sandbox get my-sandbox --policy-only > candidate.yaml +openshell-prover check candidate.yaml --boundary boundary.yaml +``` + +This export includes provider-contributed rules. For a proposed change that is +not active, supply the complete post-change effective policy. The standalone +prover does not compose a base policy with provider rules. + +Use JSON when a script consumes the result: + +```shell +openshell-prover check candidate.yaml \ + --boundary boundary.yaml \ + --output json +``` + +The JSON object includes the result, exit code, input paths, prover version, +model version, checked policy version, and modeled domains. The documented +semantics and environmental conditions for that scope are tied to its model +version. An exceeding result also includes a filesystem or network +counterexample. Automation should use `result` and `reason_code` instead of +parsing the human-readable explanation. + +| Field | When populated | +|---|---| +| `counterexample` | An object for `exceeds_boundary`; otherwise `null`. | +| `reason_code` | A stable identifier for an emitted `error`, `unsupported`, or `inconclusive` result; otherwise `null`. | +| `reason` | A human-readable explanation paired with `reason_code`; otherwise `null`. | + +The stable reason codes are `invalid_input`, `unsupported_policy_shape`, +`unresolved_workdir`, `unresolved_binary_path`, +`unresolved_filesystem_path`, `solver_timeout`, `solver_unknown`, +`resource_limit`, `invalid_witness`, and `cancelled`. + +The solver has a finite 10-second default budget. Set a different positive +budget with an integer followed by `ms`, `s`, or `m`: + +```shell +openshell-prover check candidate.yaml \ + --boundary boundary.yaml \ + --timeout 30s \ + --output json +``` + +## Exit Codes + +| Exit | Result | Meaning | +|---|---|---| +| `0` | `within_boundary` | Containment was established for the reported model scope. | +| `1` | `exceeds_boundary` | The candidate exceeds the boundary; inspect the counterexample. | +| `2` | `error` | Arguments, input files, policy syntax, or command execution prevented a valid check. | +| `3` | `unsupported` or `inconclusive` | The model cannot soundly cover the policy shape, or the solver did not reach a determination. | +| `130` | `inconclusive` when graceful handling completes | The user interrupted the command with Ctrl-C on Unix; a second or very early interruption may prevent output. | + +Only exit `0` means the verification succeeded. Treat unsupported and +inconclusive results as failures in CI. + +## Interpretation and Limits + +The initial containment model covers filesystem paths, L4 network authority, +and enforced REST method and path authority, including explicit REST denies. +The result object reports the domains used for each check. Policies that use +recognized authority outside that model return `unsupported` rather than +silently ignoring it. + +Both inputs use the same bounded YAML/JSON parser and authored policy schema as +OpenShell. Unknown fields, duplicate keys, malformed field types, and unsupported +managed `metadata` or `review` annotations return `error` with +`reason_code: invalid_input` and exit `2`. Schema-valid controls outside the +containment model return `unsupported` and exit `3`. + +The prover applies aggregate limits across the candidate and boundary before +semantic shape validation: 1,024 network rules, 4,096 endpoints, 4,096 binary +selectors, 65,536 authored port entries, 16,384 REST rules, 4 KiB per modeled +pattern, and 1 MiB of modeled pattern text. Exceeding any limit returns +`inconclusive` with `reason_code: resource_limit`. A cancellation already +requested at preflight takes precedence over that result; otherwise a resource +limit takes precedence over unsupported policy-shape diagnostics. This ordering +keeps validation work bounded for checked-in CI inputs. + +Network binary selectors, endpoint host and path selectors, and REST allow and +deny method and path selectors must use ASCII literals in both the candidate and +boundary. A non-ASCII literal in one of these fields returns `unsupported` with +`reason_code: unsupported_policy_shape`, including when it appears only in a +deny. Embedded NUL bytes in these fields are also unsupported. This is a +prover-model limitation, not a general policy validation rule: filesystem paths +and unrelated policy text retain their existing Unicode behavior. ASCII +wildcard selectors still cover non-ASCII runtime values matched by the policy +engine. + +Containment means `Allowed(candidate)` is a subset of `Allowed(boundary)` under +the reported model. It does not establish least privilege, automatic approval +eligibility, semantic safety, or equivalence to a running sandbox's kernel +state. In particular: + +- The command does not fetch the current sandbox policy or compose provider + rules. The caller must supply the effective candidate. +- The command does not apply, approve, or persist a policy. +- Environment-dependent authority, such as an unresolved image workdir, + returns `unsupported` when the result depends on that missing context. +- Binary comparisons that can change when an image resolves an exact selector + through a symlink return `unsupported`. This covers exact candidate grants + under boundary globs and exact boundary denies replaced by candidate globs. + Use matching exact canonical paths when possible. +- Policies with overlapping L4 and enforced REST endpoints return + `unsupported` because inspection selection depends on the complete set of + matching runtime endpoint configurations. +- Network containment checks both supported runtime configurations: binary + identity enforcement enabled and disabled. When enabled, grants and denies + match the executable or an ancestor identity. Network counterexamples report + the configuration and identities that expose the additional authority. +- REST containment witnesses use canonical request methods and paths. +- If a solver string cannot be decoded and validated faithfully, the command + returns `inconclusive` with `reason_code: invalid_witness` instead of emitting + a counterexample. +- Both files are interpreted in the same sandbox filesystem namespace and + mount model, with stable path resolution when enforcement rules are created. + The CLI does not resolve sandbox paths against the host. +- Filesystem containment supports removing grants and reducing write grants to + read-only grants at matching paths. A boundary grant for `/` also covers other + paths for the same access. Comparisons between different paths otherwise + return `unsupported` with `reason_code: unresolved_filesystem_path`: a lexical + child can resolve outside its parent through a symlink, and unrelated paths + can resolve to the same object. This includes narrowing `/tmp` to `/tmp/cache`. + If the boundary grants no access of the requested kind, adding that access + returns `exceeds_boundary`. + +Use the [Policy Schema Reference](/reference/policy-schema) for the full policy +language. A successful prover result covers only the scope reported in its +evidence. diff --git a/docs/reference/support-matrix.mdx b/docs/reference/support-matrix.mdx index 7671866deb..740b5c997f 100644 --- a/docs/reference/support-matrix.mdx +++ b/docs/reference/support-matrix.mdx @@ -10,7 +10,7 @@ This page lists the host platform, compute driver, software, runtime, and kernel ## Supported Platforms -OpenShell publishes multi-architecture gateway images for `linux/amd64` and `linux/arm64`. The CLI, package-managed gateway, and standalone gateway binary are supported on the following host platforms: +OpenShell publishes multi-architecture gateway images for `linux/amd64` and `linux/arm64`. The CLI, policy prover, package-managed gateway, and standalone gateway binary are supported on the following host platforms: | Platform | Architecture | Status | | -------------------------------- | --------------------- | --------- | @@ -35,6 +35,18 @@ These artifacts are attached to GitHub releases. Kubernetes deployments should u On Linux, `openshell-gateway` requires glibc 2.28 or newer. Compatible systems include, for example, Ubuntu 20.04+, RHEL 8+, Rocky Linux 8+, Amazon Linux 2023+, and Fedora 32+. +## Standalone Policy Prover + +OpenShell publishes standalone `openshell-prover` release assets for manual download on these platforms: + +| Platform | Artifact pattern | +| --------------------- | ----------------------------------------------------- | +| Linux x86_64 (amd64) | `openshell-prover-x86_64-unknown-linux-musl.tar.gz` | +| Linux aarch64 (arm64) | `openshell-prover-aarch64-unknown-linux-musl.tar.gz` | +| macOS Apple Silicon | `openshell-prover-aarch64-apple-darwin.tar.gz` | + +These artifacts are attached to GitHub releases. The Linux binaries are static and do not require glibc. All prover archives include the required solver linkage. + ## Compute Drivers The gateway can manage sandboxes through several compute drivers. diff --git a/docs/sandboxes/manage-providers.mdx b/docs/sandboxes/manage-providers.mdx index 93f5b004b6..1b20185ce9 100644 --- a/docs/sandboxes/manage-providers.mdx +++ b/docs/sandboxes/manage-providers.mdx @@ -178,6 +178,18 @@ Update a provider's credentials: openshell provider update my-claude --from-existing ``` +To wait until attached sandboxes apply the updated credentials, add `--wait`: + +```shell +openshell provider update my-claude --from-existing --wait --timeout 30 --output json +``` + +The update records which sandboxes are attached before saving the new credentials. Its result includes a change ID and outcome for each of those sandboxes. Sandboxes attached later are outside this wait. The timeout applies to the whole group; if any selected sandbox fails or times out, the command exits with an error and still reports each sandbox's outcome. When no sandboxes are attached, it reports the saved change and an empty target list. + +Credential refresh status tells you whether OpenShell obtained credentials. [Provider readiness](/providers/profiles#inspect-provider-readiness) tells you whether the sandbox applied the credentials, policy, and environment for new processes. It does not test access to a backend model or cancel requests already sent upstream. + +After a static credential update completes, launch a new client process to use the updated reference. An existing process keeps its revision-scoped reference; readiness does not make that old reference resolve the new value. Acknowledged detach revokes retained references and removes them from environments for future launches. + Set or clear a credential expiry timestamp: ```shell diff --git a/e2e/parity/test.sh b/e2e/parity/test.sh index f3052b7a7e..ca6236f214 100755 --- a/e2e/parity/test.sh +++ b/e2e/parity/test.sh @@ -301,7 +301,7 @@ if [ "${OPENSHELL_PARITY_TEST_MUTATE_ARTIFACT:-}" = "${OPENSHELL_PARITY_VARIANT} replacement="${OPENSHELL_GATEWAY_BIN}.replacement" printf '#!/usr/bin/env bash\nexit 0\n# mutated\n' >"${replacement}" chmod 0555 "${replacement}" - mv "${replacement}" "${OPENSHELL_GATEWAY_BIN}" + mv -f "${replacement}" "${OPENSHELL_GATEWAY_BIN}" fi if [ "${OPENSHELL_E2E_PODMAN_OPTION_PROFILE:-}" = podman-options ]; then case "${OPENSHELL_PARITY_VARIANT}" in baseline) pids=2048 ;; candidate) pids=31 ;; esac diff --git a/e2e/python/test_sandbox_api.py b/e2e/python/test_sandbox_api.py index 06c1d325fc..9b48152961 100644 --- a/e2e/python/test_sandbox_api.py +++ b/e2e/python/test_sandbox_api.py @@ -3,11 +3,13 @@ from __future__ import annotations +import contextlib import threading +import uuid from typing import TYPE_CHECKING from google.protobuf import duration_pb2 -from openshell._proto import openshell_pb2 +from openshell._proto import datamodel_pb2, openshell_pb2, sandbox_pb2 if TYPE_CHECKING: from collections.abc import Callable @@ -15,6 +17,71 @@ from openshell import Sandbox, SandboxClient, WorkspaceClient +def test_mutation_replay_preserves_sandbox_lifecycle_and_replacement( + sandbox_client: SandboxClient, +) -> None: + name = f"replay-{uuid.uuid4().hex[:8]}" + scope = datamodel_pb2.WorkspaceSelector(workspace="default") + stub = sandbox_client._stub + create = openshell_pb2.CreateSandboxRequest( + name=name, + spec=openshell_pb2.SandboxSpec(), + workspace_scope=scope, + request_id=str(uuid.uuid4()), + ) + + def replay(method, request): + result, call = method.with_call(request, timeout=60) + assert dict(call.initial_metadata())["openshell-replayed"] == "true" + return result + + try: + original = stub.CreateSandbox(create, timeout=60).sandbox.metadata.id + sandbox_client.wait_ready(name, workspace="default", timeout_seconds=300) + assert replay(stub.CreateSandbox, create).sandbox.metadata.id == original + stop = openshell_pb2.StopSandboxRequest( + name=name, + workspace_scope=scope, + request_id=str(uuid.uuid4()), + ) + stub.StopSandbox(stop, timeout=60) + sandbox_client.wait_stopped(name, workspace="default", timeout_seconds=120) + assert replay(stub.StopSandbox, stop).sandbox.metadata.id == original + start = openshell_pb2.StartSandboxRequest( + name=name, + workspace_scope=scope, + request_id=str(uuid.uuid4()), + ) + stub.StartSandbox(start, timeout=60) + sandbox_client.wait_ready(name, workspace="default", timeout_seconds=300) + assert replay(stub.StartSandbox, start).sandbox.metadata.id == original + update = openshell_pb2.UpdateConfigRequest( + name=name, + workspace_scope=scope, + setting_key="ocsf_json_enabled", + setting_value=sandbox_pb2.SettingValue(bool_value=True), + request_id=str(uuid.uuid4()), + ) + updated = stub.UpdateConfig(update, timeout=30) + assert replay(stub.UpdateConfig, update) == updated + delete = openshell_pb2.DeleteSandboxRequest( + name=name, + workspace_scope=scope, + request_id=str(uuid.uuid4()), + ) + deleted = stub.DeleteSandbox(delete, timeout=60) + assert deleted.sandbox_id == original + sandbox_client.wait_deleted(name, workspace="default", timeout_seconds=120) + replacement = sandbox_client.create(workspace="default", name=name) + assert replacement.id != original + assert replay(stub.DeleteSandbox, delete) == deleted + assert sandbox_client.get(name, workspace="default").id == replacement.id + finally: + with contextlib.suppress(Exception): + sandbox_client.delete(name, workspace="default", allow_missing=True) + sandbox_client.wait_deleted(name, workspace="default", timeout_seconds=120) + + def test_sandbox_api_crud_and_exec( sandbox: Callable[..., Sandbox], sandbox_client: SandboxClient, @@ -133,7 +200,7 @@ def requests(): def test_list_scoped_and_for_all_workspaces( sandbox_client: SandboxClient, - workspace_client: "WorkspaceClient", + workspace_client: WorkspaceClient, ) -> None: import contextlib import uuid @@ -151,9 +218,7 @@ def test_list_scoped_and_for_all_workspaces( ) created_default.append(ref_default.name) - ref_other = sandbox_client.create( - workspace=other_ws, name=f"ls-oth-{suffix}" - ) + ref_other = sandbox_client.create(workspace=other_ws, name=f"ls-oth-{suffix}") created_other.append(ref_other.name) default_ids = set(sandbox_client.list_ids(workspace="default")) @@ -207,15 +272,29 @@ def test_sandbox_labels_and_selectors(sandbox_client: SandboxClient) -> None: # Labels round-trip through create and get. assert ref_a.labels["role"] == "primary" - assert dict(sandbox_client.get(job_a, workspace="default").labels)["role"] == "primary" - assert dict(sandbox_client.get(job_b, workspace="default").labels)["role"] == "secondary" + assert ( + dict(sandbox_client.get(job_a, workspace="default").labels)["role"] + == "primary" + ) + assert ( + dict(sandbox_client.get(job_b, workspace="default").labels)["role"] + == "secondary" + ) # A specific selector filters to exactly the primary sandbox. assert { - s.name for s in sandbox_client.list_all(workspace="default", label_selector=primary_selector) + s.name + for s in sandbox_client.list_all( + workspace="default", label_selector=primary_selector + ) } == {job_a} # The shared group label returns both. - assert {s.name for s in sandbox_client.list_all(workspace="default", label_selector=group_selector)} == { + assert { + s.name + for s in sandbox_client.list_all( + workspace="default", label_selector=group_selector + ) + } == { job_a, job_b, } @@ -224,15 +303,20 @@ def test_sandbox_labels_and_selectors(sandbox_client: SandboxClient) -> None: assert sandbox_client.delete(job_a, workspace="default") sandbox_client.wait_deleted(job_a, workspace="default") created.remove(job_a) - assert {s.name for s in sandbox_client.list_all(workspace="default", label_selector=group_selector)} == { - job_b - } + assert { + s.name + for s in sandbox_client.list_all( + workspace="default", label_selector=group_selector + ) + } == {job_b} # Final deletion leaves no matching sandboxes. assert sandbox_client.delete(job_b, workspace="default") sandbox_client.wait_deleted(job_b, workspace="default") created.remove(job_b) - assert not sandbox_client.list_all(workspace="default", label_selector=group_selector) + assert not sandbox_client.list_all( + workspace="default", label_selector=group_selector + ) finally: for name in created: with contextlib.suppress(Exception): diff --git a/e2e/python/test_workspace_api.py b/e2e/python/test_workspace_api.py index 1fb33123eb..a60597eb53 100644 --- a/e2e/python/test_workspace_api.py +++ b/e2e/python/test_workspace_api.py @@ -10,6 +10,8 @@ import grpc import pytest +from openshell._proto import openshell_pb2 + if TYPE_CHECKING: from openshell import WorkspaceClient @@ -74,3 +76,98 @@ def test_workspace_get_nonexistent_raises_not_found( with pytest.raises(grpc.RpcError) as exc_info: workspace_client.get(f"no-such-ws-{uuid.uuid4().hex[:8]}") assert exc_info.value.code() == grpc.StatusCode.NOT_FOUND + + +def test_workspace_request_ids_are_scoped_to_each_target( + workspace_client: WorkspaceClient, +) -> None: + names = [f"ws-scope-{uuid.uuid4().hex[:8]}" for _ in range(2)] + create_id = str(uuid.uuid4()) + delete_id = str(uuid.uuid4()) + stub = workspace_client._stub + originals = [] + try: + for name in names: + request = openshell_pb2.CreateWorkspaceRequest( + name=name, request_id=create_id + ) + response, call = stub.CreateWorkspace.with_call(request, timeout=20) + assert "openshell-replayed" not in dict(call.initial_metadata()) + assert response.workspace.metadata.name == name + fetched = stub.GetWorkspace( + openshell_pb2.GetWorkspaceRequest(name=name), timeout=20 + ) + assert fetched.workspace.metadata.id == response.workspace.metadata.id + originals.append(response) + assert originals[0].workspace.metadata.id != originals[1].workspace.metadata.id + + for name, original in zip(names, originals, strict=True): + replay, call = stub.CreateWorkspace.with_call( + openshell_pb2.CreateWorkspaceRequest(name=name, request_id=create_id), + timeout=20, + ) + assert replay == original + assert dict(call.initial_metadata())["openshell-replayed"] == "true" + + for name in names: + request = openshell_pb2.DeleteWorkspaceRequest( + name=name, request_id=delete_id + ) + response, call = stub.DeleteWorkspace.with_call(request, timeout=20) + assert "openshell-replayed" not in dict(call.initial_metadata()) + assert response.outcome == openshell_pb2.DELETION_OUTCOME_COMPLETED + with pytest.raises(grpc.RpcError) as exc_info: + workspace_client.get(name) + assert exc_info.value.code() == grpc.StatusCode.NOT_FOUND + + for name in names: + replay, call = stub.DeleteWorkspace.with_call( + openshell_pb2.DeleteWorkspaceRequest(name=name, request_id=delete_id), + timeout=20, + ) + assert replay.outcome == openshell_pb2.DELETION_OUTCOME_COMPLETED + assert dict(call.initial_metadata())["openshell-replayed"] == "true" + finally: + for name in names: + with contextlib.suppress(Exception): + workspace_client.delete(name, allow_missing=True) + + +def test_workspace_request_id_replays_without_deleting_replacement( + workspace_client: WorkspaceClient, +) -> None: + name = f"ws-replay-{uuid.uuid4().hex[:8]}" + # Exercise the generated wire fields before curated request-ID helpers land. + stub = workspace_client._stub + create = openshell_pb2.CreateWorkspaceRequest( + name=name, request_id=str(uuid.uuid4()) + ) + delete = openshell_pb2.DeleteWorkspaceRequest( + name=name, request_id=str(uuid.uuid4()) + ) + try: + original = stub.CreateWorkspace(create, timeout=20) + replay, call = stub.CreateWorkspace.with_call(create, timeout=20) + assert original == replay + assert dict(call.initial_metadata())["openshell-replayed"] == "true" + + mismatch = openshell_pb2.CreateWorkspaceRequest( + name=name, request_id=create.request_id, labels={"changed": "true"} + ) + with pytest.raises(grpc.RpcError) as exc_info: + stub.CreateWorkspace(mismatch, timeout=20) + assert exc_info.value.code() == grpc.StatusCode.FAILED_PRECONDITION + + removed = stub.DeleteWorkspace(delete, timeout=20) + replacement = stub.CreateWorkspace( + openshell_pb2.CreateWorkspaceRequest(name=name), timeout=20 + ) + assert replacement.workspace.metadata.id != original.workspace.metadata.id + assert stub.DeleteWorkspace(delete, timeout=20) == removed + fetched = stub.GetWorkspace( + openshell_pb2.GetWorkspaceRequest(name=name), timeout=20 + ) + assert fetched.workspace.metadata.id == replacement.workspace.metadata.id + finally: + with contextlib.suppress(Exception): + workspace_client.delete(name) diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index d81a5865fe..51f30c37fc 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -108,6 +108,11 @@ name = "provider_refresh_handles" path = "tests/provider_refresh_handles.rs" required-features = ["e2e-podman"] +[[test]] +name = "provider_readiness" +path = "tests/provider_readiness.rs" +required-features = ["e2e-docker"] + [[test]] name = "vm_gateway_start" path = "tests/vm_gateway_start.rs" diff --git a/e2e/rust/tests/oidc_pkce.rs b/e2e/rust/tests/oidc_pkce.rs index a64dab3476..8798670e7a 100644 --- a/e2e/rust/tests/oidc_pkce.rs +++ b/e2e/rust/tests/oidc_pkce.rs @@ -808,6 +808,7 @@ async fn workspace_admin_cannot_manage_another_workspace_members() { async fn workspace_admin_cannot_manage_another_workspace_providers() { const WORKSPACE_A: &str = "oidc-wsa-xprov-a"; const WORKSPACE_B: &str = "oidc-wsa-xprov-b"; + const PROVIDER: &str = "oidc-wsa-xprovider"; let (admin, workspace_admin, _user_b) = prepare_isolated_workspaces_with_admin(WORKSPACE_A, WORKSPACE_B).await; @@ -818,7 +819,7 @@ async fn workspace_admin_cannot_manage_another_workspace_providers() { "provider", "create", "--name", - "oidc-wsa-xprovider", + PROVIDER, "--type", "openai", "--credential", @@ -826,9 +827,50 @@ async fn workspace_admin_cannot_manage_another_workspace_providers() { ], ) .await; - assert_non_member_denial( - &denied, - "manage another workspace's providers as workspace admin", + let diagnostic = combined_output(&denied); + let compact: String = diagnostic + .chars() + .filter(|character| !character.is_whitespace() && *character != '│') + .collect(); + // Profile lookup redacts backend diagnostics. Check the permission code and + // safe recovery guidance without requiring the server's membership details. + assert!( + !denied.status.success() + && compact.contains("PERMISSION_DENIED") + && compact.contains("verifyworkspacemembershipandrequiredpermissions"), + "cross-workspace provider creation did not report a safe permission denial:\n{diagnostic}" + ); + assert!(!diagnostic.contains("e2e-test-value")); + + // Query with an independent authorized identity so a failed command alone + // cannot hide a provider created before the denial was returned. + let listed = assert_workspace_allowed( + &admin, + WORKSPACE_B, + &["provider", "list", "--output", "json"], + "verify denied creation left the target workspace empty", + ) + .await; + // CLI startup diagnostics may precede the JSON object on stdout. + let stdout = String::from_utf8(listed.stdout).expect("provider list output should be UTF-8"); + let json_start = stdout + .find('{') + .expect("provider list output should contain JSON"); + let json_end = stdout + .rfind('}') + .expect("provider list output should contain a complete JSON object"); + let listing: Value = serde_json::from_str(&stdout[json_start..=json_end]) + .expect("provider list --output json should return JSON on stdout"); + assert_eq!( + listing["next_page_token"], "", + "provider listing is incomplete" + ); + assert!( + listing["providers"] + .as_array() + .expect("provider collection") + .is_empty(), + "denied creation added a provider to the isolated target workspace" ); delete_workspace(&admin, WORKSPACE_B).await; diff --git a/e2e/rust/tests/provider_readiness.rs b/e2e/rust/tests/provider_readiness.rs new file mode 100644 index 0000000000..7736681d19 --- /dev/null +++ b/e2e/rust/tests/provider_readiness.rs @@ -0,0 +1,1645 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e-docker")] + +//! Provider changes acknowledged through a real sandbox HTTPS request path. +//! +//! Attach, update, and detach wait for confirmation of their exact saved changes. +//! Clients launched after attach and update keep their own static references. +//! The first request from the updated launch uses the acknowledged credential; +//! detach revokes both retained references and removes them from future launches. +//! Only the synthetic backends and privileged provider CLI receive keys; +//! workload files, responses, and diagnostics contain status information only. + +use std::net::Ipv4Addr; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::Duration; + +use openshell_e2e::harness::binary::openshell_cmd; +use openshell_e2e::harness::container::{ContainerEngine, e2e_network_name}; +use openshell_e2e::harness::gateway::ManagedGateway; +use openshell_e2e::harness::sandbox::SandboxGuard; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use tempfile::TempDir; +use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines}; +use tokio::process::{Child, ChildStdin, ChildStdout, Command}; +use tokio::time::{Instant, sleep, timeout}; + +const TOKEN_ENV: &str = "PROVIDER_READINESS_E2E_TOKEN"; +const BACKEND_PORT: u16 = 8443; +const OTHER_BACKEND_PORT: u16 = 8444; +const READY: &str = "provider-readiness-client-ready"; +const CONTROL: &str = "/sandbox/provider-readiness-probe"; +const RESULT: &str = "/sandbox/provider-readiness-result"; +const COMMAND_TIMEOUT: Duration = Duration::from_secs(60); +const IMAGE_BUILD_TIMEOUT: Duration = Duration::from_secs(300); +const READINESS_TIMEOUT_SECONDS: &str = "90"; +const READINESS_COMMAND_TIMEOUT: Duration = Duration::from_secs(105); +const GATEWAY_READY_TIMEOUT: Duration = Duration::from_secs(120); + +// Keys arrive on a private stdin pipe after process creation. Neither the +// command line nor any file contains them, and HTTP/server errors are silent. +const BACKEND: &str = r" +import http.server, json, ssl, sys, threading + +config = json.loads(sys.stdin.readline()) +keys = config.pop('keys') +lock = threading.Lock() +state = {'phase': 0, 'total': 0, 'accepted': [0, 0], 'rejected': 0} + +class Server(http.server.ThreadingHTTPServer): + daemon_threads = True + def handle_error(self, request, client_address): + pass + +class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + def do_POST(self): + with lock: + phase = state['phase'] + valid = self.headers.get('Authorization') == 'Bearer ' + keys[phase] + state['total'] += 1 + if valid: + state['accepted'][phase] += 1 + else: + state['rejected'] += 1 + body = json.dumps({'authorized': valid, 'phase': phase}).encode() + self.send_response(200 if valid else 401) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(body))) + self.send_header('Connection', 'close') + self.end_headers() + self.wfile.write(body) + +context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +context.minimum_version = ssl.TLSVersion.TLSv1_2 +context.load_cert_chain(config['certificate'], config['private_key']) +servers = [] +for port in config['ports']: + server = Server(('0.0.0.0', port), Handler) + server.socket = context.wrap_socket(server.socket, server_side=True) + threading.Thread(target=server.serve_forever, daemon=True).start() + servers.append(server) +print(json.dumps({'ready': True}), flush=True) + +for line in sys.stdin: + request = json.loads(line) + with lock: + if request['command'] == 'rotate': + state['phase'] = 1 + print(json.dumps(state), flush=True) +for server in servers: + server.shutdown() + server.server_close() +"; + +// This source is safe to place in the workload image: it contains environment +// key names and endpoint coordinates, but never a key value or issued handle. +const CLIENT: &str = r" +import json, os, pathlib, re, ssl, sys, time, urllib.error, urllib.request + +config = json.loads(sys.argv[1]) +key = 'PROVIDER_READINESS_E2E_TOKEN' +token = os.environ.get(key, '') +if not re.fullmatch(r'openshell:resolve:env:v[1-9][0-9]*_' + key, token): + print('client did not receive a revision-scoped reference', flush=True) + sys.exit(64) +client = sys.argv[2] +if client not in ('a', 'b'): + sys.exit(64) +pid = os.getpid() +control = pathlib.Path('/sandbox/provider-readiness-probe-' + client) +result = pathlib.Path('/sandbox/provider-readiness-result-' + client) + +def probe(phase): + host, port, path = config['host'], config['port'], '/v1/chat/completions' + target = phase[:-8] if phase.endswith('_control') else phase + if target == 'wrong_host': + host = config['other_host'] + elif target == 'wrong_port': + port = config['other_port'] + elif target == 'wrong_path': + path = '/outside' + url = 'https://%s:%s%s' % (host, port, path) + response = {'phase': phase, 'pid': pid, 'same_reference': os.environ.get(key) == token, + 'ok': False, 'status': 0, 'backend_phase': -1} + try: + context = ssl.create_default_context() + if phase == 'untrusted_ca': + # An empty trust store proves this client does verify TLS. + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + headers = {'Content-Type': 'application/json'} + if not phase.endswith('_control'): + headers['Authorization'] = 'Bearer ' + token + request = urllib.request.Request(url, data=b'{}', headers=headers) + try: + reply = urllib.request.urlopen(request, context=context, timeout=5) + except urllib.error.HTTPError as error: + # The backend's safe 401 body proves the negative endpoint is + # reachable before a credential-bearing request is denied. + reply = error + with reply: + body = json.loads(reply.read(1024)) + response['ok'] = body.get('authorized') is True + response['status'] = reply.status + response['backend_phase'] = body.get('phase', -1) + except Exception as error: + # HTTP/TLS exceptions can embed headers; expose only fixed type names. + response['error_kind'] = type(error).__name__ + response['reason_kind'] = type(getattr(error, 'reason', None)).__name__ + return response + +print('provider-readiness-client-ready', flush=True) +deadline = time.monotonic() + 600 +while time.monotonic() < deadline: + if control.exists(): + phase = control.read_text().strip() + control.unlink() + temporary = result.with_suffix('.tmp') + temporary.write_text(json.dumps(probe(phase))) + temporary.replace(result) + time.sleep(0.05) +"; + +struct FixtureImage { + engine: ContainerEngine, + tag: String, +} + +impl FixtureImage { + fn new() -> Result { + Ok(Self { + engine: ContainerEngine::from_env()?, + tag: format!( + "localhost/openshell-e2e-readiness-{}-{:016x}:latest", + std::process::id(), + rand::random::(), + ), + }) + } + + fn tag(&self) -> &str { + &self.tag + } + + async fn build(&self, dockerfile: &Path, context: &Path) -> Result<(), String> { + let mut command = Command::from(self.engine.command()); + command + .args(["build", "--file"]) + .arg(dockerfile) + .args(["--tag", &self.tag]) + .arg(context); + checked_command_with_timeout(&mut command, "build fixture image", IMAGE_BUILD_TIMEOUT) + .await + .map(|_| ()) + } + + async fn remove(&self) -> Result<(), String> { + let mut command = Command::from(self.engine.command()); + command.args(["image", "rm", "--force", &self.tag]); + // Teardown is explicit and bounded. This type has no Drop subprocess + // that could block the test runtime after the removal deadline expires. + checked_command(&mut command, "remove fixture image") + .await + .map(|_| ()) + } +} + +// This fixture owns the only test in its binary. The wrapper's gateway is +// private to this run, so replacing its supervisor image cannot affect another +// test while the public fixture CA is installed in the supervisor trust store. +struct GatewayTrustConfig { + path: PathBuf, + original: String, + image_range: std::ops::Range, + supervisor_image: String, + health_port: u16, + restore_required: bool, +} + +impl GatewayTrustConfig { + fn load() -> Result { + if std::env::var_os("OPENSHELL_GATEWAY_ENDPOINT").is_some() + || std::env::var_os("OPENSHELL_E2E_GATEWAY_BIN").is_none() + || std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("docker") + || std::env::var("OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER") + .is_ok_and(|value| value != "0") + { + return Err("provider readiness fixture requires a wrapper-owned gateway with the bundled Docker driver".to_string()); + } + let args_file = std::env::var_os("OPENSHELL_E2E_GATEWAY_ARGS_FILE") + .ok_or("managed gateway argument metadata is missing")?; + let raw = + std::fs::read(args_file).map_err(|_| "could not read managed gateway arguments")?; + let args = raw + .split(|byte| *byte == 0) + .filter(|arg| !arg.is_empty()) + .map(std::str::from_utf8) + .collect::, _>>() + .map_err(|_| "managed gateway arguments were not UTF-8")?; + let argument = |name| { + let mut values = args.windows(2).filter(|pair| pair[0] == name); + let value = values.next().ok_or("managed gateway argument is missing")?[1]; + if values.next().is_some() { + return Err("managed gateway argument is duplicated"); + } + Ok(value) + }; + let path = PathBuf::from(argument("--config")?); + let health_port = argument("--health-port")? + .parse::() + .map_err(|_| "managed gateway health port is invalid")?; + let original = std::fs::read_to_string(&path) + .map_err(|_| "could not read managed gateway configuration")?; + let (image_range, supervisor_image) = docker_supervisor_image(&original)?; + Ok(Self { + path, + original, + image_range, + supervisor_image, + health_port, + restore_required: false, + }) + } + + async fn apply(&mut self, image: &str) -> Result<(), String> { + let mut updated = self.original.clone(); + updated.replace_range(self.image_range.clone(), image); + // Set the guard before the write: a failed write or restart must still + // flow through explicit restoration of the exact original bytes. + self.restore_required = true; + std::fs::write(&self.path, updated) + .map_err(|_| "could not install fixture supervisor configuration")?; + restart_fixture_gateway(self.health_port).await + } + + async fn restore(&mut self) -> Result<(), String> { + if !self.restore_required { + return Ok(()); + } + std::fs::write(&self.path, &self.original) + .map_err(|_| "could not restore original gateway configuration")?; + restart_fixture_gateway(self.health_port) + .await + .map_err(|_| "original gateway configuration was restored but restart failed")?; + self.restore_required = false; + Ok(()) + } +} + +impl Drop for GatewayTrustConfig { + fn drop(&mut self) { + if self.restore_required { + // Cancellation/panic fallback restores disk state only. Normal + // Result paths explicitly restart and verify health; Drop never + // launches a subprocess or hides a failed restart as success. + let _ = std::fs::write(&self.path, &self.original); + } + } +} + +fn docker_supervisor_image(config: &str) -> Result<(std::ops::Range, String), String> { + let mut in_docker = false; + let mut offset = 0; + let mut found = None; + for line in config.split_inclusive('\n') { + let trimmed = line.trim(); + if trimmed.starts_with('[') { + in_docker = trimmed == "[openshell.drivers.docker]"; + } else if in_docker && let Some((key, value)) = trimmed.split_once('=') { + if key.trim() == "socket_path" { + return Err( + "fixture cannot replace an external Docker driver configuration".to_string(), + ); + } + if key.trim() == "supervisor_image" { + // Accept only the wrapper's single-line quoted OCI reference. + // Reject escapes/comments instead of treating general TOML as + // text and accidentally changing a different configuration key. + let image = value + .trim() + .strip_prefix('"') + .and_then(|value| value.strip_suffix('"')) + .filter(|image| { + !image.is_empty() + && image.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || b"/:@._-".contains(&byte) + }) + }) + .ok_or("managed supervisor image is not a simple quoted OCI reference")?; + let start = offset + + line + .find('"') + .ok_or("managed supervisor image is not quoted")? + + 1; + if found + .replace((start..start + image.len(), image.to_string())) + .is_some() + { + return Err("managed Docker supervisor image is duplicated".to_string()); + } + } + } + offset += line.len(); + } + found.ok_or_else(|| "managed Docker supervisor image is missing".to_string()) +} + +async fn restart_fixture_gateway(health_port: u16) -> Result<(), String> { + let gateway = ManagedGateway::from_env() + .map_err(|_| "could not load managed gateway restart metadata")? + .ok_or("managed gateway restart metadata disappeared")?; + // ManagedGateway bounds graceful shutdown before force-kill. Keep it local: + // its Drop can start a stopped gateway, but never owns configuration restore. + gateway + .stop() + .map_err(|_| "could not stop fixture gateway")?; + gateway + .start() + .map_err(|_| "could not restart fixture gateway")?; + let url = format!("http://127.0.0.1:{health_port}/healthz"); + let deadline = Instant::now() + GATEWAY_READY_TIMEOUT; + loop { + if checked_command( + Command::new("curl").args(["--silent", "--fail", "--max-time", "2", &url]), + "check fixture gateway health", + ) + .await + .is_ok() + { + return Ok(()); + } + if Instant::now() >= deadline { + return Err("fixture gateway did not become healthy".to_string()); + } + sleep(Duration::from_millis(250)).await; + } +} + +struct Backend { + engine: ContainerEngine, + name: String, + network: String, + namespace: String, + child: Option, + input: Option, + output: Option>>, + launch_attempted: bool, +} + +struct PersistentClient { + child: Child, + // Keep the stream open after reading the marker so the CLI can continue + // relaying the same remote process until explicit sandbox teardown. + _output: Lines>, +} + +impl PersistentClient { + async fn start( + sandbox: &SandboxGuard, + python: &str, + config: &str, + client: &str, + ) -> Result { + let mut command = sandbox_command( + sandbox, + &[ + python, + "-u", + "/opt/provider-readiness-client.py", + config, + client, + ], + ); + let mut child = command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn() + .map_err(|_| "persistent workload exec could not start")?; + let output = child + .stdout + .take() + .ok_or("workload stdout was unavailable")?; + let mut output = BufReader::new(output).lines(); + timeout(COMMAND_TIMEOUT, async { + while let Some(line) = output + .next_line() + .await + .map_err(|_| "workload marker could not be read")? + { + if line.trim() == READY { + return Ok(()); + } + // A CLI or workload error can contain environment material. + // Ignore every unrecognized line without including it in errors. + } + Err("persistent workload closed before its ready marker") + }) + .await + .map_err(|_| "persistent workload ready marker timed out")??; + Ok(Self { + child, + _output: output, + }) + } + + async fn stop(&mut self) -> Result<(), String> { + // Sandbox deletion ends the remote workload; reap the retained relay + // even if the remote deletion or normal stream shutdown fails. + timeout(COMMAND_TIMEOUT, self.child.kill()) + .await + .map_err(|_| "persistent client cleanup timed out")? + .map_err(|_| "persistent client cleanup failed".to_string()) + } +} + +impl Backend { + fn new(name: String) -> Result { + Ok(Self { + engine: ContainerEngine::from_env()?, + name, + network: e2e_network_name().ok_or("fixture requires the managed Docker network")?, + namespace: std::env::var("OPENSHELL_E2E_SANDBOX_NAMESPACE") + .map_err(|_| "fixture requires the managed Docker namespace")?, + child: None, + input: None, + output: None, + launch_attempted: false, + }) + } + + async fn spawn(&mut self, base: &str, tls_directory: &Path) -> Result { + let tls_directory = tls_directory + .to_str() + .filter(|path| !path.contains([',', '\n', '\r'])) + .ok_or("fixture TLS mount path is invalid")?; + let mount = format!("type=bind,src={tls_directory},dst=/fixture-tls,readonly"); + let namespace_label = format!("openshell.ai/sandbox-namespace={}", self.namespace); + let mut command = Command::from(self.engine.command()); + command + .args([ + "run", + "--rm", + "--interactive", + "--pull=never", + "--name", + &self.name, + "--network", + &self.network, + "--label", + "openshell.ai/managed-by=openshell", + "--label", + &namespace_label, + "--label", + "openshell.ai/isolation-role=fixture", + "--read-only", + "--cap-drop=ALL", + "--security-opt=no-new-privileges:true", + "--mount", + &mount, + "--entrypoint", + "/usr/bin/python3", + base, + "-u", + "-c", + BACKEND, + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true); + // Record the unique container name before creation. Every Result exit + // removes it, including a failed readiness exchange after Docker starts. + // Wrapper-scoped labels also let wrapper teardown reap an interrupted run. + self.launch_attempted = true; + let child = command + .spawn() + .map_err(|_| "could not start synthetic HTTPS backend".to_string())?; + self.child = Some(child); + let child = self.child.as_mut().ok_or("backend child was absent")?; + self.input = Some( + child + .stdin + .take() + .ok_or("backend stdin was not available")?, + ); + let output = child + .stdout + .take() + .ok_or("backend stdout was not available")?; + self.output = Some(BufReader::new(output).lines()); + // Python waits for its private stdin configuration before reading TLS + // files. Discover the actual address first so its certificate can name + // that exact endpoint without DNS or an unverified TLS connection. + self.address().await + } + + async fn address(&mut self) -> Result { + let deadline = Instant::now() + COMMAND_TIMEOUT; + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err("backend bridge address did not become available".to_string()); + } + let mut inspect = Command::from(self.engine.command()); + inspect.args([ + "inspect", + "--format", + "{{json .NetworkSettings.Networks}}", + &self.name, + ]); + if let Ok(output) = checked_command_with_timeout( + &mut inspect, + "inspect backend bridge address", + remaining.min(Duration::from_secs(2)), + ) + .await + { + let networks: Value = serde_json::from_str(&output) + .map_err(|_| "backend network metadata was invalid")?; + if let Some(address) = networks[&self.network]["IPAddress"] + .as_str() + .filter(|address| !address.is_empty()) + { + let address = address + .parse::() + .map_err(|_| "backend network address was not IPv4")?; + if !address.is_private() { + return Err("fixture backend requires a private bridge address".to_string()); + } + return Ok(address.to_string()); + } + } + if self + .child + .as_mut() + .ok_or("backend child was absent")? + .try_wait() + .map_err(|_| "could not inspect backend client status")? + .is_some() + { + return Err("backend exited before its bridge address was available".to_string()); + } + sleep(Duration::from_millis(100)).await; + } + } + + async fn initialize(&mut self, config: &Value) -> Result<(), String> { + if self.exchange(config).await?["ready"] != true { + return Err("synthetic HTTPS backend did not become ready".to_string()); + } + Ok(()) + } + + async fn exchange(&mut self, request: &Value) -> Result { + let mut bytes = + serde_json::to_vec(request).map_err(|_| "backend request encoding failed")?; + bytes.push(b'\n'); + let input = self.input.as_mut().ok_or("backend stdin was absent")?; + let output = self.output.as_mut().ok_or("backend stdout was absent")?; + timeout(COMMAND_TIMEOUT, async { + input + .write_all(&bytes) + .await + .map_err(|_| "backend control write failed")?; + let line = output + .next_line() + .await + .map_err(|_| "backend control read failed")? + .ok_or("backend closed its control stream")?; + serde_json::from_str(&line).map_err(|_| "backend status was not valid JSON") + }) + .await + .map_err(|_| "backend control operation timed out".to_string())? + .map_err(str::to_string) + } + + async fn stop(&mut self) -> Result<(), String> { + // Closing stdin lets Python shut down normally. Removing the named + // container also covers a stalled startup or disconnected Docker client; + // killing the attached client alone cannot prove the container stopped. + drop(self.input.take()); + let mut reap_result = Ok(()); + if let Some(child) = self.child.as_mut() { + reap_result = timeout(COMMAND_TIMEOUT, child.kill()) + .await + .map_err(|_| "backend client teardown timed out".to_string()) + .and_then(|result| { + result.map_err(|_| "backend client teardown failed".to_string()) + }); + } + if !self.launch_attempted { + return reap_result; + } + remove_fixture_container(&self.engine, &self.name).await?; + reap_result + } +} + +/// Counters deliberately contain no authorization headers or secret values. +#[derive(Deserialize, Serialize)] +struct BackendCounts { + phase: u8, + total: u64, + accepted: [u64; 2], + rejected: u64, +} + +// A second endpoint supplies a reachable wrong-host control. Each container +// retains its own counters; their sum proves denied traffic reaches neither. +struct BackendPair { + backends: [Backend; 2], +} + +impl BackendPair { + fn new(name: &str) -> Result { + Ok(Self { + backends: [ + Backend::new(format!("{name}-backend"))?, + Backend::new(format!("{name}-other-backend"))?, + ], + }) + } + + async fn spawn(&mut self, base: &str, tls_directory: &Path) -> Result<[String; 2], String> { + let host = self.backends[0].spawn(base, tls_directory).await?; + let other_host = self.backends[1].spawn(base, tls_directory).await?; + if host == other_host { + return Err("wrong-host control requires a distinct backend address".to_string()); + } + Ok([host, other_host]) + } + + async fn initialize(&mut self, config: &Value) -> Result<(), String> { + for backend in &mut self.backends { + backend.initialize(config).await?; + } + Ok(()) + } + + async fn rotate(&mut self) -> Result<(), String> { + for backend in &mut self.backends { + if backend.exchange(&json!({"command": "rotate"})).await?["phase"] != 1 { + return Err("backend did not switch to the replacement key".to_string()); + } + } + Ok(()) + } + + async fn counts(&mut self) -> Result { + let mut combined: Option = None; + for backend in &mut self.backends { + let response = backend.exchange(&json!({"command": "snapshot"})).await?; + let counters: BackendCounts = + serde_json::from_value(response).map_err(|_| "backend counters were invalid")?; + if let Some(total) = combined.as_mut() { + if total.phase != counters.phase { + return Err("fixture backends disagree on the active key".to_string()); + } + let add = |left: u64, right: u64| { + left.checked_add(right).ok_or("backend counters overflowed") + }; + total.total = add(total.total, counters.total)?; + total.rejected = add(total.rejected, counters.rejected)?; + for (left, right) in total.accepted.iter_mut().zip(counters.accepted) { + *left = add(*left, right)?; + } + } else { + combined = Some(counters); + } + } + serde_json::to_value(combined.ok_or("backend counters were absent")?) + .map_err(|_| "backend counters could not be encoded".to_string()) + } + + async fn stop(&mut self) -> Result<(), String> { + let mut failures = Vec::new(); + for backend in &mut self.backends { + if let Err(error) = backend.stop().await { + failures.push(error); + } + } + if failures.is_empty() { + Ok(()) + } else { + Err(failures.join("; ")) + } + } +} + +async fn checked_command(command: &mut Command, label: &str) -> Result { + checked_command_with_timeout(command, label, COMMAND_TIMEOUT).await +} + +async fn checked_command_with_timeout( + command: &mut Command, + label: &str, + max_wait: Duration, +) -> Result { + command + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true); + let output = timeout(max_wait, command.output()) + .await + .map_err(|_| format!("{label} timed out"))? + .map_err(|_| format!("{label} could not start"))?; + if !output.status.success() { + // CLI arguments, captured output, and subprocess errors can contain + // credential material. Error messages expose only the safe operation. + return Err(format!("{label} failed; subprocess output withheld")); + } + String::from_utf8(output.stdout).map_err(|_| format!("{label} returned invalid UTF-8")) +} + +async fn cli(label: &str, args: &[&str], credential: Option<&str>) -> Result { + let mut command = openshell_cmd(); + command.args(args); + if let Some(credential) = credential { + command.env(TOKEN_ENV, credential); + } + checked_command(&mut command, label).await +} + +fn sandbox_command(sandbox: &SandboxGuard, argv: &[&str]) -> Command { + let mut command = openshell_cmd(); + command + .args(["sandbox", "exec", "--name", &sandbox.name, "--no-tty", "--"]) + .args(argv); + command +} + +async fn generate_certificates( + directory: &Path, + host: &str, + other_host: &str, +) -> Result<(PathBuf, PathBuf), String> { + let ca_key = directory.join("ca.key.fixture"); + let ca = directory.join("ca.crt"); + let key = directory.join("backend.key.fixture"); + let csr = directory.join("backend.csr"); + let certificate = directory.join("backend.crt"); + let extensions = directory.join("backend.ext"); + std::fs::write( + &extensions, + format!( + "basicConstraints=critical,CA:FALSE\nsubjectAltName=IP:{host},IP:{other_host}\nextendedKeyUsage=serverAuth\n" + ), + ) + .map_err(|_| "could not write public TLS certificate extensions")?; + checked_command( + Command::new("openssl") + .args([ + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-days", + "1", + "-subj", + "/CN=provider-readiness-e2e-ca", + "-keyout", + ]) + .arg(&ca_key) + .arg("-out") + .arg(&ca), + "generate fixture CA", + ) + .await?; + checked_command( + Command::new("openssl") + .args([ + "req", + "-newkey", + "rsa:2048", + "-nodes", + "-subj", + &format!("/CN={host}"), + "-keyout", + ]) + .arg(&key) + .arg("-out") + .arg(&csr), + "generate fixture TLS key", + ) + .await?; + checked_command( + Command::new("openssl") + .args(["x509", "-req", "-days", "1", "-in"]) + .arg(&csr) + .arg("-CA") + .arg(&ca) + .arg("-CAkey") + .arg(&ca_key) + .arg("-CAcreateserial") + .arg("-extfile") + .arg(&extensions) + .arg("-out") + .arg(&certificate), + "sign fixture TLS certificate", + ) + .await?; + Ok((certificate, key)) +} + +async fn base_binaries(base: &str) -> Result { + let engine = ContainerEngine::from_env()?; + let name = format!( + "e2e-readiness-binaries-{}-{:016x}", + std::process::id(), + rand::random::() + ); + let namespace = std::env::var("OPENSHELL_E2E_SANDBOX_NAMESPACE") + .map_err(|_| "binary probe requires the managed Docker namespace")?; + let namespace_label = format!("openshell.ai/sandbox-namespace={namespace}"); + let mut command = Command::from(engine.command()); + command.args([ + "run", "--rm", "--name", &name, "--network", "none", + "--label", "openshell.ai/managed-by=openshell", + "--label", &namespace_label, + "--label", "openshell.ai/isolation-role=fixture", + "--entrypoint", "/usr/bin/python3", base, + "-c", "import json,os,shutil,sys; print(json.dumps({'python':os.path.realpath(sys.executable),'curl':shutil.which('curl')}))", + ]); + // A timeout terminates the attached CLI, which does not prove its container + // stopped. Always remove the known name; labels also let wrapper teardown + // recover it if the entire test is cancelled before explicit cleanup. + let result = async { + let output = checked_command(&mut command, "inspect fixture image binaries").await?; + let binaries: Value = + serde_json::from_str(&output).map_err(|_| "image binary probe was invalid")?; + for field in ["python", "curl"] { + if !binaries[field] + .as_str() + .is_some_and(|path| Path::new(path).is_absolute()) + { + return Err(format!("fixture image has no absolute {field} executable")); + } + } + Ok(binaries) + } + .await; + let cleanup = remove_fixture_container(&engine, &name).await; + match (result, cleanup) { + (Ok(binaries), Ok(())) => Ok(binaries), + (Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error), + (Err(error), Err(cleanup)) => Err(format!("{error}; {cleanup}")), + } +} + +async fn remove_fixture_container(engine: &ContainerEngine, name: &str) -> Result<(), String> { + let mut remove = Command::from(engine.command()); + remove.args(["rm", "--force", name]); + let removed = checked_command(&mut remove, "remove fixture container").await; + // --rm may have already removed a normally exited fixture. Only a + // successful exact-name listing can establish absence after rm fails. + if removed.is_err() { + let mut list = Command::from(engine.command()); + let filter = format!("name=^/{name}$"); + list.args(["ps", "--all", "--quiet", "--filter", &filter]); + if !checked_command(&mut list, "verify fixture container removal") + .await? + .trim() + .is_empty() + { + return Err("fixture container remained after teardown".to_string()); + } + } + Ok(()) +} + +fn write_profile( + path: &Path, + name: &str, + host: &str, + port: u16, + python: &str, +) -> Result<(), String> { + let document = json!({ + "id": name, "display_name": "Provider readiness E2E", "category": "other", + "credentials": [{"name": "synthetic", "env_vars": [TOKEN_ENV], "required": true, + "auth_style": "bearer", "header_name": "authorization"}], + "endpoints": [{"host": host, "port": port, "path": "/v1/**", "protocol": "rest", + "access": "full", "enforcement": "enforce", + "allowed_ips": [host]}], + "binaries": [python], + }); + std::fs::write(path, document.to_string()) + .map_err(|_| "could not write synthetic profile".to_string()) +} + +fn write_policy( + path: &Path, + host: &str, + other_host: &str, + port: u16, + other_port: u16, + python: &str, +) -> Result<(), String> { + // Permit the negative endpoint probes at the network layer so the + // credential binding itself must prevent them from reaching the backend. + // The exact binary allowlist independently denies curl at the valid endpoint. + let endpoints = [(host, port), (host, other_port), (other_host, port)] + .into_iter() + .map(|(host, port)| { + json!({"host": host, "port": port, "path": "/**", "protocol": "rest", + "access": "full", "enforcement": "enforce", + "allowed_ips": [host]}) + }) + .collect::>(); + let document = json!({ + "version": 1, + "filesystem_policy": {"include_workdir": false, + "read_only": ["/usr", "/lib", "/proc", "/dev/urandom", "/etc", "/opt", "/var/log"], + "read_write": ["/sandbox", "/tmp", "/dev/null"]}, + "landlock": {"compatibility": "best_effort"}, + "process": {"run_as_user": "sandbox", "run_as_group": "sandbox"}, + "network_policies": {"synthetic_backend": {"name": "synthetic_backend", + "endpoints": endpoints, "binaries": [{"path": python}]}}, + }); + std::fs::write(path, document.to_string()) + .map_err(|_| "could not write synthetic policy".to_string()) +} + +struct MutationReceipt { + mutation_id: String, + receipt: Value, +} + +fn readiness_output(output: &str, keys: &[String; 2]) -> Result { + // Never echo a malformed response: both a key leak and a leaked issued + // reference must fail with the same fixed diagnostic. + if keys.iter().any(|key| output.contains(key)) + || output.contains("openshell:resolve:") + || output.contains("Bearer ") + { + return Err("provider readiness output contained credential material".to_string()); + } + serde_json::from_str(output) + .map_err(|_| "provider readiness output was invalid JSON".to_string()) +} + +fn single_target(body: &Value) -> Result<&Value, String> { + let targets = body["targets"] + .as_array() + .ok_or("provider readiness targets were absent")?; + // This provider is unique and has exactly one attachment. A mutation that + // selects a different sandbox or omits this sandbox cannot satisfy the test. + if targets.len() != 1 { + return Err("provider readiness did not identify exactly one sandbox".to_string()); + } + Ok(&targets[0]) +} + +fn nonempty_string<'a>(object: &'a Value, field: &str) -> Result<&'a str, String> { + object[field] + .as_str() + .filter(|value| !value.is_empty()) + .ok_or_else(|| format!("provider readiness identity field {field} was absent")) +} + +impl MutationReceipt { + fn capture( + output: &str, + sandbox: &SandboxGuard, + provider: &str, + kind: &str, + keys: &[String; 2], + ) -> Result { + let body = readiness_output(output, keys)?; + let status = single_target(&body)?; + let receipt = &status["receipt"]; + let desired = &receipt["desired"]; + let mutation_id = nonempty_string(&body, "mutation_id")?; + if receipt["mutation_id"] != mutation_id + || receipt["provider_name"] != provider + || receipt["kind"] != kind + || desired["sandbox_name"] != sandbox.name + || status["state"] != "persisted" + || status["wait_outcome"] != "not_requested" + { + return Err( + "provider mutation receipt did not match persisted target intent".to_string(), + ); + } + nonempty_string(receipt, "receipt_id")?; + for field in [ + "sandbox_id", + "attachment_epoch", + "provider_resource_version", + "provider_env_revision", + "config_revision", + "policy_hash", + ] { + nonempty_string(desired, field)?; + } + if kind == "detach" { + if desired["provider_id"] != "" || desired["provider_resource_version"] != "0" { + return Err("detach receipt retained provider authority".to_string()); + } + } else { + nonempty_string(desired, "provider_id")?; + } + nonempty_string(receipt, "persisted_time")?; + Ok(Self { + mutation_id: mutation_id.to_string(), + receipt: receipt.clone(), + }) + } + + fn follows(&self, previous: &Self) -> Result<(), String> { + let desired = &self.receipt["desired"]; + let preceding = &previous.receipt["desired"]; + if self.mutation_id == previous.mutation_id + || self.receipt["receipt_id"] == previous.receipt["receipt_id"] + || self.receipt["provider_name"] != previous.receipt["provider_name"] + || self.receipt["workspace"] != previous.receipt["workspace"] + || desired["sandbox_id"] != preceding["sandbox_id"] + || desired["sandbox_name"] != preceding["sandbox_name"] + || desired["provider_env_revision"] == preceding["provider_env_revision"] + { + return Err( + "provider mutation did not identify distinct authority for the same target" + .to_string(), + ); + } + // Revisions are opaque strings. Only identity equality is meaningful; + // a numerically lower fingerprint is still a different installation. + if self.receipt["kind"] == "update" + && (desired["provider_id"] != preceding["provider_id"] + || desired["provider_resource_version"] == preceding["provider_resource_version"] + || desired["attachment_epoch"] != preceding["attachment_epoch"]) + { + return Err("provider update did not preserve its attachment identity".to_string()); + } + if self.receipt["kind"] == "detach" + && desired["attachment_epoch"] == preceding["attachment_epoch"] + { + return Err("provider detach did not replace its attachment epoch".to_string()); + } + Ok(()) + } + + async fn wait( + &self, + sandbox: &SandboxGuard, + provider: &str, + expected_state: &str, + keys: &[String; 2], + ) -> Result { + let mut command = openshell_cmd(); + command.args([ + "sandbox", + "provider", + "status", + &sandbox.name, + provider, + "--receipt", + nonempty_string(&self.receipt, "receipt_id")?, + "--wait", + "--timeout", + READINESS_TIMEOUT_SECONDS, + "-o", + "json", + ]); + let output = checked_command_with_timeout( + &mut command, + "wait for original provider mutation receipt", + READINESS_COMMAND_TIMEOUT, + ) + .await?; + let body = readiness_output(&output, keys)?; + let status = single_target(&body)?; + if body["mutation_id"] != self.mutation_id + || status["receipt"] != self.receipt + || status["state"] != expected_state + || status["reason"] != "unspecified" + || status["wait_outcome"] != "complete" + { + return Err( + "original provider receipt did not complete against its exact desired authority" + .to_string(), + ); + } + let desired = &self.receipt["desired"]; + let observed = &status["observed"]; + for field in [ + "attachment_epoch", + "provider_env_revision", + "config_revision", + "policy_hash", + ] { + if observed[field] != desired[field] { + return Err(format!( + "provider installation did not match desired {field}" + )); + } + } + for field in [ + "credentials_installed", + "policy_active", + "launch_environment_installed", + ] { + if observed[field] != true { + return Err(format!("provider receipt completed without {field}")); + } + } + for field in ["session_id", "sequence", "process_instance_id"] { + nonempty_string(observed, field)?; + } + nonempty_string(status, "network_instance_id")?; + nonempty_string(status, "observed_time")?; + nonempty_string(status, "evaluated_time")?; + if observed["reason"] != "unspecified" { + return Err( + "provider installation observation lacked a successful timestamped acknowledgment" + .to_string(), + ); + } + Ok(status.clone()) + } +} + +async fn future_environment( + sandbox: &SandboxGuard, + python: &str, + expected_present: bool, +) -> Result<(), String> { + // A new exec consumes the process supervisor's current launch snapshot. + // Only booleans leave the process, never the reference or its length. + let script = "import json,os,re; key='PROVIDER_READINESS_E2E_TOKEN'; value=os.environ.get(key,''); print(json.dumps({'present':key in os.environ,'reference':bool(re.fullmatch(r'openshell:resolve:env:v[1-9][0-9]*_'+key,value))}))"; + let output = checked_command( + &mut sandbox_command(sandbox, &[python, "-c", script]), + "probe future process provider environment", + ) + .await?; + let result: Value = + serde_json::from_str(output.trim()).map_err(|_| "future environment probe was invalid")?; + if result["present"] != expected_present || result["reference"] != expected_present { + return Err( + "future process environment did not match acknowledged provider authority".to_string(), + ); + } + Ok(()) +} + +async fn probe(sandbox: &SandboxGuard, client: &str, phase: &str) -> Result { + // Each retained process owns a separate mailbox so both old and current + // references can be checked after detach without a client consuming the + // other client's command. Labels and phases are fixed fixture constants. + let control = format!("{CONTROL}-{client}"); + let result = format!("{RESULT}-{client}"); + // The client consumes the control file as soon as it appears. Publish a + // complete phase atomically so polling cannot observe an empty write. + let command = format!( + "rm -f {result} && printf '%s' '{phase}' > {control}.tmp && mv {control}.tmp {control}" + ); + checked_command( + &mut sandbox_command(sandbox, &["sh", "-c", &command]), + "trigger persistent client phase", + ) + .await?; + let deadline = Instant::now() + Duration::from_secs(20); + loop { + if let Ok(output) = checked_command_with_timeout( + &mut sandbox_command(sandbox, &["cat", &result]), + "read persistent client phase", + Duration::from_secs(10), + ) + .await + { + let response: Value = + serde_json::from_str(output.trim()).map_err(|_| "client result was invalid")?; + if response["phase"] != phase || response["same_reference"] != true { + return Err( + "persistent client changed its retained environment reference".to_string(), + ); + } + return Ok(response); + } + if Instant::now() >= deadline { + return Err(format!("client phase {phase} did not finish")); + } + sleep(Duration::from_millis(100)).await; + } +} + +async fn probe_disallowed_binary( + sandbox: &SandboxGuard, + curl: &str, + host: &str, + port: u16, +) -> Result<(), String> { + // Binary authorization includes allowed ancestors. Launch curl as a + // sibling of the retained Python client, so Python cannot authorize it. + // The shell builtin sends the reference only through curl's stdin pipe. + let script = r#" +test -n "$PROVIDER_READINESS_E2E_TOKEN" || exit 64 +"$1" --version >/dev/null 2>&1 || exit 65 +if printf 'Authorization: Bearer %s\n' "$PROVIDER_READINESS_E2E_TOKEN" | \ + "$1" --silent --fail --max-time 5 --output /dev/null --header @- --data '{}' "$2" 2>/dev/null +then + printf 'unexpected-success' +else + printf 'denied' +fi +"#; + let url = format!("https://{host}:{port}/v1/chat/completions"); + let output = checked_command( + &mut sandbox_command(sandbox, &["sh", "-c", script, "binary-probe", curl, &url]), + "probe independent disallowed binary", + ) + .await?; + if output.trim() != "denied" { + return Err("independent disallowed binary reached the endpoint".to_string()); + } + Ok(()) +} + +fn check( + response: &Value, + pid: u64, + success: bool, + backend_phase: Option, +) -> Result<(), String> { + if response["pid"].as_u64() != Some(pid) || response["ok"].as_bool() != Some(success) { + // Report only typed status fields; never include HTTP error text or + // a serialized response that might later grow a credential field. + return Err(format!( + "client probe failed: pid_matches={}, expected_ok={success}, actual_ok={:?}, status={:?}, error_kind={:?}, reason_kind={:?}", + response["pid"].as_u64() == Some(pid), + response["ok"].as_bool(), + response["status"].as_u64(), + response["error_kind"].as_str(), + response["reason_kind"].as_str(), + )); + } + if let Some(phase) = backend_phase + && (response["backend_phase"].as_u64() != Some(phase) || response["status"] != 200) + { + return Err("backend did not attest the expected credential generation".to_string()); + } + Ok(()) +} + +#[tokio::test] +// Both clients remain alive through detach so their own retained references +// prove revocation across the attach and update launch boundaries. +#[allow(clippy::too_many_lines)] +async fn acknowledged_provider_changes_apply_to_fresh_clients_and_revoke_retained_references() +-> Result<(), String> { + let mut gateway_config = GatewayTrustConfig::load()?; + // Sandbox names are limited to 19 characters. Retain all 64 random bits + // within that limit so concurrent fixtures still own distinct resources. + let name = format!("e2e{:016x}", rand::random::()); + let mut backend = BackendPair::new(&name)?; + // The wrapper's directory is shared with the host Docker daemon in CI; + // a job-container-local temporary path cannot back the TLS bind mount. + let fixture_parent = gateway_config + .path + .parent() + .ok_or("managed gateway configuration has no parent directory")?; + let directory = + TempDir::new_in(fixture_parent).map_err(|_| "could not allocate fixture directory")?; + let context = directory.path().join("image"); + std::fs::create_dir(&context).map_err(|_| "could not allocate public image context")?; + let backend_tls = directory.path().join("backend-tls"); + std::fs::create_dir(&backend_tls).map_err(|_| "could not allocate backend TLS directory")?; + let base = std::env::var("OPENSHELL_E2E_DOCKER_SANDBOX_IMAGE") + .unwrap_or_else(|_| "ghcr.io/nvidia/openshell-community/sandboxes/base:latest".to_string()); + if base.chars().any(char::is_whitespace) { + return Err("fixture image reference contains whitespace".to_string()); + } + let binaries = base_binaries(&base).await?; + let python = binaries["python"] + .as_str() + .ok_or("Python executable was absent")?; + let curl = binaries["curl"] + .as_str() + .ok_or("curl executable was absent")?; + let image = FixtureImage::new()?; + let supervisor_image = FixtureImage::new()?; + // Each backend has its own network namespace, so fixed internal ports need + // no host reservation or publication and remain independent across runs. + let port = BACKEND_PORT; + let other_port = OTHER_BACKEND_PORT; + let keys = [ + format!("e2e-{:032x}", rand::random::()), + format!("e2e-{:032x}", rand::random::()), + ]; + let mut sandbox = None; + let mut sandbox_attempted = false; + let mut clients = Vec::with_capacity(2); + let result = async { + // Begin container mutation inside this scope so certificate, image, + // and enrollment failures still reach explicit bounded teardown. + let [host, other_host] = backend.spawn(&base, &backend_tls).await?; + let (certificate, private_key) = + generate_certificates(directory.path(), &host, &other_host).await?; + std::fs::copy(&certificate, backend_tls.join("backend.crt")) + .map_err(|_| "could not stage backend certificate")?; + let backend_tls_key = backend_tls.join("backend.key.fixture"); + std::fs::copy(&private_key, &backend_tls_key) + .map_err(|_| "could not stage backend TLS key")?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + // The backends inherit the image's unprivileged user. Only their + // mounted leaf key is readable there; the host TempDir is private + // and the CA signing key never enters a container or image context. + std::fs::set_permissions(&backend_tls_key, std::fs::Permissions::from_mode(0o444)) + .map_err(|_| "could not set backend TLS key permissions")?; + } + backend.initialize(&json!({"keys": keys, "ports": [port, other_port], + "certificate": "/fixture-tls/backend.crt", "private_key": "/fixture-tls/backend.key.fixture"})) + .await?; + std::fs::copy(directory.path().join("ca.crt"), context.join("fixture-ca.crt")) + .map_err(|_| "could not copy public fixture CA")?; + std::fs::write(context.join("client.py"), CLIENT) + .map_err(|_| "could not write client source")?; + let dockerfile = context.join("Dockerfile"); + std::fs::write(&dockerfile, format!( + "FROM {base}\nUSER root\nCOPY client.py /opt/provider-readiness-client.py\nUSER sandbox\n" + )).map_err(|_| "could not write fixture Dockerfile")?; + let supervisor_dockerfile = context.join("Dockerfile.supervisor"); + // Outbound TLS belongs to the separate supervisor. Its combined public + // trust bundle is delivered to the workload through the sandbox protocol. + // Preserve the base image's user setting: Docker's archive upload applies + // an explicit image user to the supervisor's private bootstrap files. + std::fs::write(&supervisor_dockerfile, format!( + "FROM {}\nCOPY fixture-ca.crt /tmp/readiness-fixture-ca.crt\nRUN cat /tmp/readiness-fixture-ca.crt >> /etc/ssl/certs/ca-certificates.crt && rm /tmp/readiness-fixture-ca.crt\n", + gateway_config.supervisor_image + )).map_err(|_| "could not write fixture supervisor Dockerfile")?; + image.build(&dockerfile, &context).await?; + supervisor_image.build(&supervisor_dockerfile, &context).await?; + gateway_config.apply(supervisor_image.tag()).await?; + let profile = directory.path().join("profile.json"); + let policy = directory.path().join("policy.json"); + write_profile(&profile, &name, &host, port, python)?; + write_policy(&policy, &host, &other_host, port, other_port, python)?; + let profile_path = profile.to_str().ok_or("profile path was not UTF-8")?; + let policy_path = policy.to_str().ok_or("policy path was not UTF-8")?; + let configuration = json!({"host": host, "other_host": other_host, "port": port, + "other_port": other_port}).to_string(); + cli( + "import synthetic provider profile", + &["provider", "profile", "import", "--file", profile_path], + None, + ) + .await?; + cli( + "create synthetic provider", + &[ + "provider", + "create", + "--name", + &name, + "--type", + &name, + "--credential", + TOKEN_ENV, + ], + Some(&keys[0]), + ) + .await?; + // Retain a known name even when creation times out after persistence, + // so teardown can still remove the partially created sandbox. + sandbox_attempted = true; + sandbox = Some( + SandboxGuard::create(&[ + "--name", + &name, + "--from", + image.tag(), + "--policy", + policy_path, + "--no-auto-providers", + ]) + .await + .map_err(|_| "scratch sandbox could not start")?, + ); + let running = sandbox + .as_ref() + .ok_or("sandbox was absent after creation")?; + future_environment(running, python, false).await?; + let output = cli( + "attach synthetic provider", + &[ + "sandbox", + "provider", + "attach", + &running.name, + &name, + "-o", + "json", + ], + None, + ) + .await?; + let attach = MutationReceipt::capture(&output, running, &name, "attach", &keys)?; + let attached = attach.wait(running, &name, "ready", &keys).await?; + future_environment(running, python, true).await?; + // Start A only after the actual launch environment acknowledgment. + // It retains this static reference until teardown; updates need not + // change the credential selected by an already-running process. + clients.push(PersistentClient::start(running, python, &configuration, "a").await?); + let initial = probe(running, "a", "initial").await?; + let pid_a = initial["pid"].as_u64().ok_or("client A PID was absent")?; + check(&initial, pid_a, true, Some(0))?; + let before = backend.counts().await?; + if before["total"] != 1 || before["accepted"][0] != 1 { + return Err("initial backend request count was incorrect".to_string()); + } + for phase in [ + "wrong_host_control", + "wrong_port_control", + "wrong_path_control", + ] { + let control = probe(running, "a", phase).await?; + check(&control, pid_a, false, None)?; + if control["status"] != 401 || control["backend_phase"] != 0 { + return Err(format!( + "negative endpoint {phase} was not reachable without a credential" + )); + } + } + let before = backend.counts().await?; + if before["total"] != 4 || before["rejected"] != 3 || before["accepted"] != json!([1, 0]) { + return Err("uncredentialed endpoint control assertions failed".to_string()); + } + for phase in [ + "wrong_host", + "wrong_port", + "wrong_path", + "untrusted_ca", + ] { + check(&probe(running, "a", phase).await?, pid_a, false, None)?; + if backend.counts().await? != before { + return Err(format!("denied phase {phase} reached the backend")); + } + } + probe_disallowed_binary(running, curl, &host, port).await?; + if backend.counts().await? != before { + return Err("disallowed binary reached the backend".to_string()); + } + + backend.rotate().await?; + let output = cli( + "update synthetic provider once", + &[ + "provider", + "update", + &name, + "--credential", + TOKEN_ENV, + "-o", + "json", + ], + Some(&keys[1]), + ) + .await?; + let update = MutationReceipt::capture(&output, running, &name, "update", &keys)?; + update.follows(&attach)?; + // No workload requests occur while waiting. Launch B through the + // acknowledged environment boundary; its first request must use the + // new credential without warming requests or success retries. + let updated = update.wait(running, &name, "ready", &keys).await?; + future_environment(running, python, true).await?; + clients.push(PersistentClient::start(running, python, &configuration, "b").await?); + let rotated_request = probe(running, "b", "rotated").await?; + let pid_b = rotated_request["pid"].as_u64().ok_or("client B PID was absent")?; + if pid_b == pid_a { + return Err("provider update reused the original client process".to_string()); + } + check(&rotated_request, pid_b, true, Some(1))?; + let rotated = backend.counts().await?; + if rotated["total"] != 5 || rotated["accepted"] != json!([1, 1]) || rotated["rejected"] != 3 + { + return Err("single-update backend assertions failed".to_string()); + } + + let output = cli( + "detach synthetic provider", + &[ + "sandbox", + "provider", + "detach", + &running.name, + &name, + "-o", + "json", + ], + None, + ) + .await?; + let detach = MutationReceipt::capture(&output, running, &name, "detach", &keys)?; + detach.follows(&update)?; + let revoked = detach.wait(running, &name, "revoked", &keys).await?; + future_environment(running, python, false).await?; + // Detach must revoke the reference while leaving the independently + // authorized route usable; a network outage cannot satisfy this proof. + let control = probe(running, "b", "detached_control").await?; + check(&control, pid_b, false, None)?; + if control["status"] != 401 || control["backend_phase"] != 1 { + return Err("detached endpoint was not reachable without a credential".to_string()); + } + let detached = backend.counts().await?; + if detached["total"] != 6 + || detached["accepted"] != json!([1, 1]) + || detached["rejected"] != 4 + || detached["phase"] != 1 + { + return Err("detached endpoint control assertions failed".to_string()); + } + for (client, pid) in [("a", pid_a), ("b", pid_b)] { + check(&probe(running, client, "detached").await?, pid, false, None)?; + if backend.counts().await? != detached { + return Err(format!("detached client {client} credential reached the backend")); + } + } + println!( + "{}", + json!({"phase": "complete", "client_a_pid": pid_a, "client_b_pid": pid_b, + "clients_retained_own_references": true, "fresh_client_first_request_rotated": true, + "endpoint_denials": true, "binary_denial": true, + "tls_verified": true, "both_client_references_revoked": true, + "future_environment_installed": true, "future_environment_removed": true, + "attach": attached, "update": updated, "detach": revoked}) + ); + Ok(()) + } + .await; + + // Resource names are unique to this run. Always attempt cleanup, including + // failures during enrollment, and keep failures visible without exposing + // captured provider output. The generic guard suppresses delete errors, so + // first issue an explicit checked delete before disarming its fallback. + let mut cleanup_results = Vec::new(); + if sandbox_attempted { + cleanup_results.push( + cli( + "delete fixture sandbox", + &["sandbox", "delete", &name], + None, + ) + .await + .map(|_| ()), + ); + } + if let Some(mut sandbox) = sandbox { + cleanup_results.push( + timeout(COMMAND_TIMEOUT, sandbox.cleanup()) + .await + .map_err(|_| "sandbox guard cleanup timed out".to_string()), + ); + } + for mut client in clients { + cleanup_results.push(client.stop().await); + } + cleanup_results.push( + cli( + "delete synthetic provider", + &["provider", "delete", &name], + None, + ) + .await + .map(|_| ()), + ); + cleanup_results.push( + cli( + "delete synthetic profile", + &["provider", "profile", "delete", &name], + None, + ) + .await + .map(|_| ()), + ); + cleanup_results.push(backend.stop().await); + // Restore the original runtime before removing its replacement. Retain the + // derived supervisor image if restoration fails, and report that failure + // even when a lifecycle assertion already failed. + let gateway_restore = gateway_config.restore().await; + let supervisor_cleanup = if gateway_restore.is_ok() { + supervisor_image.remove().await + } else { + Ok(()) + }; + let image_cleanup = image.remove().await; + let failures = [result, gateway_restore, supervisor_cleanup, image_cleanup] + .into_iter() + .chain(cleanup_results) + .filter_map(Result::err) + .collect::>(); + if failures.is_empty() { + Ok(()) + } else { + Err(failures.join("; ")) + } +} diff --git a/e2e/rust/tests/sandbox_lifecycle.rs b/e2e/rust/tests/sandbox_lifecycle.rs index 946d20802f..279b5fdd47 100644 --- a/e2e/rust/tests/sandbox_lifecycle.rs +++ b/e2e/rust/tests/sandbox_lifecycle.rs @@ -514,6 +514,39 @@ async fn canonical_main_and_exec_receive_declared_environment() { } } +#[tokio::test] +async fn detached_main_exit_during_provisioning_is_classified_as_workload_result() { + let mut sandbox = SandboxGuard::create_detached_main(&["sh", "-c", "exit 11"]) + .await + .expect("fast detached main exit should not be reported as a provisioning failure"); + + wait_for_sandbox_phase(&sandbox.name, "Error", SANDBOX_PRESENCE_TIMEOUT) + .await + .unwrap_or_else(|err| panic!("fast detached main did not reach Error:\n{err}")); + + let mut get_cmd = openshell_cmd(); + get_cmd + .args(["sandbox", "get", &sandbox.name]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let get_output = get_cmd.output().await.expect("spawn openshell sandbox get"); + let details = normalize_output(&format!( + "{}{}", + String::from_utf8_lossy(&get_output.stdout), + String::from_utf8_lossy(&get_output.stderr), + )); + assert!( + get_output.status.success(), + "sandbox get failed:\n{details}" + ); + assert!( + details.contains("Phase: Error") && details.contains("Exit Code: 11"), + "fast detached main should retain its workload result:\n{details}" + ); + + sandbox.cleanup().await; +} + #[tokio::test] async fn canonical_tty_main_uses_sandbox_environment() { let script = r#"printf 'canonical_env home=%s user=%s term=%s\n' "$HOME" "$USER" "$TERM"; while true; do sleep 1; done"#; diff --git a/examples/supervisor-middleware-content-guard/Cargo.lock b/examples/supervisor-middleware-content-guard/Cargo.lock index 4a2a3a150b..381cb63c40 100644 --- a/examples/supervisor-middleware-content-guard/Cargo.lock +++ b/examples/supervisor-middleware-content-guard/Cargo.lock @@ -246,6 +246,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + [[package]] name = "clap" version = "4.6.7" @@ -301,6 +312,16 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "combine" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -326,6 +347,21 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + [[package]] name = "crypto-common" version = "0.1.7" @@ -336,6 +372,12 @@ dependencies = [ "typenum", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "digest" version = "0.10.7" @@ -499,6 +541,7 @@ dependencies = [ "cfg-if", "libc", "r-efi", + "rand_core", ] [[package]] @@ -553,6 +596,25 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hickory-proto" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" +dependencies = [ + "data-encoding", + "idna", + "ipnet", + "jni", + "once_cell", + "rand", + "ring", + "thiserror", + "tinyvec", + "tracing", + "url", +] + [[package]] name = "http" version = "1.5.0" @@ -847,6 +909,55 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -1023,6 +1134,10 @@ name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] [[package]] name = "once_cell_polyfill" @@ -1075,6 +1190,19 @@ dependencies = [ "tower", ] +[[package]] +name = "openshell-policy" +version = "0.0.0" +dependencies = [ + "hickory-proto", + "miette", + "openshell-core", + "openshell-policy-schema", + "prost-types", + "serde", + "serde_json", +] + [[package]] name = "openshell-policy-schema" version = "0.0.0" @@ -1091,6 +1219,7 @@ version = "0.0.0" dependencies = [ "clap", "openshell-core", + "openshell-policy", "prost-types", "tokio", "tokio-stream", @@ -1181,6 +1310,12 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + [[package]] name = "potential_utf" version = "0.1.6" @@ -1363,6 +1498,23 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1427,6 +1579,15 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.4" @@ -1503,6 +1664,15 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "schannel" version = "0.1.29" @@ -1541,6 +1711,12 @@ dependencies = [ "libc", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -1591,7 +1767,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -1611,6 +1787,22 @@ dependencies = [ "libc", ] +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" @@ -1775,6 +1967,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.53.1" @@ -2064,6 +2262,16 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + [[package]] name = "want" version = "0.3.1" @@ -2124,6 +2332,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-link" version = "0.2.1" diff --git a/examples/supervisor-middleware-content-guard/Cargo.toml b/examples/supervisor-middleware-content-guard/Cargo.toml index 135316979c..89e7b7a85e 100644 --- a/examples/supervisor-middleware-content-guard/Cargo.toml +++ b/examples/supervisor-middleware-content-guard/Cargo.toml @@ -20,6 +20,9 @@ tokio = { version = "1.43", features = ["macros", "rt-multi-thread"] } tokio-stream = "0.1" tonic = { version = "0.14", features = ["transport"] } +[dev-dependencies] +openshell-policy = { path = "../../crates/openshell-policy" } + [[bin]] name = "supervisor-middleware-content-guard" path = "src/main.rs" diff --git a/examples/supervisor-middleware-content-guard/README.md b/examples/supervisor-middleware-content-guard/README.md index 53eda94210..fcdc37df56 100644 --- a/examples/supervisor-middleware-content-guard/README.md +++ b/examples/supervisor-middleware-content-guard/README.md @@ -8,18 +8,18 @@ SPDX-License-Identifier: Apache-2.0 > [!WARNING] > Supervisor middleware is a research preview. Its policy and service contracts may change without compatibility guarantees. Use it only to prototype and evaluate middleware integrations. -This example implements an operator-run supervisor middleware service. It scans UTF-8 HTTP request bodies and complete client-to-upstream WebSocket text messages for configured literal strings, then either replaces every match or denies the request or message. Findings report only aggregate counts and never include configured terms or inspected content. +This configured-literal guard applies the same case-sensitive terms to UTF-8 HTTP request bodies, complete HTTP response bodies, and client WebSocket text messages. It is not a general PII detector. > [!WARNING] -> This intentionally simple implementation demonstrates the supervisor middleware service contract. It is not a complete or reliable content guard and must not be used as a security control. It handles only UTF-8 HTTP request bodies and WebSocket text messages with case-sensitive literal terms, merges overlapping literal match ranges before redaction, and does not address encodings, transformations, normalization, binary WebSocket messages, upstream-to-client messages, or adversarial inputs that a production content guard must handle. +> This intentionally simple implementation demonstrates the supervisor middleware service contract. It is not a complete or reliable content guard and must not be used as a security control. It handles only UTF-8 HTTP request and response bodies and WebSocket text messages with case-sensitive literal terms, merges overlapping literal match ranges before redaction, and does not address encodings, transformations, normalization, binary WebSocket messages, upstream-to-client messages, or adversarial inputs that a production content guard must handle. ## Prerequisites -Install `cargo`, `curl`, `jq`, and `openssl` on the host before running the smoke script. +Install `cargo`, `curl`, `jq`, `openssl`, `mise`, and `uv` with Python 3 on the host before running the smoke script. Start Docker or Podman. The supervisor image build uses the repository's Linux cross-compilation toolchain, including `cargo-zigbuild` and Zig on macOS. Install the repository's mise tools before running it. ## Run the smoke example -Run the end-to-end smoke suite to build and start a local gateway, start the content-guard service, create a sandbox, and send the same request body to two destinations: +Run the end-to-end smoke suite to build a local gateway and sandbox supervisor, start the content-guard service, create a sandbox, and send the same request body to two destinations: ```shell ./examples/supervisor-middleware-content-guard/smoke.sh --test-suite @@ -39,6 +39,16 @@ The script creates the sandbox and prints the guarded and unguarded request comm CONTENT_GUARD_SMOKE_HOST=192.168.1.10 ./examples/supervisor-middleware-content-guard/smoke.sh --test-suite ``` +The script defaults to Docker. Set `CONTENT_GUARD_SMOKE_DRIVER=podman` to build and run with Podman instead. + +On Linux and macOS, the script runs `mise run docker:build:supervisor` with the selected container engine to build a Linux supervisor from the current checkout. It configures that driver's `supervisor_image` with a unique local tag, so the response checks exercise the local runtime changes. macOS host binaries are never used inside the sandbox. The local image remains available after the smoke run. + +Cargo's configured target directory applies to the host binaries and the Linux supervisor build. For example: + +```shell +CARGO_TARGET_DIR=/tmp/content-guard-target ./examples/supervisor-middleware-content-guard/smoke.sh --test-suite +``` + ## Run manually Start the service before starting the gateway. Bind to all host interfaces so a local containerized gateway and sandbox supervisor can reach it: @@ -54,6 +64,7 @@ Add the service registration to your local gateway TOML: [[openshell.supervisor.middleware]] name = "content-guard-example" grpc_endpoint = "http://host.openshell.internal:50051" +allow_insecure_transport = true max_payload_bytes = 262144 timeout = "500ms" ``` @@ -84,6 +95,34 @@ curl -sS https://httpbin.org/anything \ The echoed JSON body contains `[FILTERED]` instead of the configured term. +## HTTP response behavior + +The smoke launcher starts the local fixture. To start it manually: + +```shell +uv run --no-project python examples/supervisor-middleware-content-guard/upstream.py +``` + +The policy permits `GET /clean` and `GET /sensitive` on +`http://host.openshell.internal:18081`. The first returns ordinary public text. +The second contains both configured terms. Redact mode returns +`contains [FILTERED] and [FILTERED]`. Deny mode returns typed `BlockDelivery` +with reason code `content_match`, which produces the canonical 403 response +before delivery. The smoke suite recreates the sandbox in deny mode and checks +both clean and matching responses through the external gRPC service. + +Every selected response requires `WHOLE_BODY_BYTES`. If that mode is unavailable, +the service returns a middleware failure and the policy's `on_error` decides +whether delivery fails open or closed. This includes encoded, partial, +no-transform, bodyless, and known oversized responses. Unknown-length bodies can +also exceed the runtime limit during collection. Invalid UTF-8 fails the same way. +The example policy uses `fail_closed`. + +Clean bodies pass unchanged. Matching spans are merged and replaced in the +complete body, so transport chunk boundaries do not affect matching. Trailers +are accepted without mutation. The guard does not decode compressed bodies, +normalize Unicode, scan response headers, retain stream units, or spool bodies. + ## WebSocket behavior For a selected WebSocket upgrade, the service accepts preflight, waits for the session-start notification, and evaluates each complete client-to-upstream text message. Redact mode returns a replacement message, while deny mode returns `content_match` and OpenShell closes the session according to middleware policy. Session-start and session-end events are notifications and do not produce results. @@ -107,4 +146,4 @@ config: - prototype-secret ``` -The implementation supports `HTTP_REQUEST/PRE_CREDENTIALS` and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`, advertises a 256 KiB limit for each operation, and inherits the service-wide RPC timeout. The gateway registration's `max_payload_bytes` may set a smaller shared limit. A binding can advertise a shorter timeout, but it cannot extend the operator-configured timeout. +The implementation supports `HTTP_REQUEST/PRE_CREDENTIALS`, `HTTP_RESPONSE/PRE_RETURN`, and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. It advertises a 256 KiB limit for each operation and inherits the service-wide RPC timeout. The gateway registration's `max_payload_bytes` may set a smaller shared limit. A binding can advertise a shorter timeout, but it cannot extend the operator-configured timeout. diff --git a/examples/supervisor-middleware-content-guard/policy.yaml b/examples/supervisor-middleware-content-guard/policy.yaml index ff3d9ef89e..da08607f27 100644 --- a/examples/supervisor-middleware-content-guard/policy.yaml +++ b/examples/supervisor-middleware-content-guard/policy.yaml @@ -18,6 +18,7 @@ network_middlewares: endpoints: include: - httpbin.org + - host.openshell.internal network_policies: httpbin: @@ -44,3 +45,18 @@ network_policies: path: /anything binaries: - path: /usr/bin/curl + guard-responses: + name: Guard responses + endpoints: + - host: host.openshell.internal + port: 18081 + protocol: rest + rules: + - allow: + method: GET + path: /clean + - allow: + method: GET + path: /sensitive + binaries: + - path: /usr/bin/curl diff --git a/examples/supervisor-middleware-content-guard/smoke.sh b/examples/supervisor-middleware-content-guard/smoke.sh index 96aa9e3c34..e37c8a5317 100755 --- a/examples/supervisor-middleware-content-guard/smoke.sh +++ b/examples/supervisor-middleware-content-guard/smoke.sh @@ -24,6 +24,8 @@ Options: Environment: CONTENT_GUARD_SMOKE_HOST Non-loopback host address reachable from both the gateway and sandbox containers. + CONTENT_GUARD_SMOKE_DRIVER + Compute driver: docker (default) or podman. EOF } @@ -103,19 +105,30 @@ detect_service_host() { } SERVICE_HOST="$(detect_service_host)" +COMPUTE_DRIVER="${CONTENT_GUARD_SMOKE_DRIVER:-docker}" +case "$COMPUTE_DRIVER" in + docker | podman) ;; + *) + echo "CONTENT_GUARD_SMOKE_DRIVER must be docker or podman" >&2 + exit 1 + ;; +esac if [[ "$SERVICE_HOST" == "localhost" || "$SERVICE_HOST" == "::1" || "$SERVICE_HOST" == 127.* || "$SERVICE_HOST" == *:* ]]; then echo "CONTENT_GUARD_SMOKE_HOST must be a non-loopback IPv4 address: $SERVICE_HOST" >&2 exit 1 fi -TMPDIR="$(mktemp -d)" -LOG_DIR="$TMPDIR/logs" -JWT_DIR="$TMPDIR/jwt" -GATEWAY_CONFIG="$TMPDIR/gateway.toml" +SMOKE_TMP_DIR="$(mktemp -d)" +LOG_DIR="$SMOKE_TMP_DIR/logs" +JWT_DIR="$SMOKE_TMP_DIR/jwt" +GATEWAY_CONFIG="$SMOKE_TMP_DIR/gateway.toml" SETUP_LOG="$LOG_DIR/setup.log" GATEWAY_LOG="$LOG_DIR/gateway.log" MIDDLEWARE_LOG="$LOG_DIR/middleware.log" +UPSTREAM_LOG="$LOG_DIR/upstream.log" +SANDBOX_LOG="$LOG_DIR/sandbox.log" RUN_ID="content-guard-smoke-$$-$RANDOM" +SUPERVISOR_IMAGE="localhost/openshell-content-guard/supervisor:$RUN_ID" # Sandbox names are capped at 19 characters. Use a short prefix with # the PID for uniqueness; keep the full RUN_ID for gateway identity. SANDBOX_NAME="cg-$$-$RANDOM" @@ -141,8 +154,13 @@ cleanup() { wait "$MIDDLEWARE_PID" 2>/dev/null || true fi + if [[ -n "${UPSTREAM_PID:-}" ]]; then + kill "$UPSTREAM_PID" 2>/dev/null || true + wait "$UPSTREAM_PID" 2>/dev/null || true + fi + if [[ "$status" -eq 0 ]]; then - rm -rf "$TMPDIR" + rm -rf "$SMOKE_TMP_DIR" else echo "logs retained in $LOG_DIR" >&2 fi @@ -213,8 +231,12 @@ gateway_id = "$RUN_ID" [[openshell.supervisor.middleware]] name = "content-guard-example" grpc_endpoint = "http://$SERVICE_HOST:$MIDDLEWARE_PORT" +allow_insecure_transport = true max_payload_bytes = 262144 timeout = "500ms" + +[openshell.drivers.$COMPUTE_DRIVER] +supervisor_image = "$SUPERVISOR_IMAGE" EOF } @@ -238,11 +260,13 @@ generate_gateway_jwt_bundle() { dump_logs() { local label path - for label in setup gateway middleware; do + for label in setup gateway middleware upstream sandbox; do case "$label" in setup) path="$SETUP_LOG" ;; gateway) path="$GATEWAY_LOG" ;; middleware) path="$MIDDLEWARE_LOG" ;; + upstream) path="$UPSTREAM_LOG" ;; + sandbox) path="$SANDBOX_LOG" ;; esac printf '\n--- %s log: %s ---\n' "$label" "$path" >&2 if [[ -f "$path" ]]; then @@ -253,8 +277,23 @@ dump_logs() { done } +capture_sandbox_log() { + local container_id + + if [[ "$SANDBOX_CREATED" -ne 1 || "$COMPUTE_DRIVER" != "docker" ]] || + ! command -v docker >/dev/null 2>&1; then + return + fi + + container_id="$(docker ps -aq --filter "name=$SANDBOX_NAME" | head -n 1)" + if [[ -n "$container_id" ]]; then + docker logs "$container_id" >"$SANDBOX_LOG" 2>&1 || true + fi +} + fail() { printf 'FAIL %s\n' "$1" >&2 + capture_sandbox_log dump_logs exit 1 } @@ -315,17 +354,42 @@ wait_for_middleware() { fail "content guard service is reachable at $SERVICE_HOST:$MIDDLEWARE_PORT" } +start_upstream() { + printf 'INFO starting content guard upstream at %s:18081\n' "$SERVICE_HOST" + uv run --no-project python "$EXAMPLE_DIR/upstream.py" >"$UPSTREAM_LOG" 2>&1 & + UPSTREAM_PID=$! +} + +wait_for_upstream() { + for _ in {1..30}; do + if ! kill -0 "$UPSTREAM_PID" 2>/dev/null; then + fail "content guard upstream starts" + fi + if curl -fsS --max-time 1 "http://127.0.0.1:18081/clean" >/dev/null 2>&1; then + printf 'INFO content guard upstream is ready\n' + return + fi + sleep 1 + done + fail "content guard upstream is reachable" +} + start_gateway() { + local -a driver_args=() + if [[ -n "$COMPUTE_DRIVER" ]]; then + driver_args=(--compute-driver "$COMPUTE_DRIVER") + fi printf 'INFO starting gateway\n' - env -u OPENSHELL_COMPUTE_DRIVER "$GATEWAY_BIN" \ + env -u OPENSHELL_DRIVERS -u OPENSHELL_COMPUTE_DRIVER "$GATEWAY_BIN" \ + "${driver_args[@]}" \ --config "$GATEWAY_CONFIG" \ --bind-address 127.0.0.1 \ --port "$GATEWAY_PORT" \ --health-port "$HEALTH_PORT" \ --metrics-port 0 \ - --log-level info \ + --log-level "${CONTENT_GUARD_SMOKE_LOG_LEVEL:-info}" \ --disable-tls \ - --db-url "sqlite://$TMPDIR/gateway.db" >"$GATEWAY_LOG" 2>&1 & + --db-url "sqlite://$SMOKE_TMP_DIR/gateway.db" >"$GATEWAY_LOG" 2>&1 & GATEWAY_PID=$! } @@ -353,10 +417,10 @@ create_sandbox() { "$CLI_BIN" --gateway-endpoint "$GATEWAY_ENDPOINT" ) + SANDBOX_CREATED=1 run_setup_step \ "creating content guard sandbox" \ - "${CLI[@]}" sandbox create --name "$SANDBOX_NAME" --policy "$EXAMPLE_DIR/policy.yaml" --keep --no-tty -- /bin/sh -lc true - SANDBOX_CREATED=1 + "${CLI[@]}" sandbox create --name "$SANDBOX_NAME" --policy "$EXAMPLE_DIR/policy.yaml" --no-tty --detach -- sleep infinity } request() { @@ -367,14 +431,33 @@ request() { --data '{"note":"prototype-secret"}' } +response_request() { + local path="$1" + "${CLI[@]}" sandbox exec --name "$SANDBOX_NAME" --no-tty -- \ + curl -sS -i --max-time 20 "http://host.openshell.internal:18081/$path" +} + run_suite() { local guarded_output="$LOG_DIR/guarded.out" local unguarded_output="$LOG_DIR/unguarded.out" + local response_output="$LOG_DIR/response.out" printf 'INFO sending guarded request to httpbin.org\n' if ! request httpbin.org >"$guarded_output" 2>>"$SETUP_LOG"; then fail "guarded request completes" fi + + printf 'INFO checking response pass-through and redaction\n' + if ! response_request clean >"$response_output" 2>>"$SETUP_LOG" || + ! grep -Fq 'ordinary public text' "$response_output"; then + fail "clean response passes unchanged" + fi + if ! response_request sensitive >"$response_output" 2>>"$SETUP_LOG" || + ! grep -Fq 'contains [FILTERED] and [FILTERED]' "$response_output" || + grep -Fq 'prototype-secret' "$response_output"; then + fail "configured response terms are redacted" + fi + printf 'PASS response pass-through and redaction\n' if grep -Fq '[FILTERED]' "$guarded_output" && ! grep -Fq 'prototype-secret' "$guarded_output"; then printf 'PASS guarded request is filtered\n' else @@ -393,6 +476,24 @@ run_suite() { fail "unguarded request is unchanged" fi + # Recreate with the same terms in deny mode, through the external service. + "${CLI[@]}" sandbox delete "$SANDBOX_NAME" >>"$SETUP_LOG" 2>&1 + SANDBOX_CREATED=0 + sed '/replacement:/d; s/mode: redact/mode: deny/' "$EXAMPLE_DIR/policy.yaml" >"$SMOKE_TMP_DIR/deny.yaml" + SANDBOX_CREATED=1 + run_setup_step "creating deny sandbox" "${CLI[@]}" sandbox create --name "$SANDBOX_NAME" --policy "$SMOKE_TMP_DIR/deny.yaml" --no-tty --detach -- sleep infinity + if ! response_request sensitive >"$response_output" 2>>"$SETUP_LOG" || + ! grep -Fq 'HTTP/1.1 403 Forbidden' "$response_output" || + ! grep -Fq 'content_match' "$response_output" || + grep -Fq 'prototype-secret' "$response_output"; then + fail "configured response term blocks delivery" + fi + if ! response_request clean >"$response_output" 2>>"$SETUP_LOG" || + ! grep -Fq 'ordinary public text' "$response_output"; then + fail "deny mode passes clean responses" + fi + printf 'PASS response denial\n' + "${CLI[@]}" sandbox delete "$SANDBOX_NAME" >>"$SETUP_LOG" 2>&1 SANDBOX_CREATED=0 echo "ALL PASS content guard smoke" @@ -438,15 +539,27 @@ require_command cargo require_command curl require_command jq require_command openssl +require_command uv +require_command mise ROOT_TARGET_DIR="$(cargo_target_dir "$ROOT/Cargo.toml")" EXAMPLE_TARGET_DIR="$(cargo_target_dir "$EXAMPLE_DIR/Cargo.toml")" GATEWAY_BIN="$ROOT_TARGET_DIR/debug/openshell-gateway" CLI_BIN="$ROOT_TARGET_DIR/debug/openshell" MIDDLEWARE_BIN="$EXAMPLE_TARGET_DIR/debug/supervisor-middleware-content-guard" run_setup_step "building gateway" cargo build --quiet -p openshell-gateway --bin openshell-gateway +# Always rebuild from this checkout and load into the selected runtime. Native +# macOS binaries cannot run in Linux sandboxes; Podman also needs an image. +# A unique tag prevents the driver from selecting an older published runtime. +run_setup_step "building Linux sandbox supervisor image" \ + env -u CI -u DOCKER_PLATFORM -u DOCKER_PUSH -u DOCKER_OUTPUT \ + CONTAINER_ENGINE="$COMPUTE_DRIVER" PREBUILT_AUTO_STAGE=1 \ + IMAGE_REGISTRY=localhost/openshell-content-guard IMAGE_TAG="$RUN_ID" \ + mise run docker:build:supervisor run_setup_step "building content guard" cargo build --quiet --manifest-path "$EXAMPLE_DIR/Cargo.toml" run_setup_step "building CLI" cargo build --quiet -p openshell-cli --bin openshell generate_gateway_jwt_bundle +start_upstream +wait_for_upstream start_middleware wait_for_middleware start_gateway diff --git a/examples/supervisor-middleware-content-guard/src/main.rs b/examples/supervisor-middleware-content-guard/src/main.rs index 0e9430bb7d..c6489d742a 100644 --- a/examples/supervisor-middleware-content-guard/src/main.rs +++ b/examples/supervisor-middleware-content-guard/src/main.rs @@ -6,20 +6,30 @@ use std::net::SocketAddr; use std::ops::Range; use clap::Parser; -use openshell_core::middleware::WebSocketResponseStream; +use openshell_core::middleware::{HttpResponseResultStream, WebSocketResponseStream}; +use openshell_core::proto::middleware::v1::http_response_pre_return_server::{ + HttpResponsePreReturn, HttpResponsePreReturnServer, +}; use openshell_core::proto::middleware::v1::supervisor_middleware_server::{ SupervisorMiddleware, SupervisorMiddlewareServer, }; use openshell_core::proto::{ - Decision, Finding, HttpRequestEvaluation, HttpRequestResult, MiddlewareBinding, - MiddlewareManifest, SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, - ValidateConfigRequest, ValidateConfigResponse, WebSocketMessage, WebSocketMessageResult, - WebSocketPreflightAction, WebSocketPreflightDecision, WebSocketSessionEvent, - WebSocketSessionEventResult, web_socket_message, web_socket_message_result, - web_socket_session_event, web_socket_session_event_result, + Decision, Finding, HttpRequestEvaluation, HttpRequestResult, HttpResponseBlockDelivery, + HttpResponseBodyMode, HttpResponseBodyResult, HttpResponseBodyTransform, HttpResponseEvent, + HttpResponseEventResult, HttpResponsePreflightInspect, HttpResponsePreflightResult, + HttpResponseTrailersResult, MiddlewareBinding, MiddlewareManifest, + SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, ValidateConfigRequest, + ValidateConfigResponse, WebSocketMessage, WebSocketMessageResult, WebSocketPreflightAction, + WebSocketPreflightDecision, WebSocketSessionEvent, WebSocketSessionEventResult, + http_response_body_result, http_response_body_transform, http_response_body_unit, + http_response_event, http_response_event_result, http_response_preflight_result, + web_socket_message, web_socket_message_result, web_socket_session_event, + web_socket_session_event_result, }; use prost_types::Struct; use prost_types::value::Kind; +use tokio::sync::mpsc; +use tokio_stream::wrappers::ReceiverStream; use tokio_stream::{Stream, StreamExt}; use tonic::transport::Server; use tonic::{Request, Response, Status}; @@ -238,6 +248,12 @@ impl SupervisorMiddleware for ContentGuard { max_payload_bytes: MAX_PAYLOAD_BYTES, request_timeout: None, }, + MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpResponse as i32, + phase: SupervisorMiddlewarePhase::PreReturn as i32, + max_payload_bytes: MAX_PAYLOAD_BYTES, + request_timeout: None, + }, ], expected_audience: String::new(), })) @@ -282,6 +298,146 @@ impl SupervisorMiddleware for ContentGuard { } } +#[derive(Debug, Default)] +struct ResponseSessionState { + config: Option, + body_ended: bool, + trailers_seen: bool, +} +impl ResponseSessionState { + fn preflight( + &mut self, + preflight: openshell_core::proto::HttpResponsePreflight, + ) -> Result { + if self.config.is_some() { + return Err(Status::failed_precondition("duplicate preflight")); + } + let config = + GuardConfig::parse(preflight.config.as_ref()).map_err(Status::invalid_argument)?; + if !preflight + .permitted_body_modes + .contains(&(HttpResponseBodyMode::WholeBodyBytes as i32)) + { + return Err(Status::failed_precondition( + "content guard requires WHOLE_BODY_BYTES", + )); + } + self.config = Some(config); + Ok(HttpResponseEventResult { + result: Some(http_response_event_result::Result::PreflightResult( + HttpResponsePreflightResult { + action: Some(http_response_preflight_result::Action::Inspect( + HttpResponsePreflightInspect { + body_mode: HttpResponseBodyMode::WholeBodyBytes as i32, + header_mutations: vec![], + }, + )), + ..Default::default() + }, + )), + }) + } + fn body( + &mut self, + body: openshell_core::proto::HttpResponseBodyUnit, + ) -> Result { + let config = self + .config + .as_ref() + .ok_or_else(|| Status::failed_precondition("body before preflight"))?; + if self.body_ended || body.sequence != 1 || !body.end_of_stream { + return Err(Status::failed_precondition( + "expected one complete response body", + )); + } + let Some(http_response_body_unit::Payload::Data(data)) = body.payload else { + return Err(Status::invalid_argument("body data required")); + }; + let text = std::str::from_utf8(&data) + .map_err(|_| Status::invalid_argument("content guard requires a UTF-8 body"))?; + let result = inspect(config, text); + let action = if result.denied { + http_response_body_result::Action::BlockDelivery(HttpResponseBlockDelivery {}) + } else if let Some(replacement) = result.replacement { + http_response_body_result::Action::Transform(HttpResponseBodyTransform { + replacement: Some(http_response_body_transform::Replacement::Data( + replacement.into_bytes(), + )), + }) + } else { + http_response_body_result::Action::PassThrough( + openshell_core::proto::HttpResponseBodyPassThrough {}, + ) + }; + self.body_ended = true; + Ok(HttpResponseEventResult { + result: Some(http_response_event_result::Result::BodyResult( + HttpResponseBodyResult { + sequence: body.sequence, + action: Some(action), + reason: result.reason, + reason_code: result.reason_code, + findings: result.findings, + metadata: result.metadata, + }, + )), + }) + } + fn trailers(&mut self) -> Result { + if !self.body_ended || self.trailers_seen { + return Err(Status::failed_precondition("expected trailers after body")); + } + self.trailers_seen = true; + Ok(HttpResponseEventResult { + result: Some(http_response_event_result::Result::TrailersResult( + HttpResponseTrailersResult::default(), + )), + }) + } +} + +#[tonic::async_trait] +impl HttpResponsePreReturn for ContentGuard { + type EvaluateStream = HttpResponseResultStream; + + async fn evaluate( + &self, + request: Request>, + ) -> Result, Status> { + let mut events = request.into_inner(); + let (sender, receiver) = mpsc::channel(4); + tokio::spawn(async move { + let mut state = ResponseSessionState::default(); + while let Some(event) = events.next().await { + let result = match event { + Ok(event) => match event.event { + Some(http_response_event::Event::Preflight(preflight)) => { + state.preflight(preflight) + } + Some(http_response_event::Event::Body(body)) => state.body(body), + Some(http_response_event::Event::Trailers(_)) => state.trailers(), + Some(http_response_event::Event::SessionEnd(_)) => break, + None => Err(Status::invalid_argument("response event is required")), + }, + Err(error) => Err(error), + }; + match result { + Ok(result) => { + if sender.send(Ok(result)).await.is_err() { + break; + } + } + Err(error) => { + let _ = sender.send(Err(error)).await; + break; + } + } + } + }); + Ok(Response::new(Box::pin(ReceiverStream::new(receiver)))) + } +} + fn validate_phase(phase: i32) -> Result<(), String> { if phase != PHASE as i32 { return Err(format!("unsupported phase '{phase}'")); @@ -289,11 +445,37 @@ fn validate_phase(phase: i32) -> Result<(), String> { Ok(()) } +#[derive(Default)] +struct GuardOutcome { + denied: bool, + replacement: Option, + reason: String, + reason_code: String, + findings: Vec, + metadata: HashMap, +} fn evaluate(config: &GuardConfig, body: &str) -> HttpRequestResult { + let result = inspect(config, body); + HttpRequestResult { + decision: if result.denied { + Decision::Deny + } else { + Decision::Allow + } as i32, + has_body: result.replacement.is_some(), + body: result.replacement.unwrap_or_default().into_bytes(), + reason: result.reason, + reason_code: result.reason_code, + findings: result.findings, + metadata: result.metadata, + ..Default::default() + } +} +fn inspect(config: &GuardConfig, body: &str) -> GuardOutcome { let (ranges, match_count, matched_term_count) = find_match_ranges(body, &config.terms); if match_count == 0 { - return allow_result(); + return GuardOutcome::default(); } let finding = Finding { @@ -315,27 +497,22 @@ fn evaluate(config: &GuardConfig, body: &str) -> HttpRequestResult { ), ]); - match config.mode { - Mode::Redact => HttpRequestResult { - decision: Decision::Allow as i32, - reason: String::new(), - body: redact_ranges(body, &ranges, &config.replacement).into_bytes(), - has_body: true, - header_mutations: Vec::new(), - findings: vec![finding], - metadata, - reason_code: String::new(), + GuardOutcome { + denied: config.mode == Mode::Deny, + replacement: (config.mode == Mode::Redact) + .then(|| redact_ranges(body, &ranges, &config.replacement)), + reason: if config.mode == Mode::Deny { + "payload matched configured content".into() + } else { + String::new() }, - Mode::Deny => HttpRequestResult { - decision: Decision::Deny as i32, - reason: "payload matched configured content".into(), - body: Vec::new(), - has_body: false, - header_mutations: Vec::new(), - findings: vec![finding], - metadata, - reason_code: "content_match".into(), + reason_code: if config.mode == Mode::Deny { + "content_match".into() + } else { + String::new() }, + findings: vec![finding], + metadata, } } @@ -356,23 +533,21 @@ fn evaluate_websocket_message( "WebSocket text message exceeds {MAX_PAYLOAD_BYTES} bytes" ))); } - let result = evaluate(config, payload); - let replacement = if result.has_body { - Some(web_socket_message_result::Replacement::Text( - String::from_utf8(result.body) - .expect("content guard replacements are constructed from UTF-8 text"), - )) - } else { - None - }; + let result = inspect(config, payload); Ok(WebSocketMessageResult { sequence: message.sequence, - decision: result.decision, - replacement, + decision: if result.denied { + Decision::Deny + } else { + Decision::Allow + } as i32, + replacement: result + .replacement + .map(web_socket_message_result::Replacement::Text), reason: result.reason, + reason_code: result.reason_code, findings: result.findings, metadata: result.metadata, - reason_code: result.reason_code, }) } @@ -451,25 +626,13 @@ fn redact_ranges(body: &str, ranges: &[Range], replacement: &str) -> Stri transformed } -fn allow_result() -> HttpRequestResult { - HttpRequestResult { - decision: Decision::Allow as i32, - reason: String::new(), - body: Vec::new(), - has_body: false, - header_mutations: Vec::new(), - findings: Vec::new(), - metadata: HashMap::new(), - reason_code: String::new(), - } -} - #[tokio::main] async fn main() -> Result<(), Box> { let cli = Cli::parse(); println!("serving {MANIFEST_NAME} on http://{}", cli.bind); Server::builder() .add_service(SupervisorMiddlewareServer::new(ContentGuard)) + .add_service(HttpResponsePreReturnServer::new(ContentGuard)) .serve(cli.bind) .await?; Ok(()) @@ -478,7 +641,10 @@ async fn main() -> Result<(), Box> { #[cfg(test)] mod tests { use super::*; - use openshell_core::proto::{MiddlewareSessionEnd, WebSocketPreflight, WebSocketSessionStart}; + use openshell_core::proto::{ + HttpResponseBodyUnit, HttpResponsePreflight, MiddlewareSessionEnd, WebSocketPreflight, + WebSocketSessionStart, + }; use prost_types::{ListValue, Value}; use std::collections::BTreeMap; @@ -511,13 +677,13 @@ mod tests { } #[tokio::test] - async fn manifest_advertises_http_and_websocket_bindings() { + async fn manifest_advertises_request_response_and_websocket_bindings() { let manifest = SupervisorMiddleware::describe(&ContentGuard, Request::new(())) .await .expect("describe") .into_inner(); - assert_eq!(manifest.bindings.len(), 2); + assert_eq!(manifest.bindings.len(), 3); assert_eq!( manifest.bindings[0].operation, SupervisorMiddlewareOperation::HttpRequest as i32 @@ -528,6 +694,110 @@ mod tests { SupervisorMiddlewareOperation::WebsocketMessage as i32 ); assert_eq!(manifest.bindings[1].max_payload_bytes, MAX_PAYLOAD_BYTES); + assert_eq!( + manifest.bindings[2].operation, + SupervisorMiddlewareOperation::HttpResponse as i32 + ); + assert_eq!( + manifest.bindings[2].phase, + SupervisorMiddlewarePhase::PreReturn as i32 + ); + } + + fn response_preflight(mode: &str) -> HttpResponsePreflight { + HttpResponsePreflight { + config: Some(config(mode, &["prototype-secret", "秘密"], None)), + permitted_body_modes: vec![HttpResponseBodyMode::WholeBodyBytes as i32], + ..Default::default() + } + } + #[test] + fn response_guard_passes_redacts_and_denies() { + for (mode, input, expected) in [ + ("redact", "clean", None), + ( + "redact", + "a prototype-secret 秘密", + Some("a [REDACTED] [REDACTED]"), + ), + ("deny", "prototype-secret", None), + ] { + let mut state = ResponseSessionState::default(); + state.preflight(response_preflight(mode)).unwrap(); + let unit = HttpResponseBodyUnit { + sequence: 1, + payload: Some(http_response_body_unit::Payload::Data( + input.as_bytes().to_vec(), + )), + end_of_stream: true, + }; + let result = state.body(unit.clone()).unwrap(); + assert!(state.body(unit).is_err()); + let Some(http_response_event_result::Result::BodyResult(result)) = result.result else { + panic!("body result") + }; + if mode == "deny" { + assert!(matches!( + result.action, + Some(http_response_body_result::Action::BlockDelivery(_)) + )); + assert_eq!(result.reason_code, "content_match"); + } else if let Some(expected) = expected { + let Some(http_response_body_result::Action::Transform(transform)) = result.action + else { + panic!("transform") + }; + assert_eq!( + transform.replacement, + Some(http_response_body_transform::Replacement::Data( + expected.as_bytes().to_vec() + )) + ); + } else { + assert!(matches!( + result.action, + Some(http_response_body_result::Action::PassThrough(_)) + )); + } + let trailers = state.trailers().unwrap(); + let Some(http_response_event_result::Result::TrailersResult(trailers)) = + trailers.result + else { + panic!("trailers") + }; + assert!(trailers.trailer_mutations.is_empty()); + assert!(state.trailers().is_err()); + } + } + #[test] + fn response_guard_rejects_unavailable_inspection_and_invalid_input() { + let mut preflight = response_preflight("redact"); + preflight.permitted_body_modes = vec![HttpResponseBodyMode::HeadersOnly as i32]; + assert!( + ResponseSessionState::default() + .preflight(preflight) + .is_err() + ); + for (sequence, end_of_stream, payload) in [ + (2, true, Some(vec![])), + (1, false, Some(vec![])), + (1, true, Some(vec![0xff])), + (1, true, None), + ] { + let mut state = ResponseSessionState::default(); + assert!(state.trailers().is_err()); + state.preflight(response_preflight("redact")).unwrap(); + assert!(state.preflight(response_preflight("redact")).is_err()); + assert!( + state + .body(HttpResponseBodyUnit { + sequence, + end_of_stream, + payload: payload.map(http_response_body_unit::Payload::Data) + }) + .is_err() + ); + } } #[tokio::test] @@ -737,4 +1007,11 @@ mod tests { assert_eq!(parsed.mode, Mode::Redact); assert_eq!(parsed.replacement, DEFAULT_REPLACEMENT); } + + #[test] + fn example_policy_is_valid() { + let policy = openshell_policy::parse_sandbox_policy(include_str!("../policy.yaml")) + .expect("example policy must parse"); + openshell_policy::validate_sandbox_policy(&policy).expect("example policy must be valid"); + } } diff --git a/examples/supervisor-middleware-content-guard/upstream.py b/examples/supervisor-middleware-content-guard/upstream.py new file mode 100644 index 0000000000..85a85396cf --- /dev/null +++ b/examples/supervisor-middleware-content-guard/upstream.py @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + bodies = { + "/clean": b"ordinary public text", + "/sensitive": b"contains prototype-secret and internal-only", + } + body = bodies.get(self.path, b"not found") + self.send_response(200 if self.path in bodies else 404) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +with ThreadingHTTPServer(("0.0.0.0", 18081), Handler) as server: + print("content guard upstream listening on 0.0.0.0:18081", flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + pass diff --git a/flake.nix b/flake.nix index 7590c75918..77f1d2c3b3 100644 --- a/flake.nix +++ b/flake.nix @@ -167,6 +167,7 @@ // { packages = commonDevShell.packages ++ [ pkgs.ansible + pkgs.skopeo pkgs.sshpass testMachines.package ]; diff --git a/install.sh b/install.sh index faa10c3e3b..7f86736148 100755 --- a/install.sh +++ b/install.sh @@ -583,6 +583,10 @@ find_rpm_asset() { _dev_name="openshell-gateway-dev-${_arch}.rpm" _fallback_re="^openshell-gateway-[0-9].*\\.${_arch}\\.rpm$" ;; + openshell-prover) + _dev_name="openshell-prover-dev-${_arch}.rpm" + _fallback_re="^openshell-prover-[0-9].*\\.${_arch}\\.rpm$" + ;; *) error "unknown RPM package selector: ${_package}" ;; @@ -944,9 +948,14 @@ install_linux_rpm() { error "no openshell-gateway RPM package found for architecture: ${_arch}" fi - info "selected ${_rpm_file} and ${_gateway_rpm_file}" + _prover_rpm_file="$(find_rpm_asset "${_tmpdir}/${CHECKSUMS_NAME}" "$_arch" openshell-prover)" + if [ -z "$_prover_rpm_file" ]; then + error "no openshell-prover RPM package found for architecture: ${_arch}" + fi + + info "selected ${_rpm_file}, ${_gateway_rpm_file}, and ${_prover_rpm_file}" - for _package_file in "$_rpm_file" "$_gateway_rpm_file"; do + for _package_file in "$_rpm_file" "$_gateway_rpm_file" "$_prover_rpm_file"; do _package_url="${GITHUB_URL}/releases/download/${RELEASE_TAG}/${_package_file}" _package_path="${_tmpdir}/${_package_file}" @@ -960,8 +969,11 @@ install_linux_rpm() { verify_checksum "$_package_path" "${_tmpdir}/${CHECKSUMS_NAME}" "$_package_file" done - info "installing ${_rpm_file} and ${_gateway_rpm_file}..." - install_rpm_packages "${_tmpdir}/${_rpm_file}" "${_tmpdir}/${_gateway_rpm_file}" + info "installing ${_rpm_file}, ${_gateway_rpm_file}, and ${_prover_rpm_file}..." + install_rpm_packages \ + "${_tmpdir}/${_rpm_file}" \ + "${_tmpdir}/${_gateway_rpm_file}" \ + "${_tmpdir}/${_prover_rpm_file}" info "installed ${APP_NAME} RPM packages from ${RELEASE_TAG}" start_user_gateway } diff --git a/openshell.spec b/openshell.spec index ce35f73791..ee9d7d5f5a 100644 --- a/openshell.spec +++ b/openshell.spec @@ -58,6 +58,14 @@ lifecycle management. This package installs Podman-oriented defaults in gateway TOML while leaving compute driver selection to gateway auto-detection or explicit operator configuration. +# --- Standalone policy prover sub-package --- +%package prover +Summary: Standalone OpenShell policy boundary prover + +%description prover +OpenShell policy prover for checking whether a local candidate policy stays +within an operator-supplied maximum without connecting to a gateway. + # --- Python SDK sub-package --- %package -n python3-%{name} Summary: OpenShell Python SDK for agent execution and management @@ -87,6 +95,7 @@ grep -q 'version = "%{openshell_cargo_version}"' Cargo.toml || (echo "ERROR: Car %build test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell" test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-gateway" +test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-prover" # Generate vendored crate manifest and license metadata. # cargo-vendor.txt is consumed by an RPM generator (from cargo-rpm-macros) @@ -103,6 +112,9 @@ pandoc -s -t man deploy/man/openshell-gateway.8.md -o openshell-gateway.8 # --- CLI binary --- install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}" %{buildroot}%{_bindir}/%{name} +# --- Standalone policy prover --- +install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-prover" %{buildroot}%{_bindir}/%{name}-prover + # --- Gateway binary --- install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-gateway" %{buildroot}%{_bindir}/%{name}-gateway @@ -209,6 +221,9 @@ touch %{buildroot}%{python3_sitelib}/%{name}-%{openshell_python_version}.dist-in # Smoke-test the CLI binary %{buildroot}%{_bindir}/%{name} --version +# Smoke-test the standalone policy prover +%{buildroot}%{_bindir}/%{name}-prover --version + # Smoke-test the gateway binary %{buildroot}%{_bindir}/%{name}-gateway --version @@ -246,6 +261,12 @@ grep -q 'gateway.toml.default.v1' %{buildroot}%{_userunitdir}/%{name}-gateway.se %{_bindir}/%{name} %{_mandir}/man1/openshell.1* +%files prover +%license LICENSE +%license LICENSE.dependencies +%license cargo-vendor.txt +%{_bindir}/%{name}-prover + %files gateway %license LICENSE %license LICENSE.dependencies diff --git a/proto/openshell.proto b/proto/openshell.proto index a349e1db8a..77bc32496b 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -158,6 +158,16 @@ service OpenShell { }; } + // Inspect the installed authority for one sandbox provider mutation. + rpc GetSandboxProviderStatus(GetSandboxProviderStatusRequest) + returns (GetSandboxProviderStatusResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:read" + workspace_role: "user" + }; + } + // Delete a sandbox by name. rpc DeleteSandbox(DeleteSandboxRequest) returns (DeleteSandboxResponse) { option (openshell.options.v1.authorization) = { @@ -484,6 +494,15 @@ service OpenShell { }; } + // Report installed provider state for the current ConnectSupervisor session. + // Replacing or losing that session invalidates its observations. + rpc ReportProviderReadiness(ReportProviderReadinessRequest) + returns (ReportProviderReadinessResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "sandbox" + }; + } + // Get provider environment for a sandbox (called by sandbox supervisor at startup). rpc GetSandboxProviderEnvironment(GetSandboxProviderEnvironmentRequest) returns (GetSandboxProviderEnvironmentResponse) { @@ -953,6 +972,9 @@ message SandboxSpec { repeated string command = 12; // Allocate a retained pseudo-terminal for the main process. bool tty = 13; + // Gateway-owned attachment identity, changed atomically with the provider set. + // Equality only: detach and reattach must not revive an older receipt. + string provider_attachment_epoch = 14; } message ResourceRequirements { @@ -1161,6 +1183,9 @@ message CreateSandboxRequest { string workload_template_name = 7; // Explicit workspace for the sandbox. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 8; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 9; } message CreateSandboxTemplateRequest { @@ -1169,6 +1194,9 @@ message CreateSandboxTemplateRequest { SandboxWorkloadTemplate template = 1; // Explicit workspace for the template. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 4; } message GetSandboxTemplateRequest { @@ -1203,6 +1231,8 @@ message DeleteSandboxTemplateRequest { // Succeed with ALREADY_ABSENT if the target is missing. Authorization and // parent-workspace checks still apply. bool allow_missing = 4; + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + string request_id = 5; } message SandboxTemplateResponse { @@ -1303,6 +1333,9 @@ message AttachSandboxProviderRequest { uint64 expected_resource_version = 3; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 6; } // Detach provider from sandbox request. @@ -1320,6 +1353,9 @@ message DetachSandboxProviderRequest { uint64 expected_resource_version = 3; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 6; } // Delete sandbox request. @@ -1333,6 +1369,9 @@ message DeleteSandboxRequest { // Succeed with ALREADY_ABSENT if the target is missing. Does not wait for // asynchronous cleanup and does not suppress authorization or parent errors. bool allow_missing = 4; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 5; } // Stop sandbox request. @@ -1343,6 +1382,9 @@ message StopSandboxRequest { string name = 1; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 4; } // Start sandbox request. @@ -1353,6 +1395,9 @@ message StartSandboxRequest { string name = 1; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 4; } // Sandbox response. @@ -1377,6 +1422,8 @@ message AttachSandboxProviderResponse { Sandbox sandbox = 1; // True when the provider was newly attached. False means it was already attached. bool attached = 2; + // Persisted intent; readiness requires current supervisor observations. + ProviderMutationReceipt receipt = 3; } // Detach provider from sandbox response. @@ -1384,6 +1431,215 @@ message DetachSandboxProviderResponse { Sandbox sandbox = 1; // True when the provider was removed. False means it was not attached. bool detached = 2; + // Revocation is complete only when this receipt reports REVOKED. + ProviderMutationReceipt receipt = 3; +} + +// Operation whose installed authority is tracked by a receipt. +enum ProviderMutationKind { + PROVIDER_MUTATION_KIND_UNSPECIFIED = 0; + PROVIDER_MUTATION_KIND_ATTACH = 1; + PROVIDER_MUTATION_KIND_DETACH = 2; + PROVIDER_MUTATION_KIND_UPDATE = 3; + // Reconstructed status for existing desired state without a mutation receipt. + PROVIDER_MUTATION_KIND_OBSERVE = 4; +} + +// Readiness states describe persisted intent separately from installed state. +enum ProviderReadinessState { + PROVIDER_READINESS_STATE_UNSPECIFIED = 0; + PROVIDER_READINESS_STATE_PERSISTED = 1; + PROVIDER_READINESS_STATE_PENDING = 2; + PROVIDER_READINESS_STATE_READY = 3; + PROVIDER_READINESS_STATE_WITHHELD = 4; + PROVIDER_READINESS_STATE_REVOKED = 5; + PROVIDER_READINESS_STATE_FAILED = 6; + PROVIDER_READINESS_STATE_SUPERSEDED = 7; +} + +// Closed reason categories are safe to display. Raw installation errors are +// never part of the readiness protocol. +enum ProviderReadinessReason { + PROVIDER_READINESS_REASON_UNSPECIFIED = 0; + PROVIDER_READINESS_REASON_WAITING_FOR_SUPERVISOR = 1; + PROVIDER_READINESS_REASON_WAITING_FOR_CREDENTIALS = 2; + PROVIDER_READINESS_REASON_WAITING_FOR_POLICY = 3; + PROVIDER_READINESS_REASON_WAITING_FOR_PROCESS = 4; + PROVIDER_READINESS_REASON_UNSUPPORTED_SUPERVISOR = 5; + PROVIDER_READINESS_REASON_CREDENTIALS_WITHHELD = 6; + PROVIDER_READINESS_REASON_CREDENTIAL_INSTALL_FAILED = 7; + PROVIDER_READINESS_REASON_POLICY_ACTIVATION_FAILED = 8; + PROVIDER_READINESS_REASON_PROCESS_INSTALL_FAILED = 9; + PROVIDER_READINESS_REASON_SUPERVISOR_DISCONNECTED = 10; + PROVIDER_READINESS_REASON_SUPERVISOR_LEASE_EXPIRED = 11; + PROVIDER_READINESS_REASON_DESIRED_STATE_CHANGED = 12; + PROVIDER_READINESS_REASON_CREDENTIAL_EXPIRED = 13; + PROVIDER_READINESS_REASON_LOCAL_POLICY = 14; + PROVIDER_READINESS_REASON_SNAPSHOT_MISMATCH = 15; +} + +// Exact desired authority. Revisions are opaque identities, never ordered. +message ProviderDesiredIdentity { + string sandbox_id = 1; + string sandbox_name = 2; + string attachment_epoch = 3; + // Empty for a detached provider. + string provider_id = 4; + uint64 provider_resource_version = 5; + uint64 provider_env_revision = 6; + uint64 config_revision = 7; + string policy_hash = 8; +} + +// Component whose desired state is tracked by a durable update operation. +enum ConfigComponent { + CONFIG_COMPONENT_UNSPECIFIED = 0; + CONFIG_COMPONENT_SANDBOX_CONFIG = 1; + CONFIG_COMPONENT_PROVIDER_ENVIRONMENT = 2; +} + +// Identifies one component snapshot revision. Revisions are equality tokens, +// not members of one shared ordering domain. +message ConfigSnapshotRevision { + oneof component { + SandboxConfigRevision sandbox_config = 1; + uint64 provider_environment = 2; + // Complete desired authority for one sandbox-scoped provider mutation. + ProviderDesiredIdentity provider_target = 3; + } +} + +// Identity needed to correlate effective sandbox configuration with the +// policy-history row whose apply status the gateway records. +message SandboxConfigRevision { + uint64 config_revision = 1; + uint32 policy_version = 2; + openshell.sandbox.v1.PolicySource policy_source = 3; + uint32 global_policy_version = 4; + // Monotonic revision of the sandbox-scoped settings row. This disambiguates + // setting operations whose effective config fingerprint is equality-only. + uint64 settings_revision = 5; +} + +// Result of applying a component revision at its owning runtime boundary. +enum ConfigApplyOutcome { + CONFIG_APPLY_OUTCOME_UNSPECIFIED = 0; + CONFIG_APPLY_OUTCOME_APPLIED = 1; + CONFIG_APPLY_OUTCOME_IGNORED_DUPLICATE = 2; + CONFIG_APPLY_OUTCOME_IGNORED_STALE = 3; + CONFIG_APPLY_OUTCOME_RETAINED_LOCAL_OVERRIDE = 4; + CONFIG_APPLY_OUTCOME_DEGRADED = 5; + CONFIG_APPLY_OUTCOME_FAILED_RETAINED_LAST_KNOWN_GOOD = 6; + CONFIG_APPLY_OUTCOME_FAILED_CLOSED = 7; + CONFIG_APPLY_OUTCOME_UNSUPPORTED = 8; +} + +// Durable lifecycle of one desired-state update operation. +enum ConfigUpdateOperationState { + CONFIG_UPDATE_OPERATION_STATE_UNSPECIFIED = 0; + CONFIG_UPDATE_OPERATION_STATE_PENDING = 1; + CONFIG_UPDATE_OPERATION_STATE_APPLIED = 2; + CONFIG_UPDATE_OPERATION_STATE_INACTIVE = 3; + CONFIG_UPDATE_OPERATION_STATE_FAILED = 4; + CONFIG_UPDATE_OPERATION_STATE_SUPERSEDED = 5; + CONFIG_UPDATE_OPERATION_STATE_CANCELLED = 6; +} + +// Durable progress for one sandbox-scoped desired-state mutation. Snapshot +// contents and credentials are never stored in this resource. +message ConfigUpdateOperation { + string operation_id = 1; + string sandbox_id = 2; + ConfigComponent component = 3; + ConfigSnapshotRevision target_revision = 4; + ConfigUpdateOperationState state = 5; + ConfigApplyOutcome outcome = 6; + string sanitized_error = 7; + reserved 8, 9, 10; + reserved "created_at_ms", "updated_at_ms", "completed_at_ms"; + google.protobuf.Timestamp created_time = 108; + google.protobuf.Timestamp updated_time = 109; + // Absent until the operation reaches a terminal state. + google.protobuf.Timestamp completed_time = 110; +} + +// Immutable, secret-free record of one sandbox's intended provider mutation. +message ProviderMutationReceipt { + string receipt_id = 1; + // Shared by all sandbox receipts from one provider update. + string mutation_id = 2; + string provider_name = 3; + string workspace = 4; + ProviderMutationKind kind = 5; + ProviderDesiredIdentity desired = 6; + reserved 7; + reserved "persisted_at_ms"; + google.protobuf.Timestamp persisted_time = 107; +} + +// Installed state reported by the current supervisor. Process installation is +// acknowledged by the authenticated sandbox boundary after replacing its +// environment for future process launches. +message ProviderReadinessObservation { + // Gateway-issued identifier from the current ConnectSupervisor response. + string session_id = 1; + // Monotonic only within this connection; unrelated to revision fingerprints. + uint64 sequence = 2; + string attachment_epoch = 3; + uint64 provider_env_revision = 4; + uint64 config_revision = 5; + string policy_hash = 6; + bool credentials_installed = 7; + bool policy_active = 8; + bool launch_environment_installed = 9; + string process_instance_id = 10; + ProviderReadinessReason reason = 11; +} + +// Operator view of desired and observed state; contains no credential material. +message ProviderReadinessStatus { + ProviderMutationReceipt receipt = 1; + ProviderReadinessState state = 2; + ProviderReadinessReason reason = 3; + ProviderReadinessObservation observed = 4; + string network_instance_id = 5; + reserved 6, 7; + reserved "observed_at_ms", "evaluated_at_ms"; + // Absent until the current supervisor session supplies accepted evidence. + google.protobuf.Timestamp observed_time = 106; + google.protobuf.Timestamp evaluated_time = 107; + // Durable operation for the receipt, including its terminal apply outcome. + ConfigUpdateOperation operation = 8; +} + +// Query an immutable receipt, or reconstruct the current desired state when +// receipt_id is empty. The sandbox identity must match the receipt. +message GetSandboxProviderStatusRequest { + string sandbox_name = 1; + string provider_name = 2; + string receipt_id = 3; + openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; +} + +message GetSandboxProviderStatusResponse { + ProviderReadinessStatus status = 1; +} + +// Installation evidence from the authenticated supervisor for this sandbox. +// A caller-provided instance identifier alone never establishes authority. +message ReportProviderReadinessRequest { + string sandbox_id = 1; + ProviderReadinessObservation observation = 2; +} + +// Acknowledges accepted evidence without granting a separate session authority. +// Identical retries do not extend the evidence's original acceptance time. +message ReportProviderReadinessResponse { + uint64 accepted_sequence = 1; + reserved 2, 3; + reserved "report_interval_seconds", "observation_ttl_seconds"; + google.protobuf.Duration report_interval = 102; + google.protobuf.Duration observation_ttl = 103; } // Delete sandbox response. @@ -1452,6 +1708,9 @@ message ExposeServiceRequest { bool domain = 4; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 6; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 7; } // Request to fetch an exposed sandbox service endpoint. @@ -1500,6 +1759,9 @@ message DeleteServiceRequest { // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; bool allow_missing = 5; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 6; } // Response for deleting an exposed sandbox service endpoint. @@ -1753,6 +2015,9 @@ message CreateProviderRequest { openshell.datamodel.v1.Provider provider = 1; // Explicit workspace for the provider. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 4; } // Get provider request. @@ -1793,6 +2058,9 @@ message UpdateProviderRequest { repeated string clear_credential_expiration_keys = 103; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 5; } // Delete provider request. @@ -1803,11 +2071,19 @@ message DeleteProviderRequest { // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; bool allow_missing = 4; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 5; } // Provider response. message ProviderResponse { openshell.datamodel.v1.Provider provider = 1; + // Selection-time sandbox target set for an update, with one receipt per target. + // Sandboxes attached later are outside this operation's readiness result. + repeated ProviderMutationReceipt target_receipts = 2; + // Identifies the update even when its target set is empty. + string mutation_id = 3; } // List providers response. @@ -2044,6 +2320,9 @@ message ConfigureProviderRefreshRequest { google.protobuf.Timestamp expiration_time = 106; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 8; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 9; } message ConfigureProviderRefreshResponse { @@ -2057,6 +2336,9 @@ message RotateProviderCredentialRequest { string credential_key = 2; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 5; } message RotateProviderCredentialResponse { @@ -2071,6 +2353,9 @@ message DeleteProviderRefreshRequest { // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; bool allow_missing = 5; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 6; } message DeleteProviderRefreshResponse { @@ -2134,6 +2419,9 @@ message ImportProviderProfilesRequest { // Workspace scope. When set, profiles are workspace-scoped (Workspace Admin). // When empty, profiles are platform-scoped (Platform Admin). string workspace = 2; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 3; } // Import custom provider profiles response. @@ -2156,6 +2444,9 @@ message UpdateProviderProfilesRequest { // Workspace scope. When set, targets workspace-scoped profile. When empty, // targets platform-scoped profile. string workspace = 4; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 5; } // Update one custom provider profile response. @@ -2193,6 +2484,9 @@ message DeleteProviderProfileRequest { // targets platform-scoped profile. string workspace = 2; bool allow_missing = 3; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 4; } // Delete custom provider profile response. @@ -2256,6 +2550,12 @@ message GetSandboxProviderEnvironmentResponse { // Environment variables that contain provider configuration rather than // credentials and therefore do not require endpoint-scoped resolution. repeated string non_secret_environment_keys = 6; + // Attachment identity captured with the returned provider records. + string provider_attachment_epoch = 7; + // Effective policy identity used to derive this snapshot's endpoint bindings. + string policy_hash = 8; + // Nonzero when material was withheld; installing an empty map is not readiness. + ProviderReadinessReason readiness_reason = 9; } message ExchangeProviderSubjectTokenRequest { @@ -2328,6 +2628,9 @@ message UpdateConfigRequest { // Explicit workspace scope for sandbox-scoped updates. Omit only when // `global` is true; the all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 11; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 12; } message PolicyMergeOperation { @@ -2569,6 +2872,8 @@ message SupervisorHello { string sandbox_id = 1; // Supervisor instance ID (e.g. boot id or process epoch). string instance_id = 2; + // The supervisor can report credential, policy, and launch-environment installation. + bool supports_provider_readiness = 4; } // Gateway accepts the supervisor session. @@ -2911,6 +3216,9 @@ message ApproveDraftChunkRequest { string review_token = 4; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 6; } message ApproveDraftChunkResponse { @@ -2932,6 +3240,9 @@ message RejectDraftChunkRequest { string reason = 3; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 6; } message RejectDraftChunkResponse {} @@ -2954,6 +3265,9 @@ message ApproveAllDraftChunksRequest { repeated DraftChunkApproval approvals = 4; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 6; } message ApproveAllDraftChunksResponse { @@ -2980,6 +3294,9 @@ message EditDraftChunkRequest { openshell.sandbox.v1.NetworkPolicyRule proposed_rule = 3; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 5; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 6; } message EditDraftChunkResponse {} @@ -2994,6 +3311,9 @@ message UndoDraftChunkRequest { string chunk_id = 2; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 4; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 5; } message UndoDraftChunkResponse { @@ -3011,6 +3331,9 @@ message ClearDraftChunksRequest { string name = 1; // Explicit workspace scope. The all-workspaces selection is invalid. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + string request_id = 4; } message ClearDraftChunksResponse { @@ -3057,6 +3380,8 @@ message CreateWorkspaceRequest { string name = 1; // Optional labels for the workspace (key-value metadata). map labels = 2; + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + string request_id = 3; } // Create workspace response. @@ -3099,6 +3424,8 @@ message DeleteWorkspaceRequest { // Workspace name (canonical lookup key). string name = 1; bool allow_missing = 2; + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + string request_id = 3; } // Delete workspace response. @@ -3148,6 +3475,8 @@ message AddWorkspaceMemberRequest { string principal_subject = 2; // Role to assign. WorkspaceRole role = 3; + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + string request_id = 4; } // Add workspace member response. @@ -3162,6 +3491,8 @@ message RemoveWorkspaceMemberRequest { // OIDC subject claim identifying the principal to remove. string principal_subject = 2; bool allow_missing = 3; + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + string request_id = 4; } // Remove workspace member response. diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 600f4a750b..8b15056455 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -399,6 +399,9 @@ message GetSandboxConfigResponse { // False also covers older gateways that do not advertise this capability; // supervisors preserve their legacy unauthenticated connection behavior. bool extension_authentication_enabled = 12; + // Gateway-owned attachment identity captured with this desired configuration. + // Compare for equality; reattachment invalidates previous installation evidence. + string provider_attachment_epoch = 14; } // Connection details for one operator-registered supervisor middleware service. diff --git a/python/openshell/release_formula_test.py b/python/openshell/release_formula_test.py index 6848097451..671577d708 100644 --- a/python/openshell/release_formula_test.py +++ b/python/openshell/release_formula_test.py @@ -29,6 +29,10 @@ def test_generate_homebrew_formula_uses_tagged_macos_driver_asset_without_defaul "d" * 64 + " openshell-gateway-aarch64-apple-darwin.tar.gz\n", encoding="utf-8", ) + (release_dir / "openshell-prover-checksums-sha256.txt").write_text( + "e" * 64 + " openshell-prover-aarch64-apple-darwin.tar.gz\n", + encoding="utf-8", + ) repo_root = Path(__file__).resolve().parents[2] output = tmp_path / "openshell.rb" @@ -53,6 +57,14 @@ def test_generate_homebrew_formula_uses_tagged_macos_driver_asset_without_defaul "v0.0.10/openshell-driver-vm-aarch64-apple-darwin.tar.gz" ) in formula assert 'sha256 "' + "b" * 64 + '"' in formula + assert ( + "https://github.com/NVIDIA/OpenShell/releases/download/" + "v0.0.10/openshell-prover-aarch64-apple-darwin.tar.gz" + ) in formula + assert 'sha256 "' + "e" * 64 + '"' in formula + assert 'resource("openshell-prover").stage' in formula + assert 'bin.install "openshell-prover"' in formula + assert "#{bin}/openshell-prover --version" in formula assert "OPENSHELL_COMPUTE_DRIVER: " not in formula assert 'OPENSHELL_GATEWAY_CONFIG: "#{var}/openshell/gateway.toml"' not in formula assert "init-gateway-config.sh" not in formula diff --git a/sdk/go/openshell/v1/internal/converter/coverage_test.go b/sdk/go/openshell/v1/internal/converter/coverage_test.go index 77d8f72ea6..4777942a02 100644 --- a/sdk/go/openshell/v1/internal/converter/coverage_test.go +++ b/sdk/go/openshell/v1/internal/converter/coverage_test.go @@ -33,7 +33,12 @@ func TestConverterCoversAllProtoFields_SandboxSpec(t *testing.T) { "tty": true, } - assertAllFieldsCovered(t, (&pb.SandboxSpec{}).ProtoReflect().Descriptor(), handled, nil) + // The gateway owns this identity. Provider status exposes it through the + // raw API; callers must not supply it when constructing a sandbox spec. + skipped := fieldSet{ + "provider_attachment_epoch": true, + } + assertAllFieldsCovered(t, (&pb.SandboxSpec{}).ProtoReflect().Descriptor(), handled, skipped) } func TestConverterCoversAllProtoFields_SandboxTemplate(t *testing.T) { diff --git a/sdk/go/proto/openshellv1/openshell.pb.go b/sdk/go/proto/openshellv1/openshell.pb.go index 935ceaac47..c7cdc8e850 100644 --- a/sdk/go/proto/openshellv1/openshell.pb.go +++ b/sdk/go/proto/openshellv1/openshell.pb.go @@ -105,6 +105,398 @@ func (SandboxPhase) EnumDescriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{0} } +// Operation whose installed authority is tracked by a receipt. +type ProviderMutationKind int32 + +const ( + ProviderMutationKind_PROVIDER_MUTATION_KIND_UNSPECIFIED ProviderMutationKind = 0 + ProviderMutationKind_PROVIDER_MUTATION_KIND_ATTACH ProviderMutationKind = 1 + ProviderMutationKind_PROVIDER_MUTATION_KIND_DETACH ProviderMutationKind = 2 + ProviderMutationKind_PROVIDER_MUTATION_KIND_UPDATE ProviderMutationKind = 3 + // Reconstructed status for existing desired state without a mutation receipt. + ProviderMutationKind_PROVIDER_MUTATION_KIND_OBSERVE ProviderMutationKind = 4 +) + +// Enum value maps for ProviderMutationKind. +var ( + ProviderMutationKind_name = map[int32]string{ + 0: "PROVIDER_MUTATION_KIND_UNSPECIFIED", + 1: "PROVIDER_MUTATION_KIND_ATTACH", + 2: "PROVIDER_MUTATION_KIND_DETACH", + 3: "PROVIDER_MUTATION_KIND_UPDATE", + 4: "PROVIDER_MUTATION_KIND_OBSERVE", + } + ProviderMutationKind_value = map[string]int32{ + "PROVIDER_MUTATION_KIND_UNSPECIFIED": 0, + "PROVIDER_MUTATION_KIND_ATTACH": 1, + "PROVIDER_MUTATION_KIND_DETACH": 2, + "PROVIDER_MUTATION_KIND_UPDATE": 3, + "PROVIDER_MUTATION_KIND_OBSERVE": 4, + } +) + +func (x ProviderMutationKind) Enum() *ProviderMutationKind { + p := new(ProviderMutationKind) + *p = x + return p +} + +func (x ProviderMutationKind) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ProviderMutationKind) Descriptor() protoreflect.EnumDescriptor { + return file_openshell_proto_enumTypes[1].Descriptor() +} + +func (ProviderMutationKind) Type() protoreflect.EnumType { + return &file_openshell_proto_enumTypes[1] +} + +func (x ProviderMutationKind) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ProviderMutationKind.Descriptor instead. +func (ProviderMutationKind) EnumDescriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{1} +} + +// Readiness states describe persisted intent separately from installed state. +type ProviderReadinessState int32 + +const ( + ProviderReadinessState_PROVIDER_READINESS_STATE_UNSPECIFIED ProviderReadinessState = 0 + ProviderReadinessState_PROVIDER_READINESS_STATE_PERSISTED ProviderReadinessState = 1 + ProviderReadinessState_PROVIDER_READINESS_STATE_PENDING ProviderReadinessState = 2 + ProviderReadinessState_PROVIDER_READINESS_STATE_READY ProviderReadinessState = 3 + ProviderReadinessState_PROVIDER_READINESS_STATE_WITHHELD ProviderReadinessState = 4 + ProviderReadinessState_PROVIDER_READINESS_STATE_REVOKED ProviderReadinessState = 5 + ProviderReadinessState_PROVIDER_READINESS_STATE_FAILED ProviderReadinessState = 6 + ProviderReadinessState_PROVIDER_READINESS_STATE_SUPERSEDED ProviderReadinessState = 7 +) + +// Enum value maps for ProviderReadinessState. +var ( + ProviderReadinessState_name = map[int32]string{ + 0: "PROVIDER_READINESS_STATE_UNSPECIFIED", + 1: "PROVIDER_READINESS_STATE_PERSISTED", + 2: "PROVIDER_READINESS_STATE_PENDING", + 3: "PROVIDER_READINESS_STATE_READY", + 4: "PROVIDER_READINESS_STATE_WITHHELD", + 5: "PROVIDER_READINESS_STATE_REVOKED", + 6: "PROVIDER_READINESS_STATE_FAILED", + 7: "PROVIDER_READINESS_STATE_SUPERSEDED", + } + ProviderReadinessState_value = map[string]int32{ + "PROVIDER_READINESS_STATE_UNSPECIFIED": 0, + "PROVIDER_READINESS_STATE_PERSISTED": 1, + "PROVIDER_READINESS_STATE_PENDING": 2, + "PROVIDER_READINESS_STATE_READY": 3, + "PROVIDER_READINESS_STATE_WITHHELD": 4, + "PROVIDER_READINESS_STATE_REVOKED": 5, + "PROVIDER_READINESS_STATE_FAILED": 6, + "PROVIDER_READINESS_STATE_SUPERSEDED": 7, + } +) + +func (x ProviderReadinessState) Enum() *ProviderReadinessState { + p := new(ProviderReadinessState) + *p = x + return p +} + +func (x ProviderReadinessState) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ProviderReadinessState) Descriptor() protoreflect.EnumDescriptor { + return file_openshell_proto_enumTypes[2].Descriptor() +} + +func (ProviderReadinessState) Type() protoreflect.EnumType { + return &file_openshell_proto_enumTypes[2] +} + +func (x ProviderReadinessState) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ProviderReadinessState.Descriptor instead. +func (ProviderReadinessState) EnumDescriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{2} +} + +// Closed reason categories are safe to display. Raw installation errors are +// never part of the readiness protocol. +type ProviderReadinessReason int32 + +const ( + ProviderReadinessReason_PROVIDER_READINESS_REASON_UNSPECIFIED ProviderReadinessReason = 0 + ProviderReadinessReason_PROVIDER_READINESS_REASON_WAITING_FOR_SUPERVISOR ProviderReadinessReason = 1 + ProviderReadinessReason_PROVIDER_READINESS_REASON_WAITING_FOR_CREDENTIALS ProviderReadinessReason = 2 + ProviderReadinessReason_PROVIDER_READINESS_REASON_WAITING_FOR_POLICY ProviderReadinessReason = 3 + ProviderReadinessReason_PROVIDER_READINESS_REASON_WAITING_FOR_PROCESS ProviderReadinessReason = 4 + ProviderReadinessReason_PROVIDER_READINESS_REASON_UNSUPPORTED_SUPERVISOR ProviderReadinessReason = 5 + ProviderReadinessReason_PROVIDER_READINESS_REASON_CREDENTIALS_WITHHELD ProviderReadinessReason = 6 + ProviderReadinessReason_PROVIDER_READINESS_REASON_CREDENTIAL_INSTALL_FAILED ProviderReadinessReason = 7 + ProviderReadinessReason_PROVIDER_READINESS_REASON_POLICY_ACTIVATION_FAILED ProviderReadinessReason = 8 + ProviderReadinessReason_PROVIDER_READINESS_REASON_PROCESS_INSTALL_FAILED ProviderReadinessReason = 9 + ProviderReadinessReason_PROVIDER_READINESS_REASON_SUPERVISOR_DISCONNECTED ProviderReadinessReason = 10 + ProviderReadinessReason_PROVIDER_READINESS_REASON_SUPERVISOR_LEASE_EXPIRED ProviderReadinessReason = 11 + ProviderReadinessReason_PROVIDER_READINESS_REASON_DESIRED_STATE_CHANGED ProviderReadinessReason = 12 + ProviderReadinessReason_PROVIDER_READINESS_REASON_CREDENTIAL_EXPIRED ProviderReadinessReason = 13 + ProviderReadinessReason_PROVIDER_READINESS_REASON_LOCAL_POLICY ProviderReadinessReason = 14 + ProviderReadinessReason_PROVIDER_READINESS_REASON_SNAPSHOT_MISMATCH ProviderReadinessReason = 15 +) + +// Enum value maps for ProviderReadinessReason. +var ( + ProviderReadinessReason_name = map[int32]string{ + 0: "PROVIDER_READINESS_REASON_UNSPECIFIED", + 1: "PROVIDER_READINESS_REASON_WAITING_FOR_SUPERVISOR", + 2: "PROVIDER_READINESS_REASON_WAITING_FOR_CREDENTIALS", + 3: "PROVIDER_READINESS_REASON_WAITING_FOR_POLICY", + 4: "PROVIDER_READINESS_REASON_WAITING_FOR_PROCESS", + 5: "PROVIDER_READINESS_REASON_UNSUPPORTED_SUPERVISOR", + 6: "PROVIDER_READINESS_REASON_CREDENTIALS_WITHHELD", + 7: "PROVIDER_READINESS_REASON_CREDENTIAL_INSTALL_FAILED", + 8: "PROVIDER_READINESS_REASON_POLICY_ACTIVATION_FAILED", + 9: "PROVIDER_READINESS_REASON_PROCESS_INSTALL_FAILED", + 10: "PROVIDER_READINESS_REASON_SUPERVISOR_DISCONNECTED", + 11: "PROVIDER_READINESS_REASON_SUPERVISOR_LEASE_EXPIRED", + 12: "PROVIDER_READINESS_REASON_DESIRED_STATE_CHANGED", + 13: "PROVIDER_READINESS_REASON_CREDENTIAL_EXPIRED", + 14: "PROVIDER_READINESS_REASON_LOCAL_POLICY", + 15: "PROVIDER_READINESS_REASON_SNAPSHOT_MISMATCH", + } + ProviderReadinessReason_value = map[string]int32{ + "PROVIDER_READINESS_REASON_UNSPECIFIED": 0, + "PROVIDER_READINESS_REASON_WAITING_FOR_SUPERVISOR": 1, + "PROVIDER_READINESS_REASON_WAITING_FOR_CREDENTIALS": 2, + "PROVIDER_READINESS_REASON_WAITING_FOR_POLICY": 3, + "PROVIDER_READINESS_REASON_WAITING_FOR_PROCESS": 4, + "PROVIDER_READINESS_REASON_UNSUPPORTED_SUPERVISOR": 5, + "PROVIDER_READINESS_REASON_CREDENTIALS_WITHHELD": 6, + "PROVIDER_READINESS_REASON_CREDENTIAL_INSTALL_FAILED": 7, + "PROVIDER_READINESS_REASON_POLICY_ACTIVATION_FAILED": 8, + "PROVIDER_READINESS_REASON_PROCESS_INSTALL_FAILED": 9, + "PROVIDER_READINESS_REASON_SUPERVISOR_DISCONNECTED": 10, + "PROVIDER_READINESS_REASON_SUPERVISOR_LEASE_EXPIRED": 11, + "PROVIDER_READINESS_REASON_DESIRED_STATE_CHANGED": 12, + "PROVIDER_READINESS_REASON_CREDENTIAL_EXPIRED": 13, + "PROVIDER_READINESS_REASON_LOCAL_POLICY": 14, + "PROVIDER_READINESS_REASON_SNAPSHOT_MISMATCH": 15, + } +) + +func (x ProviderReadinessReason) Enum() *ProviderReadinessReason { + p := new(ProviderReadinessReason) + *p = x + return p +} + +func (x ProviderReadinessReason) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ProviderReadinessReason) Descriptor() protoreflect.EnumDescriptor { + return file_openshell_proto_enumTypes[3].Descriptor() +} + +func (ProviderReadinessReason) Type() protoreflect.EnumType { + return &file_openshell_proto_enumTypes[3] +} + +func (x ProviderReadinessReason) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ProviderReadinessReason.Descriptor instead. +func (ProviderReadinessReason) EnumDescriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{3} +} + +// Component whose desired state is tracked by a durable update operation. +type ConfigComponent int32 + +const ( + ConfigComponent_CONFIG_COMPONENT_UNSPECIFIED ConfigComponent = 0 + ConfigComponent_CONFIG_COMPONENT_SANDBOX_CONFIG ConfigComponent = 1 + ConfigComponent_CONFIG_COMPONENT_PROVIDER_ENVIRONMENT ConfigComponent = 2 +) + +// Enum value maps for ConfigComponent. +var ( + ConfigComponent_name = map[int32]string{ + 0: "CONFIG_COMPONENT_UNSPECIFIED", + 1: "CONFIG_COMPONENT_SANDBOX_CONFIG", + 2: "CONFIG_COMPONENT_PROVIDER_ENVIRONMENT", + } + ConfigComponent_value = map[string]int32{ + "CONFIG_COMPONENT_UNSPECIFIED": 0, + "CONFIG_COMPONENT_SANDBOX_CONFIG": 1, + "CONFIG_COMPONENT_PROVIDER_ENVIRONMENT": 2, + } +) + +func (x ConfigComponent) Enum() *ConfigComponent { + p := new(ConfigComponent) + *p = x + return p +} + +func (x ConfigComponent) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ConfigComponent) Descriptor() protoreflect.EnumDescriptor { + return file_openshell_proto_enumTypes[4].Descriptor() +} + +func (ConfigComponent) Type() protoreflect.EnumType { + return &file_openshell_proto_enumTypes[4] +} + +func (x ConfigComponent) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ConfigComponent.Descriptor instead. +func (ConfigComponent) EnumDescriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{4} +} + +// Result of applying a component revision at its owning runtime boundary. +type ConfigApplyOutcome int32 + +const ( + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_UNSPECIFIED ConfigApplyOutcome = 0 + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_APPLIED ConfigApplyOutcome = 1 + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_IGNORED_DUPLICATE ConfigApplyOutcome = 2 + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_IGNORED_STALE ConfigApplyOutcome = 3 + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_RETAINED_LOCAL_OVERRIDE ConfigApplyOutcome = 4 + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_DEGRADED ConfigApplyOutcome = 5 + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_FAILED_RETAINED_LAST_KNOWN_GOOD ConfigApplyOutcome = 6 + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_FAILED_CLOSED ConfigApplyOutcome = 7 + ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_UNSUPPORTED ConfigApplyOutcome = 8 +) + +// Enum value maps for ConfigApplyOutcome. +var ( + ConfigApplyOutcome_name = map[int32]string{ + 0: "CONFIG_APPLY_OUTCOME_UNSPECIFIED", + 1: "CONFIG_APPLY_OUTCOME_APPLIED", + 2: "CONFIG_APPLY_OUTCOME_IGNORED_DUPLICATE", + 3: "CONFIG_APPLY_OUTCOME_IGNORED_STALE", + 4: "CONFIG_APPLY_OUTCOME_RETAINED_LOCAL_OVERRIDE", + 5: "CONFIG_APPLY_OUTCOME_DEGRADED", + 6: "CONFIG_APPLY_OUTCOME_FAILED_RETAINED_LAST_KNOWN_GOOD", + 7: "CONFIG_APPLY_OUTCOME_FAILED_CLOSED", + 8: "CONFIG_APPLY_OUTCOME_UNSUPPORTED", + } + ConfigApplyOutcome_value = map[string]int32{ + "CONFIG_APPLY_OUTCOME_UNSPECIFIED": 0, + "CONFIG_APPLY_OUTCOME_APPLIED": 1, + "CONFIG_APPLY_OUTCOME_IGNORED_DUPLICATE": 2, + "CONFIG_APPLY_OUTCOME_IGNORED_STALE": 3, + "CONFIG_APPLY_OUTCOME_RETAINED_LOCAL_OVERRIDE": 4, + "CONFIG_APPLY_OUTCOME_DEGRADED": 5, + "CONFIG_APPLY_OUTCOME_FAILED_RETAINED_LAST_KNOWN_GOOD": 6, + "CONFIG_APPLY_OUTCOME_FAILED_CLOSED": 7, + "CONFIG_APPLY_OUTCOME_UNSUPPORTED": 8, + } +) + +func (x ConfigApplyOutcome) Enum() *ConfigApplyOutcome { + p := new(ConfigApplyOutcome) + *p = x + return p +} + +func (x ConfigApplyOutcome) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ConfigApplyOutcome) Descriptor() protoreflect.EnumDescriptor { + return file_openshell_proto_enumTypes[5].Descriptor() +} + +func (ConfigApplyOutcome) Type() protoreflect.EnumType { + return &file_openshell_proto_enumTypes[5] +} + +func (x ConfigApplyOutcome) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ConfigApplyOutcome.Descriptor instead. +func (ConfigApplyOutcome) EnumDescriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{5} +} + +// Durable lifecycle of one desired-state update operation. +type ConfigUpdateOperationState int32 + +const ( + ConfigUpdateOperationState_CONFIG_UPDATE_OPERATION_STATE_UNSPECIFIED ConfigUpdateOperationState = 0 + ConfigUpdateOperationState_CONFIG_UPDATE_OPERATION_STATE_PENDING ConfigUpdateOperationState = 1 + ConfigUpdateOperationState_CONFIG_UPDATE_OPERATION_STATE_APPLIED ConfigUpdateOperationState = 2 + ConfigUpdateOperationState_CONFIG_UPDATE_OPERATION_STATE_INACTIVE ConfigUpdateOperationState = 3 + ConfigUpdateOperationState_CONFIG_UPDATE_OPERATION_STATE_FAILED ConfigUpdateOperationState = 4 + ConfigUpdateOperationState_CONFIG_UPDATE_OPERATION_STATE_SUPERSEDED ConfigUpdateOperationState = 5 + ConfigUpdateOperationState_CONFIG_UPDATE_OPERATION_STATE_CANCELLED ConfigUpdateOperationState = 6 +) + +// Enum value maps for ConfigUpdateOperationState. +var ( + ConfigUpdateOperationState_name = map[int32]string{ + 0: "CONFIG_UPDATE_OPERATION_STATE_UNSPECIFIED", + 1: "CONFIG_UPDATE_OPERATION_STATE_PENDING", + 2: "CONFIG_UPDATE_OPERATION_STATE_APPLIED", + 3: "CONFIG_UPDATE_OPERATION_STATE_INACTIVE", + 4: "CONFIG_UPDATE_OPERATION_STATE_FAILED", + 5: "CONFIG_UPDATE_OPERATION_STATE_SUPERSEDED", + 6: "CONFIG_UPDATE_OPERATION_STATE_CANCELLED", + } + ConfigUpdateOperationState_value = map[string]int32{ + "CONFIG_UPDATE_OPERATION_STATE_UNSPECIFIED": 0, + "CONFIG_UPDATE_OPERATION_STATE_PENDING": 1, + "CONFIG_UPDATE_OPERATION_STATE_APPLIED": 2, + "CONFIG_UPDATE_OPERATION_STATE_INACTIVE": 3, + "CONFIG_UPDATE_OPERATION_STATE_FAILED": 4, + "CONFIG_UPDATE_OPERATION_STATE_SUPERSEDED": 5, + "CONFIG_UPDATE_OPERATION_STATE_CANCELLED": 6, + } +) + +func (x ConfigUpdateOperationState) Enum() *ConfigUpdateOperationState { + p := new(ConfigUpdateOperationState) + *p = x + return p +} + +func (x ConfigUpdateOperationState) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ConfigUpdateOperationState) Descriptor() protoreflect.EnumDescriptor { + return file_openshell_proto_enumTypes[6].Descriptor() +} + +func (ConfigUpdateOperationState) Type() protoreflect.EnumType { + return &file_openshell_proto_enumTypes[6] +} + +func (x ConfigUpdateOperationState) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ConfigUpdateOperationState.Descriptor instead. +func (ConfigUpdateOperationState) EnumDescriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{6} +} + // Provider credential token grant configuration. // When present, the credential is obtained dynamically via OAuth2 grant when needed. type ProviderCredentialTokenGrantType int32 @@ -140,11 +532,11 @@ func (x ProviderCredentialTokenGrantType) String() string { } func (ProviderCredentialTokenGrantType) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[1].Descriptor() + return file_openshell_proto_enumTypes[7].Descriptor() } func (ProviderCredentialTokenGrantType) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[1] + return &file_openshell_proto_enumTypes[7] } func (x ProviderCredentialTokenGrantType) Number() protoreflect.EnumNumber { @@ -153,7 +545,7 @@ func (x ProviderCredentialTokenGrantType) Number() protoreflect.EnumNumber { // Deprecated: Use ProviderCredentialTokenGrantType.Descriptor instead. func (ProviderCredentialTokenGrantType) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{1} + return file_openshell_proto_rawDescGZIP(), []int{7} } type ProviderCredentialRefreshStrategy int32 @@ -201,11 +593,11 @@ func (x ProviderCredentialRefreshStrategy) String() string { } func (ProviderCredentialRefreshStrategy) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[2].Descriptor() + return file_openshell_proto_enumTypes[8].Descriptor() } func (ProviderCredentialRefreshStrategy) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[2] + return &file_openshell_proto_enumTypes[8] } func (x ProviderCredentialRefreshStrategy) Number() protoreflect.EnumNumber { @@ -214,7 +606,7 @@ func (x ProviderCredentialRefreshStrategy) Number() protoreflect.EnumNumber { // Deprecated: Use ProviderCredentialRefreshStrategy.Descriptor instead. func (ProviderCredentialRefreshStrategy) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{2} + return file_openshell_proto_rawDescGZIP(), []int{8} } // Stable provider profile categories used by clients for grouping and filtering. @@ -266,11 +658,11 @@ func (x ProviderProfileCategory) String() string { } func (ProviderProfileCategory) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[3].Descriptor() + return file_openshell_proto_enumTypes[9].Descriptor() } func (ProviderProfileCategory) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[3] + return &file_openshell_proto_enumTypes[9] } func (x ProviderProfileCategory) Number() protoreflect.EnumNumber { @@ -279,7 +671,7 @@ func (x ProviderProfileCategory) Number() protoreflect.EnumNumber { // Deprecated: Use ProviderProfileCategory.Descriptor instead. func (ProviderProfileCategory) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{3} + return file_openshell_proto_rawDescGZIP(), []int{9} } // Policy load status. @@ -328,11 +720,11 @@ func (x PolicyStatus) String() string { } func (PolicyStatus) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[4].Descriptor() + return file_openshell_proto_enumTypes[10].Descriptor() } func (PolicyStatus) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[4] + return &file_openshell_proto_enumTypes[10] } func (x PolicyStatus) Number() protoreflect.EnumNumber { @@ -341,7 +733,7 @@ func (x PolicyStatus) Number() protoreflect.EnumNumber { // Deprecated: Use PolicyStatus.Descriptor instead. func (PolicyStatus) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{4} + return file_openshell_proto_rawDescGZIP(), []int{10} } // Service status enum. @@ -381,11 +773,11 @@ func (x ServiceStatus) String() string { } func (ServiceStatus) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[5].Descriptor() + return file_openshell_proto_enumTypes[11].Descriptor() } func (ServiceStatus) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[5] + return &file_openshell_proto_enumTypes[11] } func (x ServiceStatus) Number() protoreflect.EnumNumber { @@ -394,7 +786,7 @@ func (x ServiceStatus) Number() protoreflect.EnumNumber { // Deprecated: Use ServiceStatus.Descriptor instead. func (ServiceStatus) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{5} + return file_openshell_proto_rawDescGZIP(), []int{11} } // Workspace-scoped role for members. @@ -431,11 +823,11 @@ func (x WorkspaceRole) String() string { } func (WorkspaceRole) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[6].Descriptor() + return file_openshell_proto_enumTypes[12].Descriptor() } func (WorkspaceRole) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[6] + return &file_openshell_proto_enumTypes[12] } func (x WorkspaceRole) Number() protoreflect.EnumNumber { @@ -444,7 +836,7 @@ func (x WorkspaceRole) Number() protoreflect.EnumNumber { // Deprecated: Use WorkspaceRole.Descriptor instead. func (WorkspaceRole) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{6} + return file_openshell_proto_rawDescGZIP(), []int{12} } // Stable recovery action for the most recent provider credential refresh @@ -490,11 +882,11 @@ func (x ProviderCredentialRefreshRecoveryAction) String() string { } func (ProviderCredentialRefreshRecoveryAction) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[7].Descriptor() + return file_openshell_proto_enumTypes[13].Descriptor() } func (ProviderCredentialRefreshRecoveryAction) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[7] + return &file_openshell_proto_enumTypes[13] } func (x ProviderCredentialRefreshRecoveryAction) Number() protoreflect.EnumNumber { @@ -503,7 +895,7 @@ func (x ProviderCredentialRefreshRecoveryAction) Number() protoreflect.EnumNumbe // Deprecated: Use ProviderCredentialRefreshRecoveryAction.Descriptor instead. func (ProviderCredentialRefreshRecoveryAction) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{7} + return file_openshell_proto_rawDescGZIP(), []int{13} } // Result of a public delete, membership removal, or session revocation. @@ -553,11 +945,11 @@ func (x DeletionOutcome) String() string { } func (DeletionOutcome) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[8].Descriptor() + return file_openshell_proto_enumTypes[14].Descriptor() } func (DeletionOutcome) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[8] + return &file_openshell_proto_enumTypes[14] } func (x DeletionOutcome) Number() protoreflect.EnumNumber { @@ -566,7 +958,7 @@ func (x DeletionOutcome) Number() protoreflect.EnumNumber { // Deprecated: Use DeletionOutcome.Descriptor instead. func (DeletionOutcome) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{8} + return file_openshell_proto_rawDescGZIP(), []int{14} } // Last observed network result for a configured external tool endpoint. @@ -627,11 +1019,11 @@ func (x EndpointResult) String() string { } func (EndpointResult) Descriptor() protoreflect.EnumDescriptor { - return file_openshell_proto_enumTypes[9].Descriptor() + return file_openshell_proto_enumTypes[15].Descriptor() } func (EndpointResult) Type() protoreflect.EnumType { - return &file_openshell_proto_enumTypes[9] + return &file_openshell_proto_enumTypes[15] } func (x EndpointResult) Number() protoreflect.EnumNumber { @@ -640,7 +1032,7 @@ func (x EndpointResult) Number() protoreflect.EnumNumber { // Deprecated: Use EndpointResult.Descriptor instead. func (EndpointResult) EnumDescriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{9} + return file_openshell_proto_rawDescGZIP(), []int{15} } // IssueSandboxToken request. Empty body; identity is established by the @@ -1631,9 +2023,12 @@ type SandboxSpec struct { // portable scratch login shell before persistence. Command []string `protobuf:"bytes,12,rep,name=command,proto3" json:"command,omitempty"` // Allocate a retained pseudo-terminal for the main process. - Tty bool `protobuf:"varint,13,opt,name=tty,proto3" json:"tty,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + Tty bool `protobuf:"varint,13,opt,name=tty,proto3" json:"tty,omitempty"` + // Gateway-owned attachment identity, changed atomically with the provider set. + // Equality only: detach and reattach must not revive an older receipt. + ProviderAttachmentEpoch string `protobuf:"bytes,14,opt,name=provider_attachment_epoch,json=providerAttachmentEpoch,proto3" json:"provider_attachment_epoch,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SandboxSpec) Reset() { @@ -1722,6 +2117,13 @@ func (x *SandboxSpec) GetTty() bool { return false } +func (x *SandboxSpec) GetProviderAttachmentEpoch() string { + if x != nil { + return x.ProviderAttachmentEpoch + } + return "" +} + type ResourceRequirements struct { state protoimpl.MessageState `protogen:"open.v1"` // GPU requirements for the sandbox. Presence indicates a GPU request. @@ -2668,8 +3070,11 @@ type CreateSandboxRequest struct { WorkloadTemplateName string `protobuf:"bytes,7,opt,name=workload_template_name,json=workloadTemplateName,proto3" json:"workload_template_name,omitempty"` // Explicit workspace for the sandbox. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,8,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,9,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CreateSandboxRequest) Reset() { @@ -2751,13 +3156,23 @@ func (x *CreateSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelecto return nil } +func (x *CreateSandboxRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type CreateSandboxTemplateRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Template *SandboxWorkloadTemplate `protobuf:"bytes,1,opt,name=template,proto3" json:"template,omitempty"` // Explicit workspace for the template. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,4,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CreateSandboxTemplateRequest) Reset() { @@ -2804,6 +3219,13 @@ func (x *CreateSandboxTemplateRequest) GetWorkspaceScope() *datamodelv1.Workspac return nil } +func (x *CreateSandboxTemplateRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type GetSandboxTemplateRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` @@ -2938,7 +3360,9 @@ type DeleteSandboxTemplateRequest struct { WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` // Succeed with ALREADY_ABSENT if the target is missing. Authorization and // parent-workspace checks still apply. - AllowMissing bool `protobuf:"varint,4,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` + AllowMissing bool `protobuf:"varint,4,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + RequestId string `protobuf:"bytes,5,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2994,6 +3418,13 @@ func (x *DeleteSandboxTemplateRequest) GetAllowMissing() bool { return false } +func (x *DeleteSandboxTemplateRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type SandboxTemplateResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Template *SandboxWorkloadTemplate `protobuf:"bytes,1,opt,name=template,proto3" json:"template,omitempty"` @@ -3476,8 +3907,11 @@ type AttachSandboxProviderRequest struct { ExpectedResourceVersion uint64 `protobuf:"varint,3,opt,name=expected_resource_version,json=expectedResourceVersion,proto3" json:"expected_resource_version,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,6,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *AttachSandboxProviderRequest) Reset() { @@ -3538,6 +3972,13 @@ func (x *AttachSandboxProviderRequest) GetWorkspaceScope() *datamodelv1.Workspac return nil } +func (x *AttachSandboxProviderRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Detach provider from sandbox request. type DetachSandboxProviderRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -3552,8 +3993,11 @@ type DetachSandboxProviderRequest struct { ExpectedResourceVersion uint64 `protobuf:"varint,3,opt,name=expected_resource_version,json=expectedResourceVersion,proto3" json:"expected_resource_version,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,6,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DetachSandboxProviderRequest) Reset() { @@ -3614,6 +4058,13 @@ func (x *DetachSandboxProviderRequest) GetWorkspaceScope() *datamodelv1.Workspac return nil } +func (x *DetachSandboxProviderRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Delete sandbox request. type DeleteSandboxRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -3623,7 +4074,10 @@ type DeleteSandboxRequest struct { WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` // Succeed with ALREADY_ABSENT if the target is missing. Does not wait for // asynchronous cleanup and does not suppress authorization or parent errors. - AllowMissing bool `protobuf:"varint,4,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` + AllowMissing bool `protobuf:"varint,4,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,5,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -3679,15 +4133,25 @@ func (x *DeleteSandboxRequest) GetAllowMissing() bool { return false } -// Stop sandbox request. +func (x *DeleteSandboxRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +// Stop sandbox request. type StopSandboxRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Sandbox name (canonical lookup key). Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,4,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *StopSandboxRequest) Reset() { @@ -3734,6 +4198,13 @@ func (x *StopSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector return nil } +func (x *StopSandboxRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Start sandbox request. type StartSandboxRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -3741,8 +4212,11 @@ type StartSandboxRequest struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,4,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *StartSandboxRequest) Reset() { @@ -3789,6 +4263,13 @@ func (x *StartSandboxRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector return nil } +func (x *StartSandboxRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Sandbox response. type SandboxResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -3851,14 +4332,969 @@ func (x *ListSandboxesResponse) Reset() { ms.StoreMessageInfo(mi) } -func (x *ListSandboxesResponse) String() string { +func (x *ListSandboxesResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListSandboxesResponse) ProtoMessage() {} + +func (x *ListSandboxesResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[50] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListSandboxesResponse.ProtoReflect.Descriptor instead. +func (*ListSandboxesResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{50} +} + +func (x *ListSandboxesResponse) GetSandboxes() []*Sandbox { + if x != nil { + return x.Sandboxes + } + return nil +} + +func (x *ListSandboxesResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + +// List providers attached to a sandbox response. +type ListSandboxProvidersResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Providers []*datamodelv1.Provider `protobuf:"bytes,1,rep,name=providers,proto3" json:"providers,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListSandboxProvidersResponse) Reset() { + *x = ListSandboxProvidersResponse{} + mi := &file_openshell_proto_msgTypes[51] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListSandboxProvidersResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListSandboxProvidersResponse) ProtoMessage() {} + +func (x *ListSandboxProvidersResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[51] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListSandboxProvidersResponse.ProtoReflect.Descriptor instead. +func (*ListSandboxProvidersResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{51} +} + +func (x *ListSandboxProvidersResponse) GetProviders() []*datamodelv1.Provider { + if x != nil { + return x.Providers + } + return nil +} + +// Attach provider to sandbox response. +type AttachSandboxProviderResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Sandbox *Sandbox `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` + // True when the provider was newly attached. False means it was already attached. + Attached bool `protobuf:"varint,2,opt,name=attached,proto3" json:"attached,omitempty"` + // Persisted intent; readiness requires current supervisor observations. + Receipt *ProviderMutationReceipt `protobuf:"bytes,3,opt,name=receipt,proto3" json:"receipt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AttachSandboxProviderResponse) Reset() { + *x = AttachSandboxProviderResponse{} + mi := &file_openshell_proto_msgTypes[52] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AttachSandboxProviderResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AttachSandboxProviderResponse) ProtoMessage() {} + +func (x *AttachSandboxProviderResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[52] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AttachSandboxProviderResponse.ProtoReflect.Descriptor instead. +func (*AttachSandboxProviderResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{52} +} + +func (x *AttachSandboxProviderResponse) GetSandbox() *Sandbox { + if x != nil { + return x.Sandbox + } + return nil +} + +func (x *AttachSandboxProviderResponse) GetAttached() bool { + if x != nil { + return x.Attached + } + return false +} + +func (x *AttachSandboxProviderResponse) GetReceipt() *ProviderMutationReceipt { + if x != nil { + return x.Receipt + } + return nil +} + +// Detach provider from sandbox response. +type DetachSandboxProviderResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Sandbox *Sandbox `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` + // True when the provider was removed. False means it was not attached. + Detached bool `protobuf:"varint,2,opt,name=detached,proto3" json:"detached,omitempty"` + // Revocation is complete only when this receipt reports REVOKED. + Receipt *ProviderMutationReceipt `protobuf:"bytes,3,opt,name=receipt,proto3" json:"receipt,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DetachSandboxProviderResponse) Reset() { + *x = DetachSandboxProviderResponse{} + mi := &file_openshell_proto_msgTypes[53] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DetachSandboxProviderResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DetachSandboxProviderResponse) ProtoMessage() {} + +func (x *DetachSandboxProviderResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[53] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DetachSandboxProviderResponse.ProtoReflect.Descriptor instead. +func (*DetachSandboxProviderResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{53} +} + +func (x *DetachSandboxProviderResponse) GetSandbox() *Sandbox { + if x != nil { + return x.Sandbox + } + return nil +} + +func (x *DetachSandboxProviderResponse) GetDetached() bool { + if x != nil { + return x.Detached + } + return false +} + +func (x *DetachSandboxProviderResponse) GetReceipt() *ProviderMutationReceipt { + if x != nil { + return x.Receipt + } + return nil +} + +// Exact desired authority. Revisions are opaque identities, never ordered. +type ProviderDesiredIdentity struct { + state protoimpl.MessageState `protogen:"open.v1"` + SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` + SandboxName string `protobuf:"bytes,2,opt,name=sandbox_name,json=sandboxName,proto3" json:"sandbox_name,omitempty"` + AttachmentEpoch string `protobuf:"bytes,3,opt,name=attachment_epoch,json=attachmentEpoch,proto3" json:"attachment_epoch,omitempty"` + // Empty for a detached provider. + ProviderId string `protobuf:"bytes,4,opt,name=provider_id,json=providerId,proto3" json:"provider_id,omitempty"` + ProviderResourceVersion uint64 `protobuf:"varint,5,opt,name=provider_resource_version,json=providerResourceVersion,proto3" json:"provider_resource_version,omitempty"` + ProviderEnvRevision uint64 `protobuf:"varint,6,opt,name=provider_env_revision,json=providerEnvRevision,proto3" json:"provider_env_revision,omitempty"` + ConfigRevision uint64 `protobuf:"varint,7,opt,name=config_revision,json=configRevision,proto3" json:"config_revision,omitempty"` + PolicyHash string `protobuf:"bytes,8,opt,name=policy_hash,json=policyHash,proto3" json:"policy_hash,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ProviderDesiredIdentity) Reset() { + *x = ProviderDesiredIdentity{} + mi := &file_openshell_proto_msgTypes[54] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ProviderDesiredIdentity) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProviderDesiredIdentity) ProtoMessage() {} + +func (x *ProviderDesiredIdentity) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[54] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProviderDesiredIdentity.ProtoReflect.Descriptor instead. +func (*ProviderDesiredIdentity) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{54} +} + +func (x *ProviderDesiredIdentity) GetSandboxId() string { + if x != nil { + return x.SandboxId + } + return "" +} + +func (x *ProviderDesiredIdentity) GetSandboxName() string { + if x != nil { + return x.SandboxName + } + return "" +} + +func (x *ProviderDesiredIdentity) GetAttachmentEpoch() string { + if x != nil { + return x.AttachmentEpoch + } + return "" +} + +func (x *ProviderDesiredIdentity) GetProviderId() string { + if x != nil { + return x.ProviderId + } + return "" +} + +func (x *ProviderDesiredIdentity) GetProviderResourceVersion() uint64 { + if x != nil { + return x.ProviderResourceVersion + } + return 0 +} + +func (x *ProviderDesiredIdentity) GetProviderEnvRevision() uint64 { + if x != nil { + return x.ProviderEnvRevision + } + return 0 +} + +func (x *ProviderDesiredIdentity) GetConfigRevision() uint64 { + if x != nil { + return x.ConfigRevision + } + return 0 +} + +func (x *ProviderDesiredIdentity) GetPolicyHash() string { + if x != nil { + return x.PolicyHash + } + return "" +} + +// Identifies one component snapshot revision. Revisions are equality tokens, +// not members of one shared ordering domain. +type ConfigSnapshotRevision struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Types that are valid to be assigned to Component: + // + // *ConfigSnapshotRevision_SandboxConfig + // *ConfigSnapshotRevision_ProviderEnvironment + // *ConfigSnapshotRevision_ProviderTarget + Component isConfigSnapshotRevision_Component `protobuf_oneof:"component"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ConfigSnapshotRevision) Reset() { + *x = ConfigSnapshotRevision{} + mi := &file_openshell_proto_msgTypes[55] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ConfigSnapshotRevision) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ConfigSnapshotRevision) ProtoMessage() {} + +func (x *ConfigSnapshotRevision) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[55] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ConfigSnapshotRevision.ProtoReflect.Descriptor instead. +func (*ConfigSnapshotRevision) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{55} +} + +func (x *ConfigSnapshotRevision) GetComponent() isConfigSnapshotRevision_Component { + if x != nil { + return x.Component + } + return nil +} + +func (x *ConfigSnapshotRevision) GetSandboxConfig() *SandboxConfigRevision { + if x != nil { + if x, ok := x.Component.(*ConfigSnapshotRevision_SandboxConfig); ok { + return x.SandboxConfig + } + } + return nil +} + +func (x *ConfigSnapshotRevision) GetProviderEnvironment() uint64 { + if x != nil { + if x, ok := x.Component.(*ConfigSnapshotRevision_ProviderEnvironment); ok { + return x.ProviderEnvironment + } + } + return 0 +} + +func (x *ConfigSnapshotRevision) GetProviderTarget() *ProviderDesiredIdentity { + if x != nil { + if x, ok := x.Component.(*ConfigSnapshotRevision_ProviderTarget); ok { + return x.ProviderTarget + } + } + return nil +} + +type isConfigSnapshotRevision_Component interface { + isConfigSnapshotRevision_Component() +} + +type ConfigSnapshotRevision_SandboxConfig struct { + SandboxConfig *SandboxConfigRevision `protobuf:"bytes,1,opt,name=sandbox_config,json=sandboxConfig,proto3,oneof"` +} + +type ConfigSnapshotRevision_ProviderEnvironment struct { + ProviderEnvironment uint64 `protobuf:"varint,2,opt,name=provider_environment,json=providerEnvironment,proto3,oneof"` +} + +type ConfigSnapshotRevision_ProviderTarget struct { + // Complete desired authority for one sandbox-scoped provider mutation. + ProviderTarget *ProviderDesiredIdentity `protobuf:"bytes,3,opt,name=provider_target,json=providerTarget,proto3,oneof"` +} + +func (*ConfigSnapshotRevision_SandboxConfig) isConfigSnapshotRevision_Component() {} + +func (*ConfigSnapshotRevision_ProviderEnvironment) isConfigSnapshotRevision_Component() {} + +func (*ConfigSnapshotRevision_ProviderTarget) isConfigSnapshotRevision_Component() {} + +// Identity needed to correlate effective sandbox configuration with the +// policy-history row whose apply status the gateway records. +type SandboxConfigRevision struct { + state protoimpl.MessageState `protogen:"open.v1"` + ConfigRevision uint64 `protobuf:"varint,1,opt,name=config_revision,json=configRevision,proto3" json:"config_revision,omitempty"` + PolicyVersion uint32 `protobuf:"varint,2,opt,name=policy_version,json=policyVersion,proto3" json:"policy_version,omitempty"` + PolicySource sandboxv1.PolicySource `protobuf:"varint,3,opt,name=policy_source,json=policySource,proto3,enum=openshell.sandbox.v1.PolicySource" json:"policy_source,omitempty"` + GlobalPolicyVersion uint32 `protobuf:"varint,4,opt,name=global_policy_version,json=globalPolicyVersion,proto3" json:"global_policy_version,omitempty"` + // Monotonic revision of the sandbox-scoped settings row. This disambiguates + // setting operations whose effective config fingerprint is equality-only. + SettingsRevision uint64 `protobuf:"varint,5,opt,name=settings_revision,json=settingsRevision,proto3" json:"settings_revision,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SandboxConfigRevision) Reset() { + *x = SandboxConfigRevision{} + mi := &file_openshell_proto_msgTypes[56] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SandboxConfigRevision) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SandboxConfigRevision) ProtoMessage() {} + +func (x *SandboxConfigRevision) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[56] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SandboxConfigRevision.ProtoReflect.Descriptor instead. +func (*SandboxConfigRevision) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{56} +} + +func (x *SandboxConfigRevision) GetConfigRevision() uint64 { + if x != nil { + return x.ConfigRevision + } + return 0 +} + +func (x *SandboxConfigRevision) GetPolicyVersion() uint32 { + if x != nil { + return x.PolicyVersion + } + return 0 +} + +func (x *SandboxConfigRevision) GetPolicySource() sandboxv1.PolicySource { + if x != nil { + return x.PolicySource + } + return sandboxv1.PolicySource(0) +} + +func (x *SandboxConfigRevision) GetGlobalPolicyVersion() uint32 { + if x != nil { + return x.GlobalPolicyVersion + } + return 0 +} + +func (x *SandboxConfigRevision) GetSettingsRevision() uint64 { + if x != nil { + return x.SettingsRevision + } + return 0 +} + +// Durable progress for one sandbox-scoped desired-state mutation. Snapshot +// contents and credentials are never stored in this resource. +type ConfigUpdateOperation struct { + state protoimpl.MessageState `protogen:"open.v1"` + OperationId string `protobuf:"bytes,1,opt,name=operation_id,json=operationId,proto3" json:"operation_id,omitempty"` + SandboxId string `protobuf:"bytes,2,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` + Component ConfigComponent `protobuf:"varint,3,opt,name=component,proto3,enum=openshell.v1.ConfigComponent" json:"component,omitempty"` + TargetRevision *ConfigSnapshotRevision `protobuf:"bytes,4,opt,name=target_revision,json=targetRevision,proto3" json:"target_revision,omitempty"` + State ConfigUpdateOperationState `protobuf:"varint,5,opt,name=state,proto3,enum=openshell.v1.ConfigUpdateOperationState" json:"state,omitempty"` + Outcome ConfigApplyOutcome `protobuf:"varint,6,opt,name=outcome,proto3,enum=openshell.v1.ConfigApplyOutcome" json:"outcome,omitempty"` + SanitizedError string `protobuf:"bytes,7,opt,name=sanitized_error,json=sanitizedError,proto3" json:"sanitized_error,omitempty"` + CreatedTime *timestamppb.Timestamp `protobuf:"bytes,108,opt,name=created_time,json=createdTime,proto3" json:"created_time,omitempty"` + UpdatedTime *timestamppb.Timestamp `protobuf:"bytes,109,opt,name=updated_time,json=updatedTime,proto3" json:"updated_time,omitempty"` + // Absent until the operation reaches a terminal state. + CompletedTime *timestamppb.Timestamp `protobuf:"bytes,110,opt,name=completed_time,json=completedTime,proto3" json:"completed_time,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ConfigUpdateOperation) Reset() { + *x = ConfigUpdateOperation{} + mi := &file_openshell_proto_msgTypes[57] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ConfigUpdateOperation) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ConfigUpdateOperation) ProtoMessage() {} + +func (x *ConfigUpdateOperation) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[57] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ConfigUpdateOperation.ProtoReflect.Descriptor instead. +func (*ConfigUpdateOperation) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{57} +} + +func (x *ConfigUpdateOperation) GetOperationId() string { + if x != nil { + return x.OperationId + } + return "" +} + +func (x *ConfigUpdateOperation) GetSandboxId() string { + if x != nil { + return x.SandboxId + } + return "" +} + +func (x *ConfigUpdateOperation) GetComponent() ConfigComponent { + if x != nil { + return x.Component + } + return ConfigComponent_CONFIG_COMPONENT_UNSPECIFIED +} + +func (x *ConfigUpdateOperation) GetTargetRevision() *ConfigSnapshotRevision { + if x != nil { + return x.TargetRevision + } + return nil +} + +func (x *ConfigUpdateOperation) GetState() ConfigUpdateOperationState { + if x != nil { + return x.State + } + return ConfigUpdateOperationState_CONFIG_UPDATE_OPERATION_STATE_UNSPECIFIED +} + +func (x *ConfigUpdateOperation) GetOutcome() ConfigApplyOutcome { + if x != nil { + return x.Outcome + } + return ConfigApplyOutcome_CONFIG_APPLY_OUTCOME_UNSPECIFIED +} + +func (x *ConfigUpdateOperation) GetSanitizedError() string { + if x != nil { + return x.SanitizedError + } + return "" +} + +func (x *ConfigUpdateOperation) GetCreatedTime() *timestamppb.Timestamp { + if x != nil { + return x.CreatedTime + } + return nil +} + +func (x *ConfigUpdateOperation) GetUpdatedTime() *timestamppb.Timestamp { + if x != nil { + return x.UpdatedTime + } + return nil +} + +func (x *ConfigUpdateOperation) GetCompletedTime() *timestamppb.Timestamp { + if x != nil { + return x.CompletedTime + } + return nil +} + +// Immutable, secret-free record of one sandbox's intended provider mutation. +type ProviderMutationReceipt struct { + state protoimpl.MessageState `protogen:"open.v1"` + ReceiptId string `protobuf:"bytes,1,opt,name=receipt_id,json=receiptId,proto3" json:"receipt_id,omitempty"` + // Shared by all sandbox receipts from one provider update. + MutationId string `protobuf:"bytes,2,opt,name=mutation_id,json=mutationId,proto3" json:"mutation_id,omitempty"` + ProviderName string `protobuf:"bytes,3,opt,name=provider_name,json=providerName,proto3" json:"provider_name,omitempty"` + Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` + Kind ProviderMutationKind `protobuf:"varint,5,opt,name=kind,proto3,enum=openshell.v1.ProviderMutationKind" json:"kind,omitempty"` + Desired *ProviderDesiredIdentity `protobuf:"bytes,6,opt,name=desired,proto3" json:"desired,omitempty"` + PersistedTime *timestamppb.Timestamp `protobuf:"bytes,107,opt,name=persisted_time,json=persistedTime,proto3" json:"persisted_time,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ProviderMutationReceipt) Reset() { + *x = ProviderMutationReceipt{} + mi := &file_openshell_proto_msgTypes[58] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ProviderMutationReceipt) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProviderMutationReceipt) ProtoMessage() {} + +func (x *ProviderMutationReceipt) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[58] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProviderMutationReceipt.ProtoReflect.Descriptor instead. +func (*ProviderMutationReceipt) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{58} +} + +func (x *ProviderMutationReceipt) GetReceiptId() string { + if x != nil { + return x.ReceiptId + } + return "" +} + +func (x *ProviderMutationReceipt) GetMutationId() string { + if x != nil { + return x.MutationId + } + return "" +} + +func (x *ProviderMutationReceipt) GetProviderName() string { + if x != nil { + return x.ProviderName + } + return "" +} + +func (x *ProviderMutationReceipt) GetWorkspace() string { + if x != nil { + return x.Workspace + } + return "" +} + +func (x *ProviderMutationReceipt) GetKind() ProviderMutationKind { + if x != nil { + return x.Kind + } + return ProviderMutationKind_PROVIDER_MUTATION_KIND_UNSPECIFIED +} + +func (x *ProviderMutationReceipt) GetDesired() *ProviderDesiredIdentity { + if x != nil { + return x.Desired + } + return nil +} + +func (x *ProviderMutationReceipt) GetPersistedTime() *timestamppb.Timestamp { + if x != nil { + return x.PersistedTime + } + return nil +} + +// Installed state reported by the current supervisor. Process installation is +// acknowledged by the authenticated sandbox boundary after replacing its +// environment for future process launches. +type ProviderReadinessObservation struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Gateway-issued identifier from the current ConnectSupervisor response. + SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` + // Monotonic only within this connection; unrelated to revision fingerprints. + Sequence uint64 `protobuf:"varint,2,opt,name=sequence,proto3" json:"sequence,omitempty"` + AttachmentEpoch string `protobuf:"bytes,3,opt,name=attachment_epoch,json=attachmentEpoch,proto3" json:"attachment_epoch,omitempty"` + ProviderEnvRevision uint64 `protobuf:"varint,4,opt,name=provider_env_revision,json=providerEnvRevision,proto3" json:"provider_env_revision,omitempty"` + ConfigRevision uint64 `protobuf:"varint,5,opt,name=config_revision,json=configRevision,proto3" json:"config_revision,omitempty"` + PolicyHash string `protobuf:"bytes,6,opt,name=policy_hash,json=policyHash,proto3" json:"policy_hash,omitempty"` + CredentialsInstalled bool `protobuf:"varint,7,opt,name=credentials_installed,json=credentialsInstalled,proto3" json:"credentials_installed,omitempty"` + PolicyActive bool `protobuf:"varint,8,opt,name=policy_active,json=policyActive,proto3" json:"policy_active,omitempty"` + LaunchEnvironmentInstalled bool `protobuf:"varint,9,opt,name=launch_environment_installed,json=launchEnvironmentInstalled,proto3" json:"launch_environment_installed,omitempty"` + ProcessInstanceId string `protobuf:"bytes,10,opt,name=process_instance_id,json=processInstanceId,proto3" json:"process_instance_id,omitempty"` + Reason ProviderReadinessReason `protobuf:"varint,11,opt,name=reason,proto3,enum=openshell.v1.ProviderReadinessReason" json:"reason,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ProviderReadinessObservation) Reset() { + *x = ProviderReadinessObservation{} + mi := &file_openshell_proto_msgTypes[59] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ProviderReadinessObservation) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProviderReadinessObservation) ProtoMessage() {} + +func (x *ProviderReadinessObservation) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[59] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProviderReadinessObservation.ProtoReflect.Descriptor instead. +func (*ProviderReadinessObservation) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{59} +} + +func (x *ProviderReadinessObservation) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *ProviderReadinessObservation) GetSequence() uint64 { + if x != nil { + return x.Sequence + } + return 0 +} + +func (x *ProviderReadinessObservation) GetAttachmentEpoch() string { + if x != nil { + return x.AttachmentEpoch + } + return "" +} + +func (x *ProviderReadinessObservation) GetProviderEnvRevision() uint64 { + if x != nil { + return x.ProviderEnvRevision + } + return 0 +} + +func (x *ProviderReadinessObservation) GetConfigRevision() uint64 { + if x != nil { + return x.ConfigRevision + } + return 0 +} + +func (x *ProviderReadinessObservation) GetPolicyHash() string { + if x != nil { + return x.PolicyHash + } + return "" +} + +func (x *ProviderReadinessObservation) GetCredentialsInstalled() bool { + if x != nil { + return x.CredentialsInstalled + } + return false +} + +func (x *ProviderReadinessObservation) GetPolicyActive() bool { + if x != nil { + return x.PolicyActive + } + return false +} + +func (x *ProviderReadinessObservation) GetLaunchEnvironmentInstalled() bool { + if x != nil { + return x.LaunchEnvironmentInstalled + } + return false +} + +func (x *ProviderReadinessObservation) GetProcessInstanceId() string { + if x != nil { + return x.ProcessInstanceId + } + return "" +} + +func (x *ProviderReadinessObservation) GetReason() ProviderReadinessReason { + if x != nil { + return x.Reason + } + return ProviderReadinessReason_PROVIDER_READINESS_REASON_UNSPECIFIED +} + +// Operator view of desired and observed state; contains no credential material. +type ProviderReadinessStatus struct { + state protoimpl.MessageState `protogen:"open.v1"` + Receipt *ProviderMutationReceipt `protobuf:"bytes,1,opt,name=receipt,proto3" json:"receipt,omitempty"` + State ProviderReadinessState `protobuf:"varint,2,opt,name=state,proto3,enum=openshell.v1.ProviderReadinessState" json:"state,omitempty"` + Reason ProviderReadinessReason `protobuf:"varint,3,opt,name=reason,proto3,enum=openshell.v1.ProviderReadinessReason" json:"reason,omitempty"` + Observed *ProviderReadinessObservation `protobuf:"bytes,4,opt,name=observed,proto3" json:"observed,omitempty"` + NetworkInstanceId string `protobuf:"bytes,5,opt,name=network_instance_id,json=networkInstanceId,proto3" json:"network_instance_id,omitempty"` + // Absent until the current supervisor session supplies accepted evidence. + ObservedTime *timestamppb.Timestamp `protobuf:"bytes,106,opt,name=observed_time,json=observedTime,proto3" json:"observed_time,omitempty"` + EvaluatedTime *timestamppb.Timestamp `protobuf:"bytes,107,opt,name=evaluated_time,json=evaluatedTime,proto3" json:"evaluated_time,omitempty"` + // Durable operation for the receipt, including its terminal apply outcome. + Operation *ConfigUpdateOperation `protobuf:"bytes,8,opt,name=operation,proto3" json:"operation,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ProviderReadinessStatus) Reset() { + *x = ProviderReadinessStatus{} + mi := &file_openshell_proto_msgTypes[60] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ProviderReadinessStatus) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProviderReadinessStatus) ProtoMessage() {} + +func (x *ProviderReadinessStatus) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[60] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProviderReadinessStatus.ProtoReflect.Descriptor instead. +func (*ProviderReadinessStatus) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{60} +} + +func (x *ProviderReadinessStatus) GetReceipt() *ProviderMutationReceipt { + if x != nil { + return x.Receipt + } + return nil +} + +func (x *ProviderReadinessStatus) GetState() ProviderReadinessState { + if x != nil { + return x.State + } + return ProviderReadinessState_PROVIDER_READINESS_STATE_UNSPECIFIED +} + +func (x *ProviderReadinessStatus) GetReason() ProviderReadinessReason { + if x != nil { + return x.Reason + } + return ProviderReadinessReason_PROVIDER_READINESS_REASON_UNSPECIFIED +} + +func (x *ProviderReadinessStatus) GetObserved() *ProviderReadinessObservation { + if x != nil { + return x.Observed + } + return nil +} + +func (x *ProviderReadinessStatus) GetNetworkInstanceId() string { + if x != nil { + return x.NetworkInstanceId + } + return "" +} + +func (x *ProviderReadinessStatus) GetObservedTime() *timestamppb.Timestamp { + if x != nil { + return x.ObservedTime + } + return nil +} + +func (x *ProviderReadinessStatus) GetEvaluatedTime() *timestamppb.Timestamp { + if x != nil { + return x.EvaluatedTime + } + return nil +} + +func (x *ProviderReadinessStatus) GetOperation() *ConfigUpdateOperation { + if x != nil { + return x.Operation + } + return nil +} + +// Query an immutable receipt, or reconstruct the current desired state when +// receipt_id is empty. The sandbox identity must match the receipt. +type GetSandboxProviderStatusRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + SandboxName string `protobuf:"bytes,1,opt,name=sandbox_name,json=sandboxName,proto3" json:"sandbox_name,omitempty"` + ProviderName string `protobuf:"bytes,2,opt,name=provider_name,json=providerName,proto3" json:"provider_name,omitempty"` + ReceiptId string `protobuf:"bytes,3,opt,name=receipt_id,json=receiptId,proto3" json:"receipt_id,omitempty"` + WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetSandboxProviderStatusRequest) Reset() { + *x = GetSandboxProviderStatusRequest{} + mi := &file_openshell_proto_msgTypes[61] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetSandboxProviderStatusRequest) String() string { return protoimpl.X.MessageStringOf(x) } -func (*ListSandboxesResponse) ProtoMessage() {} +func (*GetSandboxProviderStatusRequest) ProtoMessage() {} -func (x *ListSandboxesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[50] +func (x *GetSandboxProviderStatusRequest) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[61] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3869,48 +5305,61 @@ func (x *ListSandboxesResponse) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use ListSandboxesResponse.ProtoReflect.Descriptor instead. -func (*ListSandboxesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{50} +// Deprecated: Use GetSandboxProviderStatusRequest.ProtoReflect.Descriptor instead. +func (*GetSandboxProviderStatusRequest) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{61} } -func (x *ListSandboxesResponse) GetSandboxes() []*Sandbox { +func (x *GetSandboxProviderStatusRequest) GetSandboxName() string { if x != nil { - return x.Sandboxes + return x.SandboxName } - return nil + return "" } -func (x *ListSandboxesResponse) GetNextPageToken() string { +func (x *GetSandboxProviderStatusRequest) GetProviderName() string { if x != nil { - return x.NextPageToken + return x.ProviderName } return "" } -// List providers attached to a sandbox response. -type ListSandboxProvidersResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Providers []*datamodelv1.Provider `protobuf:"bytes,1,rep,name=providers,proto3" json:"providers,omitempty"` +func (x *GetSandboxProviderStatusRequest) GetReceiptId() string { + if x != nil { + return x.ReceiptId + } + return "" +} + +func (x *GetSandboxProviderStatusRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector { + if x != nil { + return x.WorkspaceScope + } + return nil +} + +type GetSandboxProviderStatusResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Status *ProviderReadinessStatus `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *ListSandboxProvidersResponse) Reset() { - *x = ListSandboxProvidersResponse{} - mi := &file_openshell_proto_msgTypes[51] +func (x *GetSandboxProviderStatusResponse) Reset() { + *x = GetSandboxProviderStatusResponse{} + mi := &file_openshell_proto_msgTypes[62] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *ListSandboxProvidersResponse) String() string { +func (x *GetSandboxProviderStatusResponse) String() string { return protoimpl.X.MessageStringOf(x) } -func (*ListSandboxProvidersResponse) ProtoMessage() {} +func (*GetSandboxProviderStatusResponse) ProtoMessage() {} -func (x *ListSandboxProvidersResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[51] +func (x *GetSandboxProviderStatusResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[62] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3921,43 +5370,43 @@ func (x *ListSandboxProvidersResponse) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use ListSandboxProvidersResponse.ProtoReflect.Descriptor instead. -func (*ListSandboxProvidersResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{51} +// Deprecated: Use GetSandboxProviderStatusResponse.ProtoReflect.Descriptor instead. +func (*GetSandboxProviderStatusResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{62} } -func (x *ListSandboxProvidersResponse) GetProviders() []*datamodelv1.Provider { +func (x *GetSandboxProviderStatusResponse) GetStatus() *ProviderReadinessStatus { if x != nil { - return x.Providers + return x.Status } return nil } -// Attach provider to sandbox response. -type AttachSandboxProviderResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Sandbox *Sandbox `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` - // True when the provider was newly attached. False means it was already attached. - Attached bool `protobuf:"varint,2,opt,name=attached,proto3" json:"attached,omitempty"` +// Installation evidence from the authenticated supervisor for this sandbox. +// A caller-provided instance identifier alone never establishes authority. +type ReportProviderReadinessRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` + Observation *ProviderReadinessObservation `protobuf:"bytes,2,opt,name=observation,proto3" json:"observation,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *AttachSandboxProviderResponse) Reset() { - *x = AttachSandboxProviderResponse{} - mi := &file_openshell_proto_msgTypes[52] +func (x *ReportProviderReadinessRequest) Reset() { + *x = ReportProviderReadinessRequest{} + mi := &file_openshell_proto_msgTypes[63] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *AttachSandboxProviderResponse) String() string { +func (x *ReportProviderReadinessRequest) String() string { return protoimpl.X.MessageStringOf(x) } -func (*AttachSandboxProviderResponse) ProtoMessage() {} +func (*ReportProviderReadinessRequest) ProtoMessage() {} -func (x *AttachSandboxProviderResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[52] +func (x *ReportProviderReadinessRequest) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[63] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3968,50 +5417,51 @@ func (x *AttachSandboxProviderResponse) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use AttachSandboxProviderResponse.ProtoReflect.Descriptor instead. -func (*AttachSandboxProviderResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{52} +// Deprecated: Use ReportProviderReadinessRequest.ProtoReflect.Descriptor instead. +func (*ReportProviderReadinessRequest) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{63} } -func (x *AttachSandboxProviderResponse) GetSandbox() *Sandbox { +func (x *ReportProviderReadinessRequest) GetSandboxId() string { if x != nil { - return x.Sandbox + return x.SandboxId } - return nil + return "" } -func (x *AttachSandboxProviderResponse) GetAttached() bool { +func (x *ReportProviderReadinessRequest) GetObservation() *ProviderReadinessObservation { if x != nil { - return x.Attached + return x.Observation } - return false + return nil } -// Detach provider from sandbox response. -type DetachSandboxProviderResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Sandbox *Sandbox `protobuf:"bytes,1,opt,name=sandbox,proto3" json:"sandbox,omitempty"` - // True when the provider was removed. False means it was not attached. - Detached bool `protobuf:"varint,2,opt,name=detached,proto3" json:"detached,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache +// Acknowledges accepted evidence without granting a separate session authority. +// Identical retries do not extend the evidence's original acceptance time. +type ReportProviderReadinessResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + AcceptedSequence uint64 `protobuf:"varint,1,opt,name=accepted_sequence,json=acceptedSequence,proto3" json:"accepted_sequence,omitempty"` + ReportInterval *durationpb.Duration `protobuf:"bytes,102,opt,name=report_interval,json=reportInterval,proto3" json:"report_interval,omitempty"` + ObservationTtl *durationpb.Duration `protobuf:"bytes,103,opt,name=observation_ttl,json=observationTtl,proto3" json:"observation_ttl,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -func (x *DetachSandboxProviderResponse) Reset() { - *x = DetachSandboxProviderResponse{} - mi := &file_openshell_proto_msgTypes[53] +func (x *ReportProviderReadinessResponse) Reset() { + *x = ReportProviderReadinessResponse{} + mi := &file_openshell_proto_msgTypes[64] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *DetachSandboxProviderResponse) String() string { +func (x *ReportProviderReadinessResponse) String() string { return protoimpl.X.MessageStringOf(x) } -func (*DetachSandboxProviderResponse) ProtoMessage() {} +func (*ReportProviderReadinessResponse) ProtoMessage() {} -func (x *DetachSandboxProviderResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[53] +func (x *ReportProviderReadinessResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[64] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4022,23 +5472,30 @@ func (x *DetachSandboxProviderResponse) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use DetachSandboxProviderResponse.ProtoReflect.Descriptor instead. -func (*DetachSandboxProviderResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{53} +// Deprecated: Use ReportProviderReadinessResponse.ProtoReflect.Descriptor instead. +func (*ReportProviderReadinessResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{64} } -func (x *DetachSandboxProviderResponse) GetSandbox() *Sandbox { +func (x *ReportProviderReadinessResponse) GetAcceptedSequence() uint64 { if x != nil { - return x.Sandbox + return x.AcceptedSequence + } + return 0 +} + +func (x *ReportProviderReadinessResponse) GetReportInterval() *durationpb.Duration { + if x != nil { + return x.ReportInterval } return nil } -func (x *DetachSandboxProviderResponse) GetDetached() bool { +func (x *ReportProviderReadinessResponse) GetObservationTtl() *durationpb.Duration { if x != nil { - return x.Detached + return x.ObservationTtl } - return false + return nil } // Delete sandbox response. @@ -4054,7 +5511,7 @@ type DeleteSandboxResponse struct { func (x *DeleteSandboxResponse) Reset() { *x = DeleteSandboxResponse{} - mi := &file_openshell_proto_msgTypes[54] + mi := &file_openshell_proto_msgTypes[65] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4066,7 +5523,7 @@ func (x *DeleteSandboxResponse) String() string { func (*DeleteSandboxResponse) ProtoMessage() {} func (x *DeleteSandboxResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[54] + mi := &file_openshell_proto_msgTypes[65] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4079,7 +5536,7 @@ func (x *DeleteSandboxResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteSandboxResponse.ProtoReflect.Descriptor instead. func (*DeleteSandboxResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{54} + return file_openshell_proto_rawDescGZIP(), []int{65} } func (x *DeleteSandboxResponse) GetOutcome() DeletionOutcome { @@ -4107,7 +5564,7 @@ type CreateSshSessionRequest struct { func (x *CreateSshSessionRequest) Reset() { *x = CreateSshSessionRequest{} - mi := &file_openshell_proto_msgTypes[55] + mi := &file_openshell_proto_msgTypes[66] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4119,7 +5576,7 @@ func (x *CreateSshSessionRequest) String() string { func (*CreateSshSessionRequest) ProtoMessage() {} func (x *CreateSshSessionRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[55] + mi := &file_openshell_proto_msgTypes[66] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4132,7 +5589,7 @@ func (x *CreateSshSessionRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateSshSessionRequest.ProtoReflect.Descriptor instead. func (*CreateSshSessionRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{55} + return file_openshell_proto_rawDescGZIP(), []int{66} } func (x *CreateSshSessionRequest) GetSandboxId() string { @@ -4175,7 +5632,7 @@ type CreateSshSessionResponse struct { func (x *CreateSshSessionResponse) Reset() { *x = CreateSshSessionResponse{} - mi := &file_openshell_proto_msgTypes[56] + mi := &file_openshell_proto_msgTypes[67] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4187,7 +5644,7 @@ func (x *CreateSshSessionResponse) String() string { func (*CreateSshSessionResponse) ProtoMessage() {} func (x *CreateSshSessionResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[56] + mi := &file_openshell_proto_msgTypes[67] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4200,7 +5657,7 @@ func (x *CreateSshSessionResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateSshSessionResponse.ProtoReflect.Descriptor instead. func (*CreateSshSessionResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{56} + return file_openshell_proto_rawDescGZIP(), []int{67} } func (x *CreateSshSessionResponse) GetSandboxId() string { @@ -4265,13 +5722,16 @@ type ExposeServiceRequest struct { Domain bool `protobuf:"varint,4,opt,name=domain,proto3" json:"domain,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,6,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,7,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ExposeServiceRequest) Reset() { *x = ExposeServiceRequest{} - mi := &file_openshell_proto_msgTypes[57] + mi := &file_openshell_proto_msgTypes[68] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4283,7 +5743,7 @@ func (x *ExposeServiceRequest) String() string { func (*ExposeServiceRequest) ProtoMessage() {} func (x *ExposeServiceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[57] + mi := &file_openshell_proto_msgTypes[68] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4296,7 +5756,7 @@ func (x *ExposeServiceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ExposeServiceRequest.ProtoReflect.Descriptor instead. func (*ExposeServiceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{57} + return file_openshell_proto_rawDescGZIP(), []int{68} } func (x *ExposeServiceRequest) GetSandbox() string { @@ -4334,6 +5794,13 @@ func (x *ExposeServiceRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelecto return nil } +func (x *ExposeServiceRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Request to fetch an exposed sandbox service endpoint. type GetServiceRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -4349,7 +5816,7 @@ type GetServiceRequest struct { func (x *GetServiceRequest) Reset() { *x = GetServiceRequest{} - mi := &file_openshell_proto_msgTypes[58] + mi := &file_openshell_proto_msgTypes[69] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4361,7 +5828,7 @@ func (x *GetServiceRequest) String() string { func (*GetServiceRequest) ProtoMessage() {} func (x *GetServiceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[58] + mi := &file_openshell_proto_msgTypes[69] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4374,7 +5841,7 @@ func (x *GetServiceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetServiceRequest.ProtoReflect.Descriptor instead. func (*GetServiceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{58} + return file_openshell_proto_rawDescGZIP(), []int{69} } func (x *GetServiceRequest) GetSandbox() string { @@ -4417,7 +5884,7 @@ type ListServicesRequest struct { func (x *ListServicesRequest) Reset() { *x = ListServicesRequest{} - mi := &file_openshell_proto_msgTypes[59] + mi := &file_openshell_proto_msgTypes[70] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4429,7 +5896,7 @@ func (x *ListServicesRequest) String() string { func (*ListServicesRequest) ProtoMessage() {} func (x *ListServicesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[59] + mi := &file_openshell_proto_msgTypes[70] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4442,7 +5909,7 @@ func (x *ListServicesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListServicesRequest.ProtoReflect.Descriptor instead. func (*ListServicesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{59} + return file_openshell_proto_rawDescGZIP(), []int{70} } func (x *ListServicesRequest) GetSandbox() string { @@ -4485,7 +5952,7 @@ type ListServicesResponse struct { func (x *ListServicesResponse) Reset() { *x = ListServicesResponse{} - mi := &file_openshell_proto_msgTypes[60] + mi := &file_openshell_proto_msgTypes[71] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4497,7 +5964,7 @@ func (x *ListServicesResponse) String() string { func (*ListServicesResponse) ProtoMessage() {} func (x *ListServicesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[60] + mi := &file_openshell_proto_msgTypes[71] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4510,7 +5977,7 @@ func (x *ListServicesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListServicesResponse.ProtoReflect.Descriptor instead. func (*ListServicesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{60} + return file_openshell_proto_rawDescGZIP(), []int{71} } func (x *ListServicesResponse) GetServices() []*ServiceEndpointResponse { @@ -4537,13 +6004,16 @@ type DeleteServiceRequest struct { // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` AllowMissing bool `protobuf:"varint,5,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,6,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DeleteServiceRequest) Reset() { *x = DeleteServiceRequest{} - mi := &file_openshell_proto_msgTypes[61] + mi := &file_openshell_proto_msgTypes[72] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4555,7 +6025,7 @@ func (x *DeleteServiceRequest) String() string { func (*DeleteServiceRequest) ProtoMessage() {} func (x *DeleteServiceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[61] + mi := &file_openshell_proto_msgTypes[72] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4568,7 +6038,7 @@ func (x *DeleteServiceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteServiceRequest.ProtoReflect.Descriptor instead. func (*DeleteServiceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{61} + return file_openshell_proto_rawDescGZIP(), []int{72} } func (x *DeleteServiceRequest) GetSandbox() string { @@ -4599,6 +6069,13 @@ func (x *DeleteServiceRequest) GetAllowMissing() bool { return false } +func (x *DeleteServiceRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Response for deleting an exposed sandbox service endpoint. type DeleteServiceResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -4609,7 +6086,7 @@ type DeleteServiceResponse struct { func (x *DeleteServiceResponse) Reset() { *x = DeleteServiceResponse{} - mi := &file_openshell_proto_msgTypes[62] + mi := &file_openshell_proto_msgTypes[73] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4621,7 +6098,7 @@ func (x *DeleteServiceResponse) String() string { func (*DeleteServiceResponse) ProtoMessage() {} func (x *DeleteServiceResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[62] + mi := &file_openshell_proto_msgTypes[73] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4634,7 +6111,7 @@ func (x *DeleteServiceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteServiceResponse.ProtoReflect.Descriptor instead. func (*DeleteServiceResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{62} + return file_openshell_proto_rawDescGZIP(), []int{73} } func (x *DeleteServiceResponse) GetOutcome() DeletionOutcome { @@ -4665,7 +6142,7 @@ type ServiceEndpoint struct { func (x *ServiceEndpoint) Reset() { *x = ServiceEndpoint{} - mi := &file_openshell_proto_msgTypes[63] + mi := &file_openshell_proto_msgTypes[74] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4677,7 +6154,7 @@ func (x *ServiceEndpoint) String() string { func (*ServiceEndpoint) ProtoMessage() {} func (x *ServiceEndpoint) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[63] + mi := &file_openshell_proto_msgTypes[74] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4690,7 +6167,7 @@ func (x *ServiceEndpoint) ProtoReflect() protoreflect.Message { // Deprecated: Use ServiceEndpoint.ProtoReflect.Descriptor instead. func (*ServiceEndpoint) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{63} + return file_openshell_proto_rawDescGZIP(), []int{74} } func (x *ServiceEndpoint) GetMetadata() *datamodelv1.ObjectMeta { @@ -4746,7 +6223,7 @@ type ServiceEndpointResponse struct { func (x *ServiceEndpointResponse) Reset() { *x = ServiceEndpointResponse{} - mi := &file_openshell_proto_msgTypes[64] + mi := &file_openshell_proto_msgTypes[75] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4758,7 +6235,7 @@ func (x *ServiceEndpointResponse) String() string { func (*ServiceEndpointResponse) ProtoMessage() {} func (x *ServiceEndpointResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[64] + mi := &file_openshell_proto_msgTypes[75] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4771,7 +6248,7 @@ func (x *ServiceEndpointResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ServiceEndpointResponse.ProtoReflect.Descriptor instead. func (*ServiceEndpointResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{64} + return file_openshell_proto_rawDescGZIP(), []int{75} } func (x *ServiceEndpointResponse) GetEndpoint() *ServiceEndpoint { @@ -4802,7 +6279,7 @@ type RevokeSshSessionRequest struct { func (x *RevokeSshSessionRequest) Reset() { *x = RevokeSshSessionRequest{} - mi := &file_openshell_proto_msgTypes[65] + mi := &file_openshell_proto_msgTypes[76] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4814,7 +6291,7 @@ func (x *RevokeSshSessionRequest) String() string { func (*RevokeSshSessionRequest) ProtoMessage() {} func (x *RevokeSshSessionRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[65] + mi := &file_openshell_proto_msgTypes[76] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4827,7 +6304,7 @@ func (x *RevokeSshSessionRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RevokeSshSessionRequest.ProtoReflect.Descriptor instead. func (*RevokeSshSessionRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{65} + return file_openshell_proto_rawDescGZIP(), []int{76} } func (x *RevokeSshSessionRequest) GetToken() string { @@ -4854,7 +6331,7 @@ type RevokeSshSessionResponse struct { func (x *RevokeSshSessionResponse) Reset() { *x = RevokeSshSessionResponse{} - mi := &file_openshell_proto_msgTypes[66] + mi := &file_openshell_proto_msgTypes[77] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4866,7 +6343,7 @@ func (x *RevokeSshSessionResponse) String() string { func (*RevokeSshSessionResponse) ProtoMessage() {} func (x *RevokeSshSessionResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[66] + mi := &file_openshell_proto_msgTypes[77] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4879,7 +6356,7 @@ func (x *RevokeSshSessionResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RevokeSshSessionResponse.ProtoReflect.Descriptor instead. func (*RevokeSshSessionResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{66} + return file_openshell_proto_rawDescGZIP(), []int{77} } func (x *RevokeSshSessionResponse) GetOutcome() DeletionOutcome { @@ -4922,7 +6399,7 @@ type ExecSandboxRequest struct { func (x *ExecSandboxRequest) Reset() { *x = ExecSandboxRequest{} - mi := &file_openshell_proto_msgTypes[67] + mi := &file_openshell_proto_msgTypes[78] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4934,7 +6411,7 @@ func (x *ExecSandboxRequest) String() string { func (*ExecSandboxRequest) ProtoMessage() {} func (x *ExecSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[67] + mi := &file_openshell_proto_msgTypes[78] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4947,7 +6424,7 @@ func (x *ExecSandboxRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxRequest.ProtoReflect.Descriptor instead. func (*ExecSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{67} + return file_openshell_proto_rawDescGZIP(), []int{78} } func (x *ExecSandboxRequest) GetSandboxId() string { @@ -5030,7 +6507,7 @@ type ExecSandboxStdout struct { func (x *ExecSandboxStdout) Reset() { *x = ExecSandboxStdout{} - mi := &file_openshell_proto_msgTypes[68] + mi := &file_openshell_proto_msgTypes[79] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5042,7 +6519,7 @@ func (x *ExecSandboxStdout) String() string { func (*ExecSandboxStdout) ProtoMessage() {} func (x *ExecSandboxStdout) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[68] + mi := &file_openshell_proto_msgTypes[79] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5055,7 +6532,7 @@ func (x *ExecSandboxStdout) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxStdout.ProtoReflect.Descriptor instead. func (*ExecSandboxStdout) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{68} + return file_openshell_proto_rawDescGZIP(), []int{79} } func (x *ExecSandboxStdout) GetData() []byte { @@ -5075,7 +6552,7 @@ type ExecSandboxStderr struct { func (x *ExecSandboxStderr) Reset() { *x = ExecSandboxStderr{} - mi := &file_openshell_proto_msgTypes[69] + mi := &file_openshell_proto_msgTypes[80] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5087,7 +6564,7 @@ func (x *ExecSandboxStderr) String() string { func (*ExecSandboxStderr) ProtoMessage() {} func (x *ExecSandboxStderr) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[69] + mi := &file_openshell_proto_msgTypes[80] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5100,7 +6577,7 @@ func (x *ExecSandboxStderr) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxStderr.ProtoReflect.Descriptor instead. func (*ExecSandboxStderr) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{69} + return file_openshell_proto_rawDescGZIP(), []int{80} } func (x *ExecSandboxStderr) GetData() []byte { @@ -5120,7 +6597,7 @@ type ExecSandboxExit struct { func (x *ExecSandboxExit) Reset() { *x = ExecSandboxExit{} - mi := &file_openshell_proto_msgTypes[70] + mi := &file_openshell_proto_msgTypes[81] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5132,7 +6609,7 @@ func (x *ExecSandboxExit) String() string { func (*ExecSandboxExit) ProtoMessage() {} func (x *ExecSandboxExit) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[70] + mi := &file_openshell_proto_msgTypes[81] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5145,7 +6622,7 @@ func (x *ExecSandboxExit) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxExit.ProtoReflect.Descriptor instead. func (*ExecSandboxExit) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{70} + return file_openshell_proto_rawDescGZIP(), []int{81} } func (x *ExecSandboxExit) GetExitCode() int32 { @@ -5170,7 +6647,7 @@ type ExecSandboxEvent struct { func (x *ExecSandboxEvent) Reset() { *x = ExecSandboxEvent{} - mi := &file_openshell_proto_msgTypes[71] + mi := &file_openshell_proto_msgTypes[82] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5182,7 +6659,7 @@ func (x *ExecSandboxEvent) String() string { func (*ExecSandboxEvent) ProtoMessage() {} func (x *ExecSandboxEvent) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[71] + mi := &file_openshell_proto_msgTypes[82] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5195,7 +6672,7 @@ func (x *ExecSandboxEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxEvent.ProtoReflect.Descriptor instead. func (*ExecSandboxEvent) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{71} + return file_openshell_proto_rawDescGZIP(), []int{82} } func (x *ExecSandboxEvent) GetPayload() isExecSandboxEvent_Payload { @@ -5277,7 +6754,7 @@ type TcpForwardInit struct { func (x *TcpForwardInit) Reset() { *x = TcpForwardInit{} - mi := &file_openshell_proto_msgTypes[72] + mi := &file_openshell_proto_msgTypes[83] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5289,7 +6766,7 @@ func (x *TcpForwardInit) String() string { func (*TcpForwardInit) ProtoMessage() {} func (x *TcpForwardInit) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[72] + mi := &file_openshell_proto_msgTypes[83] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5302,7 +6779,7 @@ func (x *TcpForwardInit) ProtoReflect() protoreflect.Message { // Deprecated: Use TcpForwardInit.ProtoReflect.Descriptor instead. func (*TcpForwardInit) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{72} + return file_openshell_proto_rawDescGZIP(), []int{83} } func (x *TcpForwardInit) GetSandboxId() string { @@ -5381,7 +6858,7 @@ type TcpForwardFrame struct { func (x *TcpForwardFrame) Reset() { *x = TcpForwardFrame{} - mi := &file_openshell_proto_msgTypes[73] + mi := &file_openshell_proto_msgTypes[84] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5393,7 +6870,7 @@ func (x *TcpForwardFrame) String() string { func (*TcpForwardFrame) ProtoMessage() {} func (x *TcpForwardFrame) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[73] + mi := &file_openshell_proto_msgTypes[84] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5406,7 +6883,7 @@ func (x *TcpForwardFrame) ProtoReflect() protoreflect.Message { // Deprecated: Use TcpForwardFrame.ProtoReflect.Descriptor instead. func (*TcpForwardFrame) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{73} + return file_openshell_proto_rawDescGZIP(), []int{84} } func (x *TcpForwardFrame) GetPayload() isTcpForwardFrame_Payload { @@ -5465,7 +6942,7 @@ type ExecSandboxInput struct { func (x *ExecSandboxInput) Reset() { *x = ExecSandboxInput{} - mi := &file_openshell_proto_msgTypes[74] + mi := &file_openshell_proto_msgTypes[85] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5477,7 +6954,7 @@ func (x *ExecSandboxInput) String() string { func (*ExecSandboxInput) ProtoMessage() {} func (x *ExecSandboxInput) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[74] + mi := &file_openshell_proto_msgTypes[85] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5490,7 +6967,7 @@ func (x *ExecSandboxInput) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxInput.ProtoReflect.Descriptor instead. func (*ExecSandboxInput) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{74} + return file_openshell_proto_rawDescGZIP(), []int{85} } func (x *ExecSandboxInput) GetPayload() isExecSandboxInput_Payload { @@ -5563,7 +7040,7 @@ type ExecSandboxWindowResize struct { func (x *ExecSandboxWindowResize) Reset() { *x = ExecSandboxWindowResize{} - mi := &file_openshell_proto_msgTypes[75] + mi := &file_openshell_proto_msgTypes[86] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5575,7 +7052,7 @@ func (x *ExecSandboxWindowResize) String() string { func (*ExecSandboxWindowResize) ProtoMessage() {} func (x *ExecSandboxWindowResize) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[75] + mi := &file_openshell_proto_msgTypes[86] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5588,7 +7065,7 @@ func (x *ExecSandboxWindowResize) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxWindowResize.ProtoReflect.Descriptor instead. func (*ExecSandboxWindowResize) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{75} + return file_openshell_proto_rawDescGZIP(), []int{86} } func (x *ExecSandboxWindowResize) GetCols() uint32 { @@ -5624,7 +7101,7 @@ type SshSession struct { func (x *SshSession) Reset() { *x = SshSession{} - mi := &file_openshell_proto_msgTypes[76] + mi := &file_openshell_proto_msgTypes[87] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5636,7 +7113,7 @@ func (x *SshSession) String() string { func (*SshSession) ProtoMessage() {} func (x *SshSession) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[76] + mi := &file_openshell_proto_msgTypes[87] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5649,7 +7126,7 @@ func (x *SshSession) ProtoReflect() protoreflect.Message { // Deprecated: Use SshSession.ProtoReflect.Descriptor instead. func (*SshSession) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{76} + return file_openshell_proto_rawDescGZIP(), []int{87} } func (x *SshSession) GetMetadata() *datamodelv1.ObjectMeta { @@ -5718,7 +7195,7 @@ type WatchSandboxRequest struct { func (x *WatchSandboxRequest) Reset() { *x = WatchSandboxRequest{} - mi := &file_openshell_proto_msgTypes[77] + mi := &file_openshell_proto_msgTypes[88] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5730,7 +7207,7 @@ func (x *WatchSandboxRequest) String() string { func (*WatchSandboxRequest) ProtoMessage() {} func (x *WatchSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[77] + mi := &file_openshell_proto_msgTypes[88] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5743,7 +7220,7 @@ func (x *WatchSandboxRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use WatchSandboxRequest.ProtoReflect.Descriptor instead. func (*WatchSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{77} + return file_openshell_proto_rawDescGZIP(), []int{88} } func (x *WatchSandboxRequest) GetId() string { @@ -5833,7 +7310,7 @@ type SandboxStreamEvent struct { func (x *SandboxStreamEvent) Reset() { *x = SandboxStreamEvent{} - mi := &file_openshell_proto_msgTypes[78] + mi := &file_openshell_proto_msgTypes[89] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5845,7 +7322,7 @@ func (x *SandboxStreamEvent) String() string { func (*SandboxStreamEvent) ProtoMessage() {} func (x *SandboxStreamEvent) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[78] + mi := &file_openshell_proto_msgTypes[89] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5858,7 +7335,7 @@ func (x *SandboxStreamEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxStreamEvent.ProtoReflect.Descriptor instead. func (*SandboxStreamEvent) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{78} + return file_openshell_proto_rawDescGZIP(), []int{89} } func (x *SandboxStreamEvent) GetPayload() isSandboxStreamEvent_Payload { @@ -5971,7 +7448,7 @@ type SandboxLogLine struct { func (x *SandboxLogLine) Reset() { *x = SandboxLogLine{} - mi := &file_openshell_proto_msgTypes[79] + mi := &file_openshell_proto_msgTypes[90] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5983,7 +7460,7 @@ func (x *SandboxLogLine) String() string { func (*SandboxLogLine) ProtoMessage() {} func (x *SandboxLogLine) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[79] + mi := &file_openshell_proto_msgTypes[90] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5996,7 +7473,7 @@ func (x *SandboxLogLine) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxLogLine.ProtoReflect.Descriptor instead. func (*SandboxLogLine) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{79} + return file_openshell_proto_rawDescGZIP(), []int{90} } func (x *SandboxLogLine) GetSandboxId() string { @@ -6057,7 +7534,7 @@ type SandboxStreamWarning struct { func (x *SandboxStreamWarning) Reset() { *x = SandboxStreamWarning{} - mi := &file_openshell_proto_msgTypes[80] + mi := &file_openshell_proto_msgTypes[91] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6069,7 +7546,7 @@ func (x *SandboxStreamWarning) String() string { func (*SandboxStreamWarning) ProtoMessage() {} func (x *SandboxStreamWarning) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[80] + mi := &file_openshell_proto_msgTypes[91] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6082,7 +7559,7 @@ func (x *SandboxStreamWarning) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxStreamWarning.ProtoReflect.Descriptor instead. func (*SandboxStreamWarning) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{80} + return file_openshell_proto_rawDescGZIP(), []int{91} } func (x *SandboxStreamWarning) GetMessage() string { @@ -6098,13 +7575,16 @@ type CreateProviderRequest struct { Provider *datamodelv1.Provider `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"` // Explicit workspace for the provider. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,4,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *CreateProviderRequest) Reset() { *x = CreateProviderRequest{} - mi := &file_openshell_proto_msgTypes[81] + mi := &file_openshell_proto_msgTypes[92] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6116,7 +7596,7 @@ func (x *CreateProviderRequest) String() string { func (*CreateProviderRequest) ProtoMessage() {} func (x *CreateProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[81] + mi := &file_openshell_proto_msgTypes[92] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6129,7 +7609,7 @@ func (x *CreateProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateProviderRequest.ProtoReflect.Descriptor instead. func (*CreateProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{81} + return file_openshell_proto_rawDescGZIP(), []int{92} } func (x *CreateProviderRequest) GetProvider() *datamodelv1.Provider { @@ -6146,6 +7626,13 @@ func (x *CreateProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelect return nil } +func (x *CreateProviderRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Get provider request. type GetProviderRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -6158,7 +7645,7 @@ type GetProviderRequest struct { func (x *GetProviderRequest) Reset() { *x = GetProviderRequest{} - mi := &file_openshell_proto_msgTypes[82] + mi := &file_openshell_proto_msgTypes[93] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6170,7 +7657,7 @@ func (x *GetProviderRequest) String() string { func (*GetProviderRequest) ProtoMessage() {} func (x *GetProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[82] + mi := &file_openshell_proto_msgTypes[93] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6183,7 +7670,7 @@ func (x *GetProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetProviderRequest.ProtoReflect.Descriptor instead. func (*GetProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{82} + return file_openshell_proto_rawDescGZIP(), []int{93} } func (x *GetProviderRequest) GetName() string { @@ -6217,7 +7704,7 @@ type ListProvidersRequest struct { func (x *ListProvidersRequest) Reset() { *x = ListProvidersRequest{} - mi := &file_openshell_proto_msgTypes[83] + mi := &file_openshell_proto_msgTypes[94] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6229,7 +7716,7 @@ func (x *ListProvidersRequest) String() string { func (*ListProvidersRequest) ProtoMessage() {} func (x *ListProvidersRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[83] + mi := &file_openshell_proto_msgTypes[94] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6242,7 +7729,7 @@ func (x *ListProvidersRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListProvidersRequest.ProtoReflect.Descriptor instead. func (*ListProvidersRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{83} + return file_openshell_proto_rawDescGZIP(), []int{94} } func (x *ListProvidersRequest) GetPageSize() int32 { @@ -6278,13 +7765,16 @@ type UpdateProviderRequest struct { ClearCredentialExpirationKeys []string `protobuf:"bytes,103,rep,name=clear_credential_expiration_keys,json=clearCredentialExpirationKeys,proto3" json:"clear_credential_expiration_keys,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,5,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *UpdateProviderRequest) Reset() { *x = UpdateProviderRequest{} - mi := &file_openshell_proto_msgTypes[84] + mi := &file_openshell_proto_msgTypes[95] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6296,7 +7786,7 @@ func (x *UpdateProviderRequest) String() string { func (*UpdateProviderRequest) ProtoMessage() {} func (x *UpdateProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[84] + mi := &file_openshell_proto_msgTypes[95] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6309,7 +7799,7 @@ func (x *UpdateProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateProviderRequest.ProtoReflect.Descriptor instead. func (*UpdateProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{84} + return file_openshell_proto_rawDescGZIP(), []int{95} } func (x *UpdateProviderRequest) GetProvider() *datamodelv1.Provider { @@ -6340,6 +7830,13 @@ func (x *UpdateProviderRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelect return nil } +func (x *UpdateProviderRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Delete provider request. type DeleteProviderRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -6347,13 +7844,16 @@ type DeleteProviderRequest struct { // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` AllowMissing bool `protobuf:"varint,4,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,5,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DeleteProviderRequest) Reset() { *x = DeleteProviderRequest{} - mi := &file_openshell_proto_msgTypes[85] + mi := &file_openshell_proto_msgTypes[96] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6365,7 +7865,7 @@ func (x *DeleteProviderRequest) String() string { func (*DeleteProviderRequest) ProtoMessage() {} func (x *DeleteProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[85] + mi := &file_openshell_proto_msgTypes[96] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6378,7 +7878,7 @@ func (x *DeleteProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderRequest.ProtoReflect.Descriptor instead. func (*DeleteProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{85} + return file_openshell_proto_rawDescGZIP(), []int{96} } func (x *DeleteProviderRequest) GetName() string { @@ -6402,17 +7902,29 @@ func (x *DeleteProviderRequest) GetAllowMissing() bool { return false } +func (x *DeleteProviderRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Provider response. type ProviderResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Provider *datamodelv1.Provider `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Provider *datamodelv1.Provider `protobuf:"bytes,1,opt,name=provider,proto3" json:"provider,omitempty"` + // Selection-time sandbox target set for an update, with one receipt per target. + // Sandboxes attached later are outside this operation's readiness result. + TargetReceipts []*ProviderMutationReceipt `protobuf:"bytes,2,rep,name=target_receipts,json=targetReceipts,proto3" json:"target_receipts,omitempty"` + // Identifies the update even when its target set is empty. + MutationId string `protobuf:"bytes,3,opt,name=mutation_id,json=mutationId,proto3" json:"mutation_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ProviderResponse) Reset() { *x = ProviderResponse{} - mi := &file_openshell_proto_msgTypes[86] + mi := &file_openshell_proto_msgTypes[97] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6424,7 +7936,7 @@ func (x *ProviderResponse) String() string { func (*ProviderResponse) ProtoMessage() {} func (x *ProviderResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[86] + mi := &file_openshell_proto_msgTypes[97] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6437,7 +7949,7 @@ func (x *ProviderResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderResponse.ProtoReflect.Descriptor instead. func (*ProviderResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{86} + return file_openshell_proto_rawDescGZIP(), []int{97} } func (x *ProviderResponse) GetProvider() *datamodelv1.Provider { @@ -6447,6 +7959,20 @@ func (x *ProviderResponse) GetProvider() *datamodelv1.Provider { return nil } +func (x *ProviderResponse) GetTargetReceipts() []*ProviderMutationReceipt { + if x != nil { + return x.TargetReceipts + } + return nil +} + +func (x *ProviderResponse) GetMutationId() string { + if x != nil { + return x.MutationId + } + return "" +} + // List providers response. type ListProvidersResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -6459,7 +7985,7 @@ type ListProvidersResponse struct { func (x *ListProvidersResponse) Reset() { *x = ListProvidersResponse{} - mi := &file_openshell_proto_msgTypes[87] + mi := &file_openshell_proto_msgTypes[98] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6471,7 +7997,7 @@ func (x *ListProvidersResponse) String() string { func (*ListProvidersResponse) ProtoMessage() {} func (x *ListProvidersResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[87] + mi := &file_openshell_proto_msgTypes[98] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6484,7 +8010,7 @@ func (x *ListProvidersResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListProvidersResponse.ProtoReflect.Descriptor instead. func (*ListProvidersResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{87} + return file_openshell_proto_rawDescGZIP(), []int{98} } func (x *ListProvidersResponse) GetProviders() []*datamodelv1.Provider { @@ -6519,7 +8045,7 @@ type ListProviderProfilesRequest struct { func (x *ListProviderProfilesRequest) Reset() { *x = ListProviderProfilesRequest{} - mi := &file_openshell_proto_msgTypes[88] + mi := &file_openshell_proto_msgTypes[99] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6531,7 +8057,7 @@ func (x *ListProviderProfilesRequest) String() string { func (*ListProviderProfilesRequest) ProtoMessage() {} func (x *ListProviderProfilesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[88] + mi := &file_openshell_proto_msgTypes[99] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6544,7 +8070,7 @@ func (x *ListProviderProfilesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListProviderProfilesRequest.ProtoReflect.Descriptor instead. func (*ListProviderProfilesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{88} + return file_openshell_proto_rawDescGZIP(), []int{99} } func (x *ListProviderProfilesRequest) GetPageSize() int32 { @@ -6582,7 +8108,7 @@ type GetProviderProfileRequest struct { func (x *GetProviderProfileRequest) Reset() { *x = GetProviderProfileRequest{} - mi := &file_openshell_proto_msgTypes[89] + mi := &file_openshell_proto_msgTypes[100] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6594,7 +8120,7 @@ func (x *GetProviderProfileRequest) String() string { func (*GetProviderProfileRequest) ProtoMessage() {} func (x *GetProviderProfileRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[89] + mi := &file_openshell_proto_msgTypes[100] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6607,7 +8133,7 @@ func (x *GetProviderProfileRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetProviderProfileRequest.ProtoReflect.Descriptor instead. func (*GetProviderProfileRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{89} + return file_openshell_proto_rawDescGZIP(), []int{100} } func (x *GetProviderProfileRequest) GetId() string { @@ -6635,7 +8161,7 @@ type ProviderProfileImportItem struct { func (x *ProviderProfileImportItem) Reset() { *x = ProviderProfileImportItem{} - mi := &file_openshell_proto_msgTypes[90] + mi := &file_openshell_proto_msgTypes[101] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6647,7 +8173,7 @@ func (x *ProviderProfileImportItem) String() string { func (*ProviderProfileImportItem) ProtoMessage() {} func (x *ProviderProfileImportItem) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[90] + mi := &file_openshell_proto_msgTypes[101] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6660,7 +8186,7 @@ func (x *ProviderProfileImportItem) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileImportItem.ProtoReflect.Descriptor instead. func (*ProviderProfileImportItem) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{90} + return file_openshell_proto_rawDescGZIP(), []int{101} } func (x *ProviderProfileImportItem) GetProfile() *ProviderProfile { @@ -6691,7 +8217,7 @@ type ProviderProfileDiagnostic struct { func (x *ProviderProfileDiagnostic) Reset() { *x = ProviderProfileDiagnostic{} - mi := &file_openshell_proto_msgTypes[91] + mi := &file_openshell_proto_msgTypes[102] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6703,7 +8229,7 @@ func (x *ProviderProfileDiagnostic) String() string { func (*ProviderProfileDiagnostic) ProtoMessage() {} func (x *ProviderProfileDiagnostic) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[91] + mi := &file_openshell_proto_msgTypes[102] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6716,7 +8242,7 @@ func (x *ProviderProfileDiagnostic) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileDiagnostic.ProtoReflect.Descriptor instead. func (*ProviderProfileDiagnostic) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{91} + return file_openshell_proto_rawDescGZIP(), []int{102} } func (x *ProviderProfileDiagnostic) GetSource() string { @@ -6773,7 +8299,7 @@ type ProviderCredentialTokenGrantAudienceOverride struct { func (x *ProviderCredentialTokenGrantAudienceOverride) Reset() { *x = ProviderCredentialTokenGrantAudienceOverride{} - mi := &file_openshell_proto_msgTypes[92] + mi := &file_openshell_proto_msgTypes[103] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6785,7 +8311,7 @@ func (x *ProviderCredentialTokenGrantAudienceOverride) String() string { func (*ProviderCredentialTokenGrantAudienceOverride) ProtoMessage() {} func (x *ProviderCredentialTokenGrantAudienceOverride) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[92] + mi := &file_openshell_proto_msgTypes[103] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6798,7 +8324,7 @@ func (x *ProviderCredentialTokenGrantAudienceOverride) ProtoReflect() protorefle // Deprecated: Use ProviderCredentialTokenGrantAudienceOverride.ProtoReflect.Descriptor instead. func (*ProviderCredentialTokenGrantAudienceOverride) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{92} + return file_openshell_proto_rawDescGZIP(), []int{103} } func (x *ProviderCredentialTokenGrantAudienceOverride) GetHost() string { @@ -6852,7 +8378,7 @@ type ProviderCredentialTokenGrantSubjectToken struct { func (x *ProviderCredentialTokenGrantSubjectToken) Reset() { *x = ProviderCredentialTokenGrantSubjectToken{} - mi := &file_openshell_proto_msgTypes[93] + mi := &file_openshell_proto_msgTypes[104] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6864,7 +8390,7 @@ func (x *ProviderCredentialTokenGrantSubjectToken) String() string { func (*ProviderCredentialTokenGrantSubjectToken) ProtoMessage() {} func (x *ProviderCredentialTokenGrantSubjectToken) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[93] + mi := &file_openshell_proto_msgTypes[104] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6877,7 +8403,7 @@ func (x *ProviderCredentialTokenGrantSubjectToken) ProtoReflect() protoreflect.M // Deprecated: Use ProviderCredentialTokenGrantSubjectToken.ProtoReflect.Descriptor instead. func (*ProviderCredentialTokenGrantSubjectToken) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{93} + return file_openshell_proto_rawDescGZIP(), []int{104} } func (x *ProviderCredentialTokenGrantSubjectToken) GetSource() string { @@ -6933,7 +8459,7 @@ type ProviderCredentialTokenGrant struct { func (x *ProviderCredentialTokenGrant) Reset() { *x = ProviderCredentialTokenGrant{} - mi := &file_openshell_proto_msgTypes[94] + mi := &file_openshell_proto_msgTypes[105] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6945,7 +8471,7 @@ func (x *ProviderCredentialTokenGrant) String() string { func (*ProviderCredentialTokenGrant) ProtoMessage() {} func (x *ProviderCredentialTokenGrant) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[94] + mi := &file_openshell_proto_msgTypes[105] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6958,7 +8484,7 @@ func (x *ProviderCredentialTokenGrant) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderCredentialTokenGrant.ProtoReflect.Descriptor instead. func (*ProviderCredentialTokenGrant) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{94} + return file_openshell_proto_rawDescGZIP(), []int{105} } func (x *ProviderCredentialTokenGrant) GetTokenEndpoint() string { @@ -7050,7 +8576,7 @@ type ProviderProfileCredential struct { func (x *ProviderProfileCredential) Reset() { *x = ProviderProfileCredential{} - mi := &file_openshell_proto_msgTypes[95] + mi := &file_openshell_proto_msgTypes[106] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7062,7 +8588,7 @@ func (x *ProviderProfileCredential) String() string { func (*ProviderProfileCredential) ProtoMessage() {} func (x *ProviderProfileCredential) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[95] + mi := &file_openshell_proto_msgTypes[106] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7075,7 +8601,7 @@ func (x *ProviderProfileCredential) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileCredential.ProtoReflect.Descriptor instead. func (*ProviderProfileCredential) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{95} + return file_openshell_proto_rawDescGZIP(), []int{106} } func (x *ProviderProfileCredential) GetName() string { @@ -7160,7 +8686,7 @@ type ProviderCredentialRefreshMaterial struct { func (x *ProviderCredentialRefreshMaterial) Reset() { *x = ProviderCredentialRefreshMaterial{} - mi := &file_openshell_proto_msgTypes[96] + mi := &file_openshell_proto_msgTypes[107] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7172,7 +8698,7 @@ func (x *ProviderCredentialRefreshMaterial) String() string { func (*ProviderCredentialRefreshMaterial) ProtoMessage() {} func (x *ProviderCredentialRefreshMaterial) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[96] + mi := &file_openshell_proto_msgTypes[107] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7185,7 +8711,7 @@ func (x *ProviderCredentialRefreshMaterial) ProtoReflect() protoreflect.Message // Deprecated: Use ProviderCredentialRefreshMaterial.ProtoReflect.Descriptor instead. func (*ProviderCredentialRefreshMaterial) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{96} + return file_openshell_proto_rawDescGZIP(), []int{107} } func (x *ProviderCredentialRefreshMaterial) GetName() string { @@ -7230,7 +8756,7 @@ type ProviderCredentialRefreshOutput struct { func (x *ProviderCredentialRefreshOutput) Reset() { *x = ProviderCredentialRefreshOutput{} - mi := &file_openshell_proto_msgTypes[97] + mi := &file_openshell_proto_msgTypes[108] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7242,7 +8768,7 @@ func (x *ProviderCredentialRefreshOutput) String() string { func (*ProviderCredentialRefreshOutput) ProtoMessage() {} func (x *ProviderCredentialRefreshOutput) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[97] + mi := &file_openshell_proto_msgTypes[108] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7255,7 +8781,7 @@ func (x *ProviderCredentialRefreshOutput) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderCredentialRefreshOutput.ProtoReflect.Descriptor instead. func (*ProviderCredentialRefreshOutput) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{97} + return file_openshell_proto_rawDescGZIP(), []int{108} } func (x *ProviderCredentialRefreshOutput) GetOutput() string { @@ -7287,7 +8813,7 @@ type ProviderCredentialRefresh struct { func (x *ProviderCredentialRefresh) Reset() { *x = ProviderCredentialRefresh{} - mi := &file_openshell_proto_msgTypes[98] + mi := &file_openshell_proto_msgTypes[109] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7299,7 +8825,7 @@ func (x *ProviderCredentialRefresh) String() string { func (*ProviderCredentialRefresh) ProtoMessage() {} func (x *ProviderCredentialRefresh) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[98] + mi := &file_openshell_proto_msgTypes[109] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7312,7 +8838,7 @@ func (x *ProviderCredentialRefresh) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderCredentialRefresh.ProtoReflect.Descriptor instead. func (*ProviderCredentialRefresh) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{98} + return file_openshell_proto_rawDescGZIP(), []int{109} } func (x *ProviderCredentialRefresh) GetStrategy() ProviderCredentialRefreshStrategy { @@ -7393,7 +8919,7 @@ type ProviderCredentialRefreshStatus struct { func (x *ProviderCredentialRefreshStatus) Reset() { *x = ProviderCredentialRefreshStatus{} - mi := &file_openshell_proto_msgTypes[99] + mi := &file_openshell_proto_msgTypes[110] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7405,7 +8931,7 @@ func (x *ProviderCredentialRefreshStatus) String() string { func (*ProviderCredentialRefreshStatus) ProtoMessage() {} func (x *ProviderCredentialRefreshStatus) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[99] + mi := &file_openshell_proto_msgTypes[110] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7418,7 +8944,7 @@ func (x *ProviderCredentialRefreshStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderCredentialRefreshStatus.ProtoReflect.Descriptor instead. func (*ProviderCredentialRefreshStatus) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{99} + return file_openshell_proto_rawDescGZIP(), []int{110} } func (x *ProviderCredentialRefreshStatus) GetProviderName() string { @@ -7523,7 +9049,7 @@ type ProviderProfileDiscovery struct { func (x *ProviderProfileDiscovery) Reset() { *x = ProviderProfileDiscovery{} - mi := &file_openshell_proto_msgTypes[100] + mi := &file_openshell_proto_msgTypes[111] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7535,7 +9061,7 @@ func (x *ProviderProfileDiscovery) String() string { func (*ProviderProfileDiscovery) ProtoMessage() {} func (x *ProviderProfileDiscovery) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[100] + mi := &file_openshell_proto_msgTypes[111] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7548,7 +9074,7 @@ func (x *ProviderProfileDiscovery) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileDiscovery.ProtoReflect.Descriptor instead. func (*ProviderProfileDiscovery) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{100} + return file_openshell_proto_rawDescGZIP(), []int{111} } func (x *ProviderProfileDiscovery) GetCredentials() []string { @@ -7570,7 +9096,7 @@ type GetProviderRefreshStatusRequest struct { func (x *GetProviderRefreshStatusRequest) Reset() { *x = GetProviderRefreshStatusRequest{} - mi := &file_openshell_proto_msgTypes[101] + mi := &file_openshell_proto_msgTypes[112] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7582,7 +9108,7 @@ func (x *GetProviderRefreshStatusRequest) String() string { func (*GetProviderRefreshStatusRequest) ProtoMessage() {} func (x *GetProviderRefreshStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[101] + mi := &file_openshell_proto_msgTypes[112] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7595,7 +9121,7 @@ func (x *GetProviderRefreshStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetProviderRefreshStatusRequest.ProtoReflect.Descriptor instead. func (*GetProviderRefreshStatusRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{101} + return file_openshell_proto_rawDescGZIP(), []int{112} } func (x *GetProviderRefreshStatusRequest) GetProvider() string { @@ -7628,7 +9154,7 @@ type GetProviderRefreshStatusResponse struct { func (x *GetProviderRefreshStatusResponse) Reset() { *x = GetProviderRefreshStatusResponse{} - mi := &file_openshell_proto_msgTypes[102] + mi := &file_openshell_proto_msgTypes[113] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7640,7 +9166,7 @@ func (x *GetProviderRefreshStatusResponse) String() string { func (*GetProviderRefreshStatusResponse) ProtoMessage() {} func (x *GetProviderRefreshStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[102] + mi := &file_openshell_proto_msgTypes[113] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7653,7 +9179,7 @@ func (x *GetProviderRefreshStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetProviderRefreshStatusResponse.ProtoReflect.Descriptor instead. func (*GetProviderRefreshStatusResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{102} + return file_openshell_proto_rawDescGZIP(), []int{113} } func (x *GetProviderRefreshStatusResponse) GetCredentials() []*ProviderCredentialRefreshStatus { @@ -7676,13 +9202,16 @@ type ConfigureProviderRefreshRequest struct { ExpirationTime *timestamppb.Timestamp `protobuf:"bytes,106,opt,name=expiration_time,json=expirationTime,proto3" json:"expiration_time,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,8,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,9,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ConfigureProviderRefreshRequest) Reset() { *x = ConfigureProviderRefreshRequest{} - mi := &file_openshell_proto_msgTypes[103] + mi := &file_openshell_proto_msgTypes[114] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7694,7 +9223,7 @@ func (x *ConfigureProviderRefreshRequest) String() string { func (*ConfigureProviderRefreshRequest) ProtoMessage() {} func (x *ConfigureProviderRefreshRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[103] + mi := &file_openshell_proto_msgTypes[114] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7707,7 +9236,7 @@ func (x *ConfigureProviderRefreshRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ConfigureProviderRefreshRequest.ProtoReflect.Descriptor instead. func (*ConfigureProviderRefreshRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{103} + return file_openshell_proto_rawDescGZIP(), []int{114} } func (x *ConfigureProviderRefreshRequest) GetProvider() string { @@ -7759,6 +9288,13 @@ func (x *ConfigureProviderRefreshRequest) GetWorkspaceScope() *datamodelv1.Works return nil } +func (x *ConfigureProviderRefreshRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type ConfigureProviderRefreshResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Status *ProviderCredentialRefreshStatus `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` @@ -7768,7 +9304,7 @@ type ConfigureProviderRefreshResponse struct { func (x *ConfigureProviderRefreshResponse) Reset() { *x = ConfigureProviderRefreshResponse{} - mi := &file_openshell_proto_msgTypes[104] + mi := &file_openshell_proto_msgTypes[115] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7780,7 +9316,7 @@ func (x *ConfigureProviderRefreshResponse) String() string { func (*ConfigureProviderRefreshResponse) ProtoMessage() {} func (x *ConfigureProviderRefreshResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[104] + mi := &file_openshell_proto_msgTypes[115] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7793,7 +9329,7 @@ func (x *ConfigureProviderRefreshResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ConfigureProviderRefreshResponse.ProtoReflect.Descriptor instead. func (*ConfigureProviderRefreshResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{104} + return file_openshell_proto_rawDescGZIP(), []int{115} } func (x *ConfigureProviderRefreshResponse) GetStatus() *ProviderCredentialRefreshStatus { @@ -7809,13 +9345,16 @@ type RotateProviderCredentialRequest struct { CredentialKey string `protobuf:"bytes,2,opt,name=credential_key,json=credentialKey,proto3" json:"credential_key,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,5,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RotateProviderCredentialRequest) Reset() { *x = RotateProviderCredentialRequest{} - mi := &file_openshell_proto_msgTypes[105] + mi := &file_openshell_proto_msgTypes[116] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7827,7 +9366,7 @@ func (x *RotateProviderCredentialRequest) String() string { func (*RotateProviderCredentialRequest) ProtoMessage() {} func (x *RotateProviderCredentialRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[105] + mi := &file_openshell_proto_msgTypes[116] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7840,7 +9379,7 @@ func (x *RotateProviderCredentialRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RotateProviderCredentialRequest.ProtoReflect.Descriptor instead. func (*RotateProviderCredentialRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{105} + return file_openshell_proto_rawDescGZIP(), []int{116} } func (x *RotateProviderCredentialRequest) GetProvider() string { @@ -7864,6 +9403,13 @@ func (x *RotateProviderCredentialRequest) GetWorkspaceScope() *datamodelv1.Works return nil } +func (x *RotateProviderCredentialRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type RotateProviderCredentialResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Status *ProviderCredentialRefreshStatus `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` @@ -7873,7 +9419,7 @@ type RotateProviderCredentialResponse struct { func (x *RotateProviderCredentialResponse) Reset() { *x = RotateProviderCredentialResponse{} - mi := &file_openshell_proto_msgTypes[106] + mi := &file_openshell_proto_msgTypes[117] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7885,7 +9431,7 @@ func (x *RotateProviderCredentialResponse) String() string { func (*RotateProviderCredentialResponse) ProtoMessage() {} func (x *RotateProviderCredentialResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[106] + mi := &file_openshell_proto_msgTypes[117] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7898,7 +9444,7 @@ func (x *RotateProviderCredentialResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RotateProviderCredentialResponse.ProtoReflect.Descriptor instead. func (*RotateProviderCredentialResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{106} + return file_openshell_proto_rawDescGZIP(), []int{117} } func (x *RotateProviderCredentialResponse) GetStatus() *ProviderCredentialRefreshStatus { @@ -7915,13 +9461,16 @@ type DeleteProviderRefreshRequest struct { // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` AllowMissing bool `protobuf:"varint,5,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,6,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *DeleteProviderRefreshRequest) Reset() { *x = DeleteProviderRefreshRequest{} - mi := &file_openshell_proto_msgTypes[107] + mi := &file_openshell_proto_msgTypes[118] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7933,7 +9482,7 @@ func (x *DeleteProviderRefreshRequest) String() string { func (*DeleteProviderRefreshRequest) ProtoMessage() {} func (x *DeleteProviderRefreshRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[107] + mi := &file_openshell_proto_msgTypes[118] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7946,7 +9495,7 @@ func (x *DeleteProviderRefreshRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderRefreshRequest.ProtoReflect.Descriptor instead. func (*DeleteProviderRefreshRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{107} + return file_openshell_proto_rawDescGZIP(), []int{118} } func (x *DeleteProviderRefreshRequest) GetProvider() string { @@ -7977,6 +9526,13 @@ func (x *DeleteProviderRefreshRequest) GetAllowMissing() bool { return false } +func (x *DeleteProviderRefreshRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type DeleteProviderRefreshResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Outcome DeletionOutcome `protobuf:"varint,2,opt,name=outcome,proto3,enum=openshell.v1.DeletionOutcome" json:"outcome,omitempty"` @@ -7986,7 +9542,7 @@ type DeleteProviderRefreshResponse struct { func (x *DeleteProviderRefreshResponse) Reset() { *x = DeleteProviderRefreshResponse{} - mi := &file_openshell_proto_msgTypes[108] + mi := &file_openshell_proto_msgTypes[119] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7998,7 +9554,7 @@ func (x *DeleteProviderRefreshResponse) String() string { func (*DeleteProviderRefreshResponse) ProtoMessage() {} func (x *DeleteProviderRefreshResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[108] + mi := &file_openshell_proto_msgTypes[119] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8011,7 +9567,7 @@ func (x *DeleteProviderRefreshResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderRefreshResponse.ProtoReflect.Descriptor instead. func (*DeleteProviderRefreshResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{108} + return file_openshell_proto_rawDescGZIP(), []int{119} } func (x *DeleteProviderRefreshResponse) GetOutcome() DeletionOutcome { @@ -8051,7 +9607,7 @@ type ProviderProfile struct { func (x *ProviderProfile) Reset() { *x = ProviderProfile{} - mi := &file_openshell_proto_msgTypes[109] + mi := &file_openshell_proto_msgTypes[120] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8063,7 +9619,7 @@ func (x *ProviderProfile) String() string { func (*ProviderProfile) ProtoMessage() {} func (x *ProviderProfile) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[109] + mi := &file_openshell_proto_msgTypes[120] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8076,7 +9632,7 @@ func (x *ProviderProfile) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfile.ProtoReflect.Descriptor instead. func (*ProviderProfile) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{109} + return file_openshell_proto_rawDescGZIP(), []int{120} } func (x *ProviderProfile) GetId() string { @@ -8180,7 +9736,7 @@ type ProviderProfileResponse struct { func (x *ProviderProfileResponse) Reset() { *x = ProviderProfileResponse{} - mi := &file_openshell_proto_msgTypes[110] + mi := &file_openshell_proto_msgTypes[121] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8192,7 +9748,7 @@ func (x *ProviderProfileResponse) String() string { func (*ProviderProfileResponse) ProtoMessage() {} func (x *ProviderProfileResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[110] + mi := &file_openshell_proto_msgTypes[121] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8205,7 +9761,7 @@ func (x *ProviderProfileResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileResponse.ProtoReflect.Descriptor instead. func (*ProviderProfileResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{110} + return file_openshell_proto_rawDescGZIP(), []int{121} } func (x *ProviderProfileResponse) GetProfile() *ProviderProfile { @@ -8227,7 +9783,7 @@ type ListProviderProfilesResponse struct { func (x *ListProviderProfilesResponse) Reset() { *x = ListProviderProfilesResponse{} - mi := &file_openshell_proto_msgTypes[111] + mi := &file_openshell_proto_msgTypes[122] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8239,7 +9795,7 @@ func (x *ListProviderProfilesResponse) String() string { func (*ListProviderProfilesResponse) ProtoMessage() {} func (x *ListProviderProfilesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[111] + mi := &file_openshell_proto_msgTypes[122] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8252,7 +9808,7 @@ func (x *ListProviderProfilesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListProviderProfilesResponse.ProtoReflect.Descriptor instead. func (*ListProviderProfilesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{111} + return file_openshell_proto_rawDescGZIP(), []int{122} } func (x *ListProviderProfilesResponse) GetProfiles() []*ProviderProfile { @@ -8275,14 +9831,17 @@ type ImportProviderProfilesRequest struct { Profiles []*ProviderProfileImportItem `protobuf:"bytes,1,rep,name=profiles,proto3" json:"profiles,omitempty"` // Workspace scope. When set, profiles are workspace-scoped (Workspace Admin). // When empty, profiles are platform-scoped (Platform Admin). - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` + Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,3,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ImportProviderProfilesRequest) Reset() { *x = ImportProviderProfilesRequest{} - mi := &file_openshell_proto_msgTypes[112] + mi := &file_openshell_proto_msgTypes[123] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8294,7 +9853,7 @@ func (x *ImportProviderProfilesRequest) String() string { func (*ImportProviderProfilesRequest) ProtoMessage() {} func (x *ImportProviderProfilesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[112] + mi := &file_openshell_proto_msgTypes[123] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8307,7 +9866,7 @@ func (x *ImportProviderProfilesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ImportProviderProfilesRequest.ProtoReflect.Descriptor instead. func (*ImportProviderProfilesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{112} + return file_openshell_proto_rawDescGZIP(), []int{123} } func (x *ImportProviderProfilesRequest) GetProfiles() []*ProviderProfileImportItem { @@ -8324,6 +9883,13 @@ func (x *ImportProviderProfilesRequest) GetWorkspace() string { return "" } +func (x *ImportProviderProfilesRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Import custom provider profiles response. type ImportProviderProfilesResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -8336,7 +9902,7 @@ type ImportProviderProfilesResponse struct { func (x *ImportProviderProfilesResponse) Reset() { *x = ImportProviderProfilesResponse{} - mi := &file_openshell_proto_msgTypes[113] + mi := &file_openshell_proto_msgTypes[124] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8348,7 +9914,7 @@ func (x *ImportProviderProfilesResponse) String() string { func (*ImportProviderProfilesResponse) ProtoMessage() {} func (x *ImportProviderProfilesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[113] + mi := &file_openshell_proto_msgTypes[124] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8361,7 +9927,7 @@ func (x *ImportProviderProfilesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ImportProviderProfilesResponse.ProtoReflect.Descriptor instead. func (*ImportProviderProfilesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{113} + return file_openshell_proto_rawDescGZIP(), []int{124} } func (x *ImportProviderProfilesResponse) GetDiagnostics() []*ProviderProfileDiagnostic { @@ -8398,14 +9964,17 @@ type UpdateProviderProfilesRequest struct { Id string `protobuf:"bytes,3,opt,name=id,proto3" json:"id,omitempty"` // Workspace scope. When set, targets workspace-scoped profile. When empty, // targets platform-scoped profile. - Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` + Workspace string `protobuf:"bytes,4,opt,name=workspace,proto3" json:"workspace,omitempty"` + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,5,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *UpdateProviderProfilesRequest) Reset() { *x = UpdateProviderProfilesRequest{} - mi := &file_openshell_proto_msgTypes[114] + mi := &file_openshell_proto_msgTypes[125] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8417,7 +9986,7 @@ func (x *UpdateProviderProfilesRequest) String() string { func (*UpdateProviderProfilesRequest) ProtoMessage() {} func (x *UpdateProviderProfilesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[114] + mi := &file_openshell_proto_msgTypes[125] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8430,7 +9999,7 @@ func (x *UpdateProviderProfilesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateProviderProfilesRequest.ProtoReflect.Descriptor instead. func (*UpdateProviderProfilesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{114} + return file_openshell_proto_rawDescGZIP(), []int{125} } func (x *UpdateProviderProfilesRequest) GetProfile() *ProviderProfileImportItem { @@ -8461,6 +10030,13 @@ func (x *UpdateProviderProfilesRequest) GetWorkspace() string { return "" } +func (x *UpdateProviderProfilesRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Update one custom provider profile response. type UpdateProviderProfilesResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -8473,7 +10049,7 @@ type UpdateProviderProfilesResponse struct { func (x *UpdateProviderProfilesResponse) Reset() { *x = UpdateProviderProfilesResponse{} - mi := &file_openshell_proto_msgTypes[115] + mi := &file_openshell_proto_msgTypes[126] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8485,7 +10061,7 @@ func (x *UpdateProviderProfilesResponse) String() string { func (*UpdateProviderProfilesResponse) ProtoMessage() {} func (x *UpdateProviderProfilesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[115] + mi := &file_openshell_proto_msgTypes[126] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8498,7 +10074,7 @@ func (x *UpdateProviderProfilesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateProviderProfilesResponse.ProtoReflect.Descriptor instead. func (*UpdateProviderProfilesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{115} + return file_openshell_proto_rawDescGZIP(), []int{126} } func (x *UpdateProviderProfilesResponse) GetDiagnostics() []*ProviderProfileDiagnostic { @@ -8535,7 +10111,7 @@ type LintProviderProfilesRequest struct { func (x *LintProviderProfilesRequest) Reset() { *x = LintProviderProfilesRequest{} - mi := &file_openshell_proto_msgTypes[116] + mi := &file_openshell_proto_msgTypes[127] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8547,7 +10123,7 @@ func (x *LintProviderProfilesRequest) String() string { func (*LintProviderProfilesRequest) ProtoMessage() {} func (x *LintProviderProfilesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[116] + mi := &file_openshell_proto_msgTypes[127] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8560,7 +10136,7 @@ func (x *LintProviderProfilesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use LintProviderProfilesRequest.ProtoReflect.Descriptor instead. func (*LintProviderProfilesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{116} + return file_openshell_proto_rawDescGZIP(), []int{127} } func (x *LintProviderProfilesRequest) GetProfiles() []*ProviderProfileImportItem { @@ -8588,7 +10164,7 @@ type LintProviderProfilesResponse struct { func (x *LintProviderProfilesResponse) Reset() { *x = LintProviderProfilesResponse{} - mi := &file_openshell_proto_msgTypes[117] + mi := &file_openshell_proto_msgTypes[128] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8600,7 +10176,7 @@ func (x *LintProviderProfilesResponse) String() string { func (*LintProviderProfilesResponse) ProtoMessage() {} func (x *LintProviderProfilesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[117] + mi := &file_openshell_proto_msgTypes[128] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8613,7 +10189,7 @@ func (x *LintProviderProfilesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use LintProviderProfilesResponse.ProtoReflect.Descriptor instead. func (*LintProviderProfilesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{117} + return file_openshell_proto_rawDescGZIP(), []int{128} } func (x *LintProviderProfilesResponse) GetDiagnostics() []*ProviderProfileDiagnostic { @@ -8640,7 +10216,7 @@ type DeleteProviderResponse struct { func (x *DeleteProviderResponse) Reset() { *x = DeleteProviderResponse{} - mi := &file_openshell_proto_msgTypes[118] + mi := &file_openshell_proto_msgTypes[129] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8652,7 +10228,7 @@ func (x *DeleteProviderResponse) String() string { func (*DeleteProviderResponse) ProtoMessage() {} func (x *DeleteProviderResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[118] + mi := &file_openshell_proto_msgTypes[129] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8665,7 +10241,7 @@ func (x *DeleteProviderResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderResponse.ProtoReflect.Descriptor instead. func (*DeleteProviderResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{118} + return file_openshell_proto_rawDescGZIP(), []int{129} } func (x *DeleteProviderResponse) GetOutcome() DeletionOutcome { @@ -8681,15 +10257,18 @@ type DeleteProviderProfileRequest struct { Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // Workspace scope. When set, targets workspace-scoped profile. When empty, // targets platform-scoped profile. - Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` - AllowMissing bool `protobuf:"varint,3,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` + Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` + AllowMissing bool `protobuf:"varint,3,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,4,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *DeleteProviderProfileRequest) Reset() { *x = DeleteProviderProfileRequest{} - mi := &file_openshell_proto_msgTypes[119] + mi := &file_openshell_proto_msgTypes[130] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8701,7 +10280,7 @@ func (x *DeleteProviderProfileRequest) String() string { func (*DeleteProviderProfileRequest) ProtoMessage() {} func (x *DeleteProviderProfileRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[119] + mi := &file_openshell_proto_msgTypes[130] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8714,7 +10293,7 @@ func (x *DeleteProviderProfileRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderProfileRequest.ProtoReflect.Descriptor instead. func (*DeleteProviderProfileRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{119} + return file_openshell_proto_rawDescGZIP(), []int{130} } func (x *DeleteProviderProfileRequest) GetId() string { @@ -8738,6 +10317,13 @@ func (x *DeleteProviderProfileRequest) GetAllowMissing() bool { return false } +func (x *DeleteProviderProfileRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Delete custom provider profile response. type DeleteProviderProfileResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -8748,7 +10334,7 @@ type DeleteProviderProfileResponse struct { func (x *DeleteProviderProfileResponse) Reset() { *x = DeleteProviderProfileResponse{} - mi := &file_openshell_proto_msgTypes[120] + mi := &file_openshell_proto_msgTypes[131] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8760,7 +10346,7 @@ func (x *DeleteProviderProfileResponse) String() string { func (*DeleteProviderProfileResponse) ProtoMessage() {} func (x *DeleteProviderProfileResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[120] + mi := &file_openshell_proto_msgTypes[131] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8773,7 +10359,7 @@ func (x *DeleteProviderProfileResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderProfileResponse.ProtoReflect.Descriptor instead. func (*DeleteProviderProfileResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{120} + return file_openshell_proto_rawDescGZIP(), []int{131} } func (x *DeleteProviderProfileResponse) GetOutcome() DeletionOutcome { @@ -8798,7 +10384,7 @@ type GetSandboxProviderEnvironmentRequest struct { func (x *GetSandboxProviderEnvironmentRequest) Reset() { *x = GetSandboxProviderEnvironmentRequest{} - mi := &file_openshell_proto_msgTypes[121] + mi := &file_openshell_proto_msgTypes[132] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8810,7 +10396,7 @@ func (x *GetSandboxProviderEnvironmentRequest) String() string { func (*GetSandboxProviderEnvironmentRequest) ProtoMessage() {} func (x *GetSandboxProviderEnvironmentRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[121] + mi := &file_openshell_proto_msgTypes[132] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8823,7 +10409,7 @@ func (x *GetSandboxProviderEnvironmentRequest) ProtoReflect() protoreflect.Messa // Deprecated: Use GetSandboxProviderEnvironmentRequest.ProtoReflect.Descriptor instead. func (*GetSandboxProviderEnvironmentRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{121} + return file_openshell_proto_rawDescGZIP(), []int{132} } func (x *GetSandboxProviderEnvironmentRequest) GetSandboxId() string { @@ -8852,7 +10438,7 @@ type StaticCredentialEndpointBinding struct { func (x *StaticCredentialEndpointBinding) Reset() { *x = StaticCredentialEndpointBinding{} - mi := &file_openshell_proto_msgTypes[122] + mi := &file_openshell_proto_msgTypes[133] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8864,7 +10450,7 @@ func (x *StaticCredentialEndpointBinding) String() string { func (*StaticCredentialEndpointBinding) ProtoMessage() {} func (x *StaticCredentialEndpointBinding) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[122] + mi := &file_openshell_proto_msgTypes[133] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8877,7 +10463,7 @@ func (x *StaticCredentialEndpointBinding) ProtoReflect() protoreflect.Message { // Deprecated: Use StaticCredentialEndpointBinding.ProtoReflect.Descriptor instead. func (*StaticCredentialEndpointBinding) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{122} + return file_openshell_proto_rawDescGZIP(), []int{133} } func (x *StaticCredentialEndpointBinding) GetHost() string { @@ -8921,7 +10507,7 @@ type StaticCredentialBinding struct { func (x *StaticCredentialBinding) Reset() { *x = StaticCredentialBinding{} - mi := &file_openshell_proto_msgTypes[123] + mi := &file_openshell_proto_msgTypes[134] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8933,7 +10519,7 @@ func (x *StaticCredentialBinding) String() string { func (*StaticCredentialBinding) ProtoMessage() {} func (x *StaticCredentialBinding) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[123] + mi := &file_openshell_proto_msgTypes[134] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8946,7 +10532,7 @@ func (x *StaticCredentialBinding) ProtoReflect() protoreflect.Message { // Deprecated: Use StaticCredentialBinding.ProtoReflect.Descriptor instead. func (*StaticCredentialBinding) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{123} + return file_openshell_proto_rawDescGZIP(), []int{134} } func (x *StaticCredentialBinding) GetEndpoints() []*StaticCredentialEndpointBinding { @@ -8991,13 +10577,19 @@ type GetSandboxProviderEnvironmentResponse struct { // Environment variables that contain provider configuration rather than // credentials and therefore do not require endpoint-scoped resolution. NonSecretEnvironmentKeys []string `protobuf:"bytes,6,rep,name=non_secret_environment_keys,json=nonSecretEnvironmentKeys,proto3" json:"non_secret_environment_keys,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Attachment identity captured with the returned provider records. + ProviderAttachmentEpoch string `protobuf:"bytes,7,opt,name=provider_attachment_epoch,json=providerAttachmentEpoch,proto3" json:"provider_attachment_epoch,omitempty"` + // Effective policy identity used to derive this snapshot's endpoint bindings. + PolicyHash string `protobuf:"bytes,8,opt,name=policy_hash,json=policyHash,proto3" json:"policy_hash,omitempty"` + // Nonzero when material was withheld; installing an empty map is not readiness. + ReadinessReason ProviderReadinessReason `protobuf:"varint,9,opt,name=readiness_reason,json=readinessReason,proto3,enum=openshell.v1.ProviderReadinessReason" json:"readiness_reason,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetSandboxProviderEnvironmentResponse) Reset() { *x = GetSandboxProviderEnvironmentResponse{} - mi := &file_openshell_proto_msgTypes[124] + mi := &file_openshell_proto_msgTypes[135] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9009,7 +10601,7 @@ func (x *GetSandboxProviderEnvironmentResponse) String() string { func (*GetSandboxProviderEnvironmentResponse) ProtoMessage() {} func (x *GetSandboxProviderEnvironmentResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[124] + mi := &file_openshell_proto_msgTypes[135] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9022,7 +10614,7 @@ func (x *GetSandboxProviderEnvironmentResponse) ProtoReflect() protoreflect.Mess // Deprecated: Use GetSandboxProviderEnvironmentResponse.ProtoReflect.Descriptor instead. func (*GetSandboxProviderEnvironmentResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{124} + return file_openshell_proto_rawDescGZIP(), []int{135} } func (x *GetSandboxProviderEnvironmentResponse) GetEnvironment() map[string]string { @@ -9067,6 +10659,27 @@ func (x *GetSandboxProviderEnvironmentResponse) GetNonSecretEnvironmentKeys() [] return nil } +func (x *GetSandboxProviderEnvironmentResponse) GetProviderAttachmentEpoch() string { + if x != nil { + return x.ProviderAttachmentEpoch + } + return "" +} + +func (x *GetSandboxProviderEnvironmentResponse) GetPolicyHash() string { + if x != nil { + return x.PolicyHash + } + return "" +} + +func (x *GetSandboxProviderEnvironmentResponse) GetReadinessReason() ProviderReadinessReason { + if x != nil { + return x.ReadinessReason + } + return ProviderReadinessReason_PROVIDER_READINESS_REASON_UNSPECIFIED +} + type ExchangeProviderSubjectTokenRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // The sandbox ID. Must match the authenticated sandbox principal. @@ -9084,7 +10697,7 @@ type ExchangeProviderSubjectTokenRequest struct { func (x *ExchangeProviderSubjectTokenRequest) Reset() { *x = ExchangeProviderSubjectTokenRequest{} - mi := &file_openshell_proto_msgTypes[125] + mi := &file_openshell_proto_msgTypes[136] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9096,7 +10709,7 @@ func (x *ExchangeProviderSubjectTokenRequest) String() string { func (*ExchangeProviderSubjectTokenRequest) ProtoMessage() {} func (x *ExchangeProviderSubjectTokenRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[125] + mi := &file_openshell_proto_msgTypes[136] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9109,7 +10722,7 @@ func (x *ExchangeProviderSubjectTokenRequest) ProtoReflect() protoreflect.Messag // Deprecated: Use ExchangeProviderSubjectTokenRequest.ProtoReflect.Descriptor instead. func (*ExchangeProviderSubjectTokenRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{125} + return file_openshell_proto_rawDescGZIP(), []int{136} } func (x *ExchangeProviderSubjectTokenRequest) GetSandboxId() string { @@ -9151,7 +10764,7 @@ type ExchangeProviderSubjectTokenResponse struct { func (x *ExchangeProviderSubjectTokenResponse) Reset() { *x = ExchangeProviderSubjectTokenResponse{} - mi := &file_openshell_proto_msgTypes[126] + mi := &file_openshell_proto_msgTypes[137] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9163,7 +10776,7 @@ func (x *ExchangeProviderSubjectTokenResponse) String() string { func (*ExchangeProviderSubjectTokenResponse) ProtoMessage() {} func (x *ExchangeProviderSubjectTokenResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[126] + mi := &file_openshell_proto_msgTypes[137] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9176,7 +10789,7 @@ func (x *ExchangeProviderSubjectTokenResponse) ProtoReflect() protoreflect.Messa // Deprecated: Use ExchangeProviderSubjectTokenResponse.ProtoReflect.Descriptor instead. func (*ExchangeProviderSubjectTokenResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{126} + return file_openshell_proto_rawDescGZIP(), []int{137} } func (x *ExchangeProviderSubjectTokenResponse) GetAccessToken() string { @@ -9242,13 +10855,16 @@ type UpdateConfigRequest struct { // Explicit workspace scope for sandbox-scoped updates. Omit only when // `global` is true; the all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,11,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,12,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *UpdateConfigRequest) Reset() { *x = UpdateConfigRequest{} - mi := &file_openshell_proto_msgTypes[127] + mi := &file_openshell_proto_msgTypes[138] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9260,7 +10876,7 @@ func (x *UpdateConfigRequest) String() string { func (*UpdateConfigRequest) ProtoMessage() {} func (x *UpdateConfigRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[127] + mi := &file_openshell_proto_msgTypes[138] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9273,7 +10889,7 @@ func (x *UpdateConfigRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateConfigRequest.ProtoReflect.Descriptor instead. func (*UpdateConfigRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{127} + return file_openshell_proto_rawDescGZIP(), []int{138} } func (x *UpdateConfigRequest) GetName() string { @@ -9346,6 +10962,13 @@ func (x *UpdateConfigRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelector return nil } +func (x *UpdateConfigRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type PolicyMergeOperation struct { state protoimpl.MessageState `protogen:"open.v1"` // Types that are valid to be assigned to Operation: @@ -9363,7 +10986,7 @@ type PolicyMergeOperation struct { func (x *PolicyMergeOperation) Reset() { *x = PolicyMergeOperation{} - mi := &file_openshell_proto_msgTypes[128] + mi := &file_openshell_proto_msgTypes[139] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9375,7 +10998,7 @@ func (x *PolicyMergeOperation) String() string { func (*PolicyMergeOperation) ProtoMessage() {} func (x *PolicyMergeOperation) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[128] + mi := &file_openshell_proto_msgTypes[139] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9388,7 +11011,7 @@ func (x *PolicyMergeOperation) ProtoReflect() protoreflect.Message { // Deprecated: Use PolicyMergeOperation.ProtoReflect.Descriptor instead. func (*PolicyMergeOperation) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{128} + return file_openshell_proto_rawDescGZIP(), []int{139} } func (x *PolicyMergeOperation) GetOperation() isPolicyMergeOperation_Operation { @@ -9502,7 +11125,7 @@ type AddNetworkRule struct { func (x *AddNetworkRule) Reset() { *x = AddNetworkRule{} - mi := &file_openshell_proto_msgTypes[129] + mi := &file_openshell_proto_msgTypes[140] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9514,7 +11137,7 @@ func (x *AddNetworkRule) String() string { func (*AddNetworkRule) ProtoMessage() {} func (x *AddNetworkRule) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[129] + mi := &file_openshell_proto_msgTypes[140] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9527,7 +11150,7 @@ func (x *AddNetworkRule) ProtoReflect() protoreflect.Message { // Deprecated: Use AddNetworkRule.ProtoReflect.Descriptor instead. func (*AddNetworkRule) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{129} + return file_openshell_proto_rawDescGZIP(), []int{140} } func (x *AddNetworkRule) GetRuleName() string { @@ -9555,7 +11178,7 @@ type RemoveNetworkEndpoint struct { func (x *RemoveNetworkEndpoint) Reset() { *x = RemoveNetworkEndpoint{} - mi := &file_openshell_proto_msgTypes[130] + mi := &file_openshell_proto_msgTypes[141] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9567,7 +11190,7 @@ func (x *RemoveNetworkEndpoint) String() string { func (*RemoveNetworkEndpoint) ProtoMessage() {} func (x *RemoveNetworkEndpoint) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[130] + mi := &file_openshell_proto_msgTypes[141] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9580,7 +11203,7 @@ func (x *RemoveNetworkEndpoint) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveNetworkEndpoint.ProtoReflect.Descriptor instead. func (*RemoveNetworkEndpoint) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{130} + return file_openshell_proto_rawDescGZIP(), []int{141} } func (x *RemoveNetworkEndpoint) GetRuleName() string { @@ -9613,7 +11236,7 @@ type RemoveNetworkRule struct { func (x *RemoveNetworkRule) Reset() { *x = RemoveNetworkRule{} - mi := &file_openshell_proto_msgTypes[131] + mi := &file_openshell_proto_msgTypes[142] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9625,7 +11248,7 @@ func (x *RemoveNetworkRule) String() string { func (*RemoveNetworkRule) ProtoMessage() {} func (x *RemoveNetworkRule) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[131] + mi := &file_openshell_proto_msgTypes[142] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9638,7 +11261,7 @@ func (x *RemoveNetworkRule) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveNetworkRule.ProtoReflect.Descriptor instead. func (*RemoveNetworkRule) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{131} + return file_openshell_proto_rawDescGZIP(), []int{142} } func (x *RemoveNetworkRule) GetRuleName() string { @@ -9659,7 +11282,7 @@ type AddDenyRules struct { func (x *AddDenyRules) Reset() { *x = AddDenyRules{} - mi := &file_openshell_proto_msgTypes[132] + mi := &file_openshell_proto_msgTypes[143] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9671,7 +11294,7 @@ func (x *AddDenyRules) String() string { func (*AddDenyRules) ProtoMessage() {} func (x *AddDenyRules) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[132] + mi := &file_openshell_proto_msgTypes[143] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9684,7 +11307,7 @@ func (x *AddDenyRules) ProtoReflect() protoreflect.Message { // Deprecated: Use AddDenyRules.ProtoReflect.Descriptor instead. func (*AddDenyRules) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{132} + return file_openshell_proto_rawDescGZIP(), []int{143} } func (x *AddDenyRules) GetHost() string { @@ -9719,7 +11342,7 @@ type AddAllowRules struct { func (x *AddAllowRules) Reset() { *x = AddAllowRules{} - mi := &file_openshell_proto_msgTypes[133] + mi := &file_openshell_proto_msgTypes[144] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9731,7 +11354,7 @@ func (x *AddAllowRules) String() string { func (*AddAllowRules) ProtoMessage() {} func (x *AddAllowRules) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[133] + mi := &file_openshell_proto_msgTypes[144] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9744,7 +11367,7 @@ func (x *AddAllowRules) ProtoReflect() protoreflect.Message { // Deprecated: Use AddAllowRules.ProtoReflect.Descriptor instead. func (*AddAllowRules) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{133} + return file_openshell_proto_rawDescGZIP(), []int{144} } func (x *AddAllowRules) GetHost() string { @@ -9778,7 +11401,7 @@ type RemoveNetworkBinary struct { func (x *RemoveNetworkBinary) Reset() { *x = RemoveNetworkBinary{} - mi := &file_openshell_proto_msgTypes[134] + mi := &file_openshell_proto_msgTypes[145] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9790,7 +11413,7 @@ func (x *RemoveNetworkBinary) String() string { func (*RemoveNetworkBinary) ProtoMessage() {} func (x *RemoveNetworkBinary) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[134] + mi := &file_openshell_proto_msgTypes[145] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9803,7 +11426,7 @@ func (x *RemoveNetworkBinary) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveNetworkBinary.ProtoReflect.Descriptor instead. func (*RemoveNetworkBinary) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{134} + return file_openshell_proto_rawDescGZIP(), []int{145} } func (x *RemoveNetworkBinary) GetRuleName() string { @@ -9839,7 +11462,7 @@ type UpdateConfigResponse struct { func (x *UpdateConfigResponse) Reset() { *x = UpdateConfigResponse{} - mi := &file_openshell_proto_msgTypes[135] + mi := &file_openshell_proto_msgTypes[146] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9851,7 +11474,7 @@ func (x *UpdateConfigResponse) String() string { func (*UpdateConfigResponse) ProtoMessage() {} func (x *UpdateConfigResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[135] + mi := &file_openshell_proto_msgTypes[146] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9864,7 +11487,7 @@ func (x *UpdateConfigResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateConfigResponse.ProtoReflect.Descriptor instead. func (*UpdateConfigResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{135} + return file_openshell_proto_rawDescGZIP(), []int{146} } func (x *UpdateConfigResponse) GetVersion() uint32 { @@ -9920,7 +11543,7 @@ type GetSandboxPolicyStatusRequest struct { func (x *GetSandboxPolicyStatusRequest) Reset() { *x = GetSandboxPolicyStatusRequest{} - mi := &file_openshell_proto_msgTypes[136] + mi := &file_openshell_proto_msgTypes[147] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9932,7 +11555,7 @@ func (x *GetSandboxPolicyStatusRequest) String() string { func (*GetSandboxPolicyStatusRequest) ProtoMessage() {} func (x *GetSandboxPolicyStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[136] + mi := &file_openshell_proto_msgTypes[147] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9945,7 +11568,7 @@ func (x *GetSandboxPolicyStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxPolicyStatusRequest.ProtoReflect.Descriptor instead. func (*GetSandboxPolicyStatusRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{136} + return file_openshell_proto_rawDescGZIP(), []int{147} } func (x *GetSandboxPolicyStatusRequest) GetName() string { @@ -9989,7 +11612,7 @@ type GetSandboxPolicyStatusResponse struct { func (x *GetSandboxPolicyStatusResponse) Reset() { *x = GetSandboxPolicyStatusResponse{} - mi := &file_openshell_proto_msgTypes[137] + mi := &file_openshell_proto_msgTypes[148] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10001,7 +11624,7 @@ func (x *GetSandboxPolicyStatusResponse) String() string { func (*GetSandboxPolicyStatusResponse) ProtoMessage() {} func (x *GetSandboxPolicyStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[137] + mi := &file_openshell_proto_msgTypes[148] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10014,7 +11637,7 @@ func (x *GetSandboxPolicyStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxPolicyStatusResponse.ProtoReflect.Descriptor instead. func (*GetSandboxPolicyStatusResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{137} + return file_openshell_proto_rawDescGZIP(), []int{148} } func (x *GetSandboxPolicyStatusResponse) GetRevision() *SandboxPolicyRevision { @@ -10053,7 +11676,7 @@ type ListSandboxPoliciesRequest struct { func (x *ListSandboxPoliciesRequest) Reset() { *x = ListSandboxPoliciesRequest{} - mi := &file_openshell_proto_msgTypes[138] + mi := &file_openshell_proto_msgTypes[149] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10065,7 +11688,7 @@ func (x *ListSandboxPoliciesRequest) String() string { func (*ListSandboxPoliciesRequest) ProtoMessage() {} func (x *ListSandboxPoliciesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[138] + mi := &file_openshell_proto_msgTypes[149] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10078,7 +11701,7 @@ func (x *ListSandboxPoliciesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSandboxPoliciesRequest.ProtoReflect.Descriptor instead. func (*ListSandboxPoliciesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{138} + return file_openshell_proto_rawDescGZIP(), []int{149} } func (x *ListSandboxPoliciesRequest) GetName() string { @@ -10130,7 +11753,7 @@ type ListSandboxPoliciesResponse struct { func (x *ListSandboxPoliciesResponse) Reset() { *x = ListSandboxPoliciesResponse{} - mi := &file_openshell_proto_msgTypes[139] + mi := &file_openshell_proto_msgTypes[150] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10142,7 +11765,7 @@ func (x *ListSandboxPoliciesResponse) String() string { func (*ListSandboxPoliciesResponse) ProtoMessage() {} func (x *ListSandboxPoliciesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[139] + mi := &file_openshell_proto_msgTypes[150] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10155,7 +11778,7 @@ func (x *ListSandboxPoliciesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSandboxPoliciesResponse.ProtoReflect.Descriptor instead. func (*ListSandboxPoliciesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{139} + return file_openshell_proto_rawDescGZIP(), []int{150} } func (x *ListSandboxPoliciesResponse) GetRevisions() []*SandboxPolicyRevision { @@ -10189,7 +11812,7 @@ type ReportPolicyStatusRequest struct { func (x *ReportPolicyStatusRequest) Reset() { *x = ReportPolicyStatusRequest{} - mi := &file_openshell_proto_msgTypes[140] + mi := &file_openshell_proto_msgTypes[151] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10201,7 +11824,7 @@ func (x *ReportPolicyStatusRequest) String() string { func (*ReportPolicyStatusRequest) ProtoMessage() {} func (x *ReportPolicyStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[140] + mi := &file_openshell_proto_msgTypes[151] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10214,7 +11837,7 @@ func (x *ReportPolicyStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportPolicyStatusRequest.ProtoReflect.Descriptor instead. func (*ReportPolicyStatusRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{140} + return file_openshell_proto_rawDescGZIP(), []int{151} } func (x *ReportPolicyStatusRequest) GetSandboxId() string { @@ -10254,7 +11877,7 @@ type ReportPolicyStatusResponse struct { func (x *ReportPolicyStatusResponse) Reset() { *x = ReportPolicyStatusResponse{} - mi := &file_openshell_proto_msgTypes[141] + mi := &file_openshell_proto_msgTypes[152] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10266,7 +11889,7 @@ func (x *ReportPolicyStatusResponse) String() string { func (*ReportPolicyStatusResponse) ProtoMessage() {} func (x *ReportPolicyStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[141] + mi := &file_openshell_proto_msgTypes[152] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10279,7 +11902,7 @@ func (x *ReportPolicyStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportPolicyStatusResponse.ProtoReflect.Descriptor instead. func (*ReportPolicyStatusResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{141} + return file_openshell_proto_rawDescGZIP(), []int{152} } // A versioned policy revision with metadata. @@ -10312,7 +11935,7 @@ type SandboxPolicyRevision struct { func (x *SandboxPolicyRevision) Reset() { *x = SandboxPolicyRevision{} - mi := &file_openshell_proto_msgTypes[142] + mi := &file_openshell_proto_msgTypes[153] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10324,7 +11947,7 @@ func (x *SandboxPolicyRevision) String() string { func (*SandboxPolicyRevision) ProtoMessage() {} func (x *SandboxPolicyRevision) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[142] + mi := &file_openshell_proto_msgTypes[153] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10337,7 +11960,7 @@ func (x *SandboxPolicyRevision) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxPolicyRevision.ProtoReflect.Descriptor instead. func (*SandboxPolicyRevision) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{142} + return file_openshell_proto_rawDescGZIP(), []int{153} } func (x *SandboxPolicyRevision) GetVersion() uint32 { @@ -10417,7 +12040,7 @@ type GetSandboxLogsRequest struct { func (x *GetSandboxLogsRequest) Reset() { *x = GetSandboxLogsRequest{} - mi := &file_openshell_proto_msgTypes[143] + mi := &file_openshell_proto_msgTypes[154] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10429,7 +12052,7 @@ func (x *GetSandboxLogsRequest) String() string { func (*GetSandboxLogsRequest) ProtoMessage() {} func (x *GetSandboxLogsRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[143] + mi := &file_openshell_proto_msgTypes[154] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10442,7 +12065,7 @@ func (x *GetSandboxLogsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxLogsRequest.ProtoReflect.Descriptor instead. func (*GetSandboxLogsRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{143} + return file_openshell_proto_rawDescGZIP(), []int{154} } func (x *GetSandboxLogsRequest) GetSandboxId() string { @@ -10500,7 +12123,7 @@ type PushSandboxLogsRequest struct { func (x *PushSandboxLogsRequest) Reset() { *x = PushSandboxLogsRequest{} - mi := &file_openshell_proto_msgTypes[144] + mi := &file_openshell_proto_msgTypes[155] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10512,7 +12135,7 @@ func (x *PushSandboxLogsRequest) String() string { func (*PushSandboxLogsRequest) ProtoMessage() {} func (x *PushSandboxLogsRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[144] + mi := &file_openshell_proto_msgTypes[155] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10525,7 +12148,7 @@ func (x *PushSandboxLogsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use PushSandboxLogsRequest.ProtoReflect.Descriptor instead. func (*PushSandboxLogsRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{144} + return file_openshell_proto_rawDescGZIP(), []int{155} } func (x *PushSandboxLogsRequest) GetSandboxId() string { @@ -10551,7 +12174,7 @@ type PushSandboxLogsResponse struct { func (x *PushSandboxLogsResponse) Reset() { *x = PushSandboxLogsResponse{} - mi := &file_openshell_proto_msgTypes[145] + mi := &file_openshell_proto_msgTypes[156] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10563,7 +12186,7 @@ func (x *PushSandboxLogsResponse) String() string { func (*PushSandboxLogsResponse) ProtoMessage() {} func (x *PushSandboxLogsResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[145] + mi := &file_openshell_proto_msgTypes[156] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10576,7 +12199,7 @@ func (x *PushSandboxLogsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PushSandboxLogsResponse.ProtoReflect.Descriptor instead. func (*PushSandboxLogsResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{145} + return file_openshell_proto_rawDescGZIP(), []int{156} } // Get sandbox logs response. @@ -10592,7 +12215,7 @@ type GetSandboxLogsResponse struct { func (x *GetSandboxLogsResponse) Reset() { *x = GetSandboxLogsResponse{} - mi := &file_openshell_proto_msgTypes[146] + mi := &file_openshell_proto_msgTypes[157] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10604,7 +12227,7 @@ func (x *GetSandboxLogsResponse) String() string { func (*GetSandboxLogsResponse) ProtoMessage() {} func (x *GetSandboxLogsResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[146] + mi := &file_openshell_proto_msgTypes[157] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10617,7 +12240,7 @@ func (x *GetSandboxLogsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxLogsResponse.ProtoReflect.Descriptor instead. func (*GetSandboxLogsResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{146} + return file_openshell_proto_rawDescGZIP(), []int{157} } func (x *GetSandboxLogsResponse) GetLogs() []*SandboxLogLine { @@ -10650,7 +12273,7 @@ type SupervisorMessage struct { func (x *SupervisorMessage) Reset() { *x = SupervisorMessage{} - mi := &file_openshell_proto_msgTypes[147] + mi := &file_openshell_proto_msgTypes[158] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10662,7 +12285,7 @@ func (x *SupervisorMessage) String() string { func (*SupervisorMessage) ProtoMessage() {} func (x *SupervisorMessage) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[147] + mi := &file_openshell_proto_msgTypes[158] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10675,7 +12298,7 @@ func (x *SupervisorMessage) ProtoReflect() protoreflect.Message { // Deprecated: Use SupervisorMessage.ProtoReflect.Descriptor instead. func (*SupervisorMessage) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{147} + return file_openshell_proto_rawDescGZIP(), []int{158} } func (x *SupervisorMessage) GetPayload() isSupervisorMessage_Payload { @@ -10766,7 +12389,7 @@ type GatewayMessage struct { func (x *GatewayMessage) Reset() { *x = GatewayMessage{} - mi := &file_openshell_proto_msgTypes[148] + mi := &file_openshell_proto_msgTypes[159] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10778,7 +12401,7 @@ func (x *GatewayMessage) String() string { func (*GatewayMessage) ProtoMessage() {} func (x *GatewayMessage) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[148] + mi := &file_openshell_proto_msgTypes[159] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10791,7 +12414,7 @@ func (x *GatewayMessage) ProtoReflect() protoreflect.Message { // Deprecated: Use GatewayMessage.ProtoReflect.Descriptor instead. func (*GatewayMessage) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{148} + return file_openshell_proto_rawDescGZIP(), []int{159} } func (x *GatewayMessage) GetPayload() isGatewayMessage_Payload { @@ -10886,14 +12509,16 @@ type SupervisorHello struct { // Sandbox ID this supervisor manages. SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"` // Supervisor instance ID (e.g. boot id or process epoch). - InstanceId string `protobuf:"bytes,2,opt,name=instance_id,json=instanceId,proto3" json:"instance_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + InstanceId string `protobuf:"bytes,2,opt,name=instance_id,json=instanceId,proto3" json:"instance_id,omitempty"` + // The supervisor can report credential, policy, and launch-environment installation. + SupportsProviderReadiness bool `protobuf:"varint,4,opt,name=supports_provider_readiness,json=supportsProviderReadiness,proto3" json:"supports_provider_readiness,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SupervisorHello) Reset() { *x = SupervisorHello{} - mi := &file_openshell_proto_msgTypes[149] + mi := &file_openshell_proto_msgTypes[160] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10905,7 +12530,7 @@ func (x *SupervisorHello) String() string { func (*SupervisorHello) ProtoMessage() {} func (x *SupervisorHello) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[149] + mi := &file_openshell_proto_msgTypes[160] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10918,7 +12543,7 @@ func (x *SupervisorHello) ProtoReflect() protoreflect.Message { // Deprecated: Use SupervisorHello.ProtoReflect.Descriptor instead. func (*SupervisorHello) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{149} + return file_openshell_proto_rawDescGZIP(), []int{160} } func (x *SupervisorHello) GetSandboxId() string { @@ -10935,6 +12560,13 @@ func (x *SupervisorHello) GetInstanceId() string { return "" } +func (x *SupervisorHello) GetSupportsProviderReadiness() bool { + if x != nil { + return x.SupportsProviderReadiness + } + return false +} + // Gateway accepts the supervisor session. type SessionAccepted struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -10948,7 +12580,7 @@ type SessionAccepted struct { func (x *SessionAccepted) Reset() { *x = SessionAccepted{} - mi := &file_openshell_proto_msgTypes[150] + mi := &file_openshell_proto_msgTypes[161] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10960,7 +12592,7 @@ func (x *SessionAccepted) String() string { func (*SessionAccepted) ProtoMessage() {} func (x *SessionAccepted) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[150] + mi := &file_openshell_proto_msgTypes[161] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10973,7 +12605,7 @@ func (x *SessionAccepted) ProtoReflect() protoreflect.Message { // Deprecated: Use SessionAccepted.ProtoReflect.Descriptor instead. func (*SessionAccepted) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{150} + return file_openshell_proto_rawDescGZIP(), []int{161} } func (x *SessionAccepted) GetSessionId() string { @@ -11001,7 +12633,7 @@ type SessionRejected struct { func (x *SessionRejected) Reset() { *x = SessionRejected{} - mi := &file_openshell_proto_msgTypes[151] + mi := &file_openshell_proto_msgTypes[162] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11013,7 +12645,7 @@ func (x *SessionRejected) String() string { func (*SessionRejected) ProtoMessage() {} func (x *SessionRejected) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[151] + mi := &file_openshell_proto_msgTypes[162] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11026,7 +12658,7 @@ func (x *SessionRejected) ProtoReflect() protoreflect.Message { // Deprecated: Use SessionRejected.ProtoReflect.Descriptor instead. func (*SessionRejected) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{151} + return file_openshell_proto_rawDescGZIP(), []int{162} } func (x *SessionRejected) GetReason() string { @@ -11045,7 +12677,7 @@ type SupervisorHeartbeat struct { func (x *SupervisorHeartbeat) Reset() { *x = SupervisorHeartbeat{} - mi := &file_openshell_proto_msgTypes[152] + mi := &file_openshell_proto_msgTypes[163] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11057,7 +12689,7 @@ func (x *SupervisorHeartbeat) String() string { func (*SupervisorHeartbeat) ProtoMessage() {} func (x *SupervisorHeartbeat) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[152] + mi := &file_openshell_proto_msgTypes[163] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11070,7 +12702,7 @@ func (x *SupervisorHeartbeat) ProtoReflect() protoreflect.Message { // Deprecated: Use SupervisorHeartbeat.ProtoReflect.Descriptor instead. func (*SupervisorHeartbeat) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{152} + return file_openshell_proto_rawDescGZIP(), []int{163} } // Gateway heartbeat. @@ -11082,7 +12714,7 @@ type GatewayHeartbeat struct { func (x *GatewayHeartbeat) Reset() { *x = GatewayHeartbeat{} - mi := &file_openshell_proto_msgTypes[153] + mi := &file_openshell_proto_msgTypes[164] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11094,7 +12726,7 @@ func (x *GatewayHeartbeat) String() string { func (*GatewayHeartbeat) ProtoMessage() {} func (x *GatewayHeartbeat) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[153] + mi := &file_openshell_proto_msgTypes[164] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11107,7 +12739,7 @@ func (x *GatewayHeartbeat) ProtoReflect() protoreflect.Message { // Deprecated: Use GatewayHeartbeat.ProtoReflect.Descriptor instead. func (*GatewayHeartbeat) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{153} + return file_openshell_proto_rawDescGZIP(), []int{164} } // Terminal result reported before the supervisor shuts down. A successful RPC @@ -11124,7 +12756,7 @@ type ReportMainProcessExitRequest struct { func (x *ReportMainProcessExitRequest) Reset() { *x = ReportMainProcessExitRequest{} - mi := &file_openshell_proto_msgTypes[154] + mi := &file_openshell_proto_msgTypes[165] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11136,7 +12768,7 @@ func (x *ReportMainProcessExitRequest) String() string { func (*ReportMainProcessExitRequest) ProtoMessage() {} func (x *ReportMainProcessExitRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[154] + mi := &file_openshell_proto_msgTypes[165] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11149,7 +12781,7 @@ func (x *ReportMainProcessExitRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportMainProcessExitRequest.ProtoReflect.Descriptor instead. func (*ReportMainProcessExitRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{154} + return file_openshell_proto_rawDescGZIP(), []int{165} } func (x *ReportMainProcessExitRequest) GetSandboxId() string { @@ -11181,7 +12813,7 @@ type ReportMainProcessExitResponse struct { func (x *ReportMainProcessExitResponse) Reset() { *x = ReportMainProcessExitResponse{} - mi := &file_openshell_proto_msgTypes[155] + mi := &file_openshell_proto_msgTypes[166] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11193,7 +12825,7 @@ func (x *ReportMainProcessExitResponse) String() string { func (*ReportMainProcessExitResponse) ProtoMessage() {} func (x *ReportMainProcessExitResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[155] + mi := &file_openshell_proto_msgTypes[166] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11206,7 +12838,7 @@ func (x *ReportMainProcessExitResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportMainProcessExitResponse.ProtoReflect.Descriptor instead. func (*ReportMainProcessExitResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{155} + return file_openshell_proto_rawDescGZIP(), []int{166} } // Terminal-delivery completion reported after all expected foreground SSH @@ -11221,7 +12853,7 @@ type FinalizeMainProcessExitRequest struct { func (x *FinalizeMainProcessExitRequest) Reset() { *x = FinalizeMainProcessExitRequest{} - mi := &file_openshell_proto_msgTypes[156] + mi := &file_openshell_proto_msgTypes[167] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11233,7 +12865,7 @@ func (x *FinalizeMainProcessExitRequest) String() string { func (*FinalizeMainProcessExitRequest) ProtoMessage() {} func (x *FinalizeMainProcessExitRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[156] + mi := &file_openshell_proto_msgTypes[167] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11246,7 +12878,7 @@ func (x *FinalizeMainProcessExitRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use FinalizeMainProcessExitRequest.ProtoReflect.Descriptor instead. func (*FinalizeMainProcessExitRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{156} + return file_openshell_proto_rawDescGZIP(), []int{167} } func (x *FinalizeMainProcessExitRequest) GetSandboxId() string { @@ -11271,7 +12903,7 @@ type FinalizeMainProcessExitResponse struct { func (x *FinalizeMainProcessExitResponse) Reset() { *x = FinalizeMainProcessExitResponse{} - mi := &file_openshell_proto_msgTypes[157] + mi := &file_openshell_proto_msgTypes[168] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11283,7 +12915,7 @@ func (x *FinalizeMainProcessExitResponse) String() string { func (*FinalizeMainProcessExitResponse) ProtoMessage() {} func (x *FinalizeMainProcessExitResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[157] + mi := &file_openshell_proto_msgTypes[168] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11296,7 +12928,7 @@ func (x *FinalizeMainProcessExitResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use FinalizeMainProcessExitResponse.ProtoReflect.Descriptor instead. func (*FinalizeMainProcessExitResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{157} + return file_openshell_proto_rawDescGZIP(), []int{168} } // Gateway requests the supervisor to open a relay channel. @@ -11325,7 +12957,7 @@ type RelayOpen struct { func (x *RelayOpen) Reset() { *x = RelayOpen{} - mi := &file_openshell_proto_msgTypes[158] + mi := &file_openshell_proto_msgTypes[169] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11337,7 +12969,7 @@ func (x *RelayOpen) String() string { func (*RelayOpen) ProtoMessage() {} func (x *RelayOpen) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[158] + mi := &file_openshell_proto_msgTypes[169] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11350,7 +12982,7 @@ func (x *RelayOpen) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayOpen.ProtoReflect.Descriptor instead. func (*RelayOpen) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{158} + return file_openshell_proto_rawDescGZIP(), []int{169} } func (x *RelayOpen) GetChannelId() string { @@ -11417,7 +13049,7 @@ type SshRelayTarget struct { func (x *SshRelayTarget) Reset() { *x = SshRelayTarget{} - mi := &file_openshell_proto_msgTypes[159] + mi := &file_openshell_proto_msgTypes[170] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11429,7 +13061,7 @@ func (x *SshRelayTarget) String() string { func (*SshRelayTarget) ProtoMessage() {} func (x *SshRelayTarget) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[159] + mi := &file_openshell_proto_msgTypes[170] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11442,7 +13074,7 @@ func (x *SshRelayTarget) ProtoReflect() protoreflect.Message { // Deprecated: Use SshRelayTarget.ProtoReflect.Descriptor instead. func (*SshRelayTarget) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{159} + return file_openshell_proto_rawDescGZIP(), []int{170} } // TCP target dialed by the supervisor from inside the sandbox. @@ -11458,7 +13090,7 @@ type TcpRelayTarget struct { func (x *TcpRelayTarget) Reset() { *x = TcpRelayTarget{} - mi := &file_openshell_proto_msgTypes[160] + mi := &file_openshell_proto_msgTypes[171] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11470,7 +13102,7 @@ func (x *TcpRelayTarget) String() string { func (*TcpRelayTarget) ProtoMessage() {} func (x *TcpRelayTarget) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[160] + mi := &file_openshell_proto_msgTypes[171] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11483,7 +13115,7 @@ func (x *TcpRelayTarget) ProtoReflect() protoreflect.Message { // Deprecated: Use TcpRelayTarget.ProtoReflect.Descriptor instead. func (*TcpRelayTarget) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{160} + return file_openshell_proto_rawDescGZIP(), []int{171} } func (x *TcpRelayTarget) GetHost() string { @@ -11511,7 +13143,7 @@ type RelayInit struct { func (x *RelayInit) Reset() { *x = RelayInit{} - mi := &file_openshell_proto_msgTypes[161] + mi := &file_openshell_proto_msgTypes[172] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11523,7 +13155,7 @@ func (x *RelayInit) String() string { func (*RelayInit) ProtoMessage() {} func (x *RelayInit) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[161] + mi := &file_openshell_proto_msgTypes[172] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11536,7 +13168,7 @@ func (x *RelayInit) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayInit.ProtoReflect.Descriptor instead. func (*RelayInit) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{161} + return file_openshell_proto_rawDescGZIP(), []int{172} } func (x *RelayInit) GetChannelId() string { @@ -11563,7 +13195,7 @@ type RelayFrame struct { func (x *RelayFrame) Reset() { *x = RelayFrame{} - mi := &file_openshell_proto_msgTypes[162] + mi := &file_openshell_proto_msgTypes[173] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11575,7 +13207,7 @@ func (x *RelayFrame) String() string { func (*RelayFrame) ProtoMessage() {} func (x *RelayFrame) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[162] + mi := &file_openshell_proto_msgTypes[173] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11588,7 +13220,7 @@ func (x *RelayFrame) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayFrame.ProtoReflect.Descriptor instead. func (*RelayFrame) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{162} + return file_openshell_proto_rawDescGZIP(), []int{173} } func (x *RelayFrame) GetPayload() isRelayFrame_Payload { @@ -11647,7 +13279,7 @@ type RelayOpenResult struct { func (x *RelayOpenResult) Reset() { *x = RelayOpenResult{} - mi := &file_openshell_proto_msgTypes[163] + mi := &file_openshell_proto_msgTypes[174] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11659,7 +13291,7 @@ func (x *RelayOpenResult) String() string { func (*RelayOpenResult) ProtoMessage() {} func (x *RelayOpenResult) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[163] + mi := &file_openshell_proto_msgTypes[174] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11672,7 +13304,7 @@ func (x *RelayOpenResult) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayOpenResult.ProtoReflect.Descriptor instead. func (*RelayOpenResult) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{163} + return file_openshell_proto_rawDescGZIP(), []int{174} } func (x *RelayOpenResult) GetChannelId() string { @@ -11709,7 +13341,7 @@ type RelayClose struct { func (x *RelayClose) Reset() { *x = RelayClose{} - mi := &file_openshell_proto_msgTypes[164] + mi := &file_openshell_proto_msgTypes[175] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11721,7 +13353,7 @@ func (x *RelayClose) String() string { func (*RelayClose) ProtoMessage() {} func (x *RelayClose) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[164] + mi := &file_openshell_proto_msgTypes[175] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11734,7 +13366,7 @@ func (x *RelayClose) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayClose.ProtoReflect.Descriptor instead. func (*RelayClose) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{164} + return file_openshell_proto_rawDescGZIP(), []int{175} } func (x *RelayClose) GetChannelId() string { @@ -11768,7 +13400,7 @@ type L7RequestSample struct { func (x *L7RequestSample) Reset() { *x = L7RequestSample{} - mi := &file_openshell_proto_msgTypes[165] + mi := &file_openshell_proto_msgTypes[176] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11780,7 +13412,7 @@ func (x *L7RequestSample) String() string { func (*L7RequestSample) ProtoMessage() {} func (x *L7RequestSample) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[165] + mi := &file_openshell_proto_msgTypes[176] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11793,7 +13425,7 @@ func (x *L7RequestSample) ProtoReflect() protoreflect.Message { // Deprecated: Use L7RequestSample.ProtoReflect.Descriptor instead. func (*L7RequestSample) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{165} + return file_openshell_proto_rawDescGZIP(), []int{176} } func (x *L7RequestSample) GetMethod() string { @@ -11867,7 +13499,7 @@ type DenialSummary struct { func (x *DenialSummary) Reset() { *x = DenialSummary{} - mi := &file_openshell_proto_msgTypes[166] + mi := &file_openshell_proto_msgTypes[177] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11879,7 +13511,7 @@ func (x *DenialSummary) String() string { func (*DenialSummary) ProtoMessage() {} func (x *DenialSummary) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[166] + mi := &file_openshell_proto_msgTypes[177] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11892,7 +13524,7 @@ func (x *DenialSummary) ProtoReflect() protoreflect.Message { // Deprecated: Use DenialSummary.ProtoReflect.Descriptor instead. func (*DenialSummary) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{166} + return file_openshell_proto_rawDescGZIP(), []int{177} } func (x *DenialSummary) GetSandboxId() string { @@ -12027,7 +13659,7 @@ type DenialGroupCount struct { func (x *DenialGroupCount) Reset() { *x = DenialGroupCount{} - mi := &file_openshell_proto_msgTypes[167] + mi := &file_openshell_proto_msgTypes[178] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12039,7 +13671,7 @@ func (x *DenialGroupCount) String() string { func (*DenialGroupCount) ProtoMessage() {} func (x *DenialGroupCount) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[167] + mi := &file_openshell_proto_msgTypes[178] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12052,7 +13684,7 @@ func (x *DenialGroupCount) ProtoReflect() protoreflect.Message { // Deprecated: Use DenialGroupCount.ProtoReflect.Descriptor instead. func (*DenialGroupCount) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{167} + return file_openshell_proto_rawDescGZIP(), []int{178} } func (x *DenialGroupCount) GetDenyGroup() string { @@ -12085,7 +13717,7 @@ type NetworkActivitySummary struct { func (x *NetworkActivitySummary) Reset() { *x = NetworkActivitySummary{} - mi := &file_openshell_proto_msgTypes[168] + mi := &file_openshell_proto_msgTypes[179] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12097,7 +13729,7 @@ func (x *NetworkActivitySummary) String() string { func (*NetworkActivitySummary) ProtoMessage() {} func (x *NetworkActivitySummary) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[168] + mi := &file_openshell_proto_msgTypes[179] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12110,7 +13742,7 @@ func (x *NetworkActivitySummary) ProtoReflect() protoreflect.Message { // Deprecated: Use NetworkActivitySummary.ProtoReflect.Descriptor instead. func (*NetworkActivitySummary) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{168} + return file_openshell_proto_rawDescGZIP(), []int{179} } func (x *NetworkActivitySummary) GetNetworkActivityCount() uint32 { @@ -12198,7 +13830,7 @@ type PolicyChunk struct { func (x *PolicyChunk) Reset() { *x = PolicyChunk{} - mi := &file_openshell_proto_msgTypes[169] + mi := &file_openshell_proto_msgTypes[180] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12210,7 +13842,7 @@ func (x *PolicyChunk) String() string { func (*PolicyChunk) ProtoMessage() {} func (x *PolicyChunk) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[169] + mi := &file_openshell_proto_msgTypes[180] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12223,7 +13855,7 @@ func (x *PolicyChunk) ProtoReflect() protoreflect.Message { // Deprecated: Use PolicyChunk.ProtoReflect.Descriptor instead. func (*PolicyChunk) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{169} + return file_openshell_proto_rawDescGZIP(), []int{180} } func (x *PolicyChunk) GetId() string { @@ -12411,7 +14043,7 @@ type DraftPolicyUpdate struct { func (x *DraftPolicyUpdate) Reset() { *x = DraftPolicyUpdate{} - mi := &file_openshell_proto_msgTypes[170] + mi := &file_openshell_proto_msgTypes[181] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12423,7 +14055,7 @@ func (x *DraftPolicyUpdate) String() string { func (*DraftPolicyUpdate) ProtoMessage() {} func (x *DraftPolicyUpdate) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[170] + mi := &file_openshell_proto_msgTypes[181] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12436,7 +14068,7 @@ func (x *DraftPolicyUpdate) ProtoReflect() protoreflect.Message { // Deprecated: Use DraftPolicyUpdate.ProtoReflect.Descriptor instead. func (*DraftPolicyUpdate) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{170} + return file_openshell_proto_rawDescGZIP(), []int{181} } func (x *DraftPolicyUpdate) GetDraftVersion() uint64 { @@ -12494,7 +14126,7 @@ type SubmitPolicyAnalysisRequest struct { func (x *SubmitPolicyAnalysisRequest) Reset() { *x = SubmitPolicyAnalysisRequest{} - mi := &file_openshell_proto_msgTypes[171] + mi := &file_openshell_proto_msgTypes[182] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12506,7 +14138,7 @@ func (x *SubmitPolicyAnalysisRequest) String() string { func (*SubmitPolicyAnalysisRequest) ProtoMessage() {} func (x *SubmitPolicyAnalysisRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[171] + mi := &file_openshell_proto_msgTypes[182] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12519,7 +14151,7 @@ func (x *SubmitPolicyAnalysisRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SubmitPolicyAnalysisRequest.ProtoReflect.Descriptor instead. func (*SubmitPolicyAnalysisRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{171} + return file_openshell_proto_rawDescGZIP(), []int{182} } func (x *SubmitPolicyAnalysisRequest) GetSummaries() []*DenialSummary { @@ -12582,7 +14214,7 @@ type SubmitPolicyAnalysisResponse struct { func (x *SubmitPolicyAnalysisResponse) Reset() { *x = SubmitPolicyAnalysisResponse{} - mi := &file_openshell_proto_msgTypes[172] + mi := &file_openshell_proto_msgTypes[183] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12594,7 +14226,7 @@ func (x *SubmitPolicyAnalysisResponse) String() string { func (*SubmitPolicyAnalysisResponse) ProtoMessage() {} func (x *SubmitPolicyAnalysisResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[172] + mi := &file_openshell_proto_msgTypes[183] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12607,7 +14239,7 @@ func (x *SubmitPolicyAnalysisResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SubmitPolicyAnalysisResponse.ProtoReflect.Descriptor instead. func (*SubmitPolicyAnalysisResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{172} + return file_openshell_proto_rawDescGZIP(), []int{183} } func (x *SubmitPolicyAnalysisResponse) GetAcceptedChunks() uint32 { @@ -12653,7 +14285,7 @@ type GetDraftPolicyRequest struct { func (x *GetDraftPolicyRequest) Reset() { *x = GetDraftPolicyRequest{} - mi := &file_openshell_proto_msgTypes[173] + mi := &file_openshell_proto_msgTypes[184] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12665,7 +14297,7 @@ func (x *GetDraftPolicyRequest) String() string { func (*GetDraftPolicyRequest) ProtoMessage() {} func (x *GetDraftPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[173] + mi := &file_openshell_proto_msgTypes[184] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12678,7 +14310,7 @@ func (x *GetDraftPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetDraftPolicyRequest.ProtoReflect.Descriptor instead. func (*GetDraftPolicyRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{173} + return file_openshell_proto_rawDescGZIP(), []int{184} } func (x *GetDraftPolicyRequest) GetName() string { @@ -12718,7 +14350,7 @@ type GetDraftPolicyResponse struct { func (x *GetDraftPolicyResponse) Reset() { *x = GetDraftPolicyResponse{} - mi := &file_openshell_proto_msgTypes[174] + mi := &file_openshell_proto_msgTypes[185] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12730,7 +14362,7 @@ func (x *GetDraftPolicyResponse) String() string { func (*GetDraftPolicyResponse) ProtoMessage() {} func (x *GetDraftPolicyResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[174] + mi := &file_openshell_proto_msgTypes[185] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12743,7 +14375,7 @@ func (x *GetDraftPolicyResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetDraftPolicyResponse.ProtoReflect.Descriptor instead. func (*GetDraftPolicyResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{174} + return file_openshell_proto_rawDescGZIP(), []int{185} } func (x *GetDraftPolicyResponse) GetChunks() []*PolicyChunk { @@ -12786,13 +14418,16 @@ type ApproveDraftChunkRequest struct { ReviewToken string `protobuf:"bytes,4,opt,name=review_token,json=reviewToken,proto3" json:"review_token,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,6,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ApproveDraftChunkRequest) Reset() { *x = ApproveDraftChunkRequest{} - mi := &file_openshell_proto_msgTypes[175] + mi := &file_openshell_proto_msgTypes[186] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12804,7 +14439,7 @@ func (x *ApproveDraftChunkRequest) String() string { func (*ApproveDraftChunkRequest) ProtoMessage() {} func (x *ApproveDraftChunkRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[175] + mi := &file_openshell_proto_msgTypes[186] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12817,7 +14452,7 @@ func (x *ApproveDraftChunkRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveDraftChunkRequest.ProtoReflect.Descriptor instead. func (*ApproveDraftChunkRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{175} + return file_openshell_proto_rawDescGZIP(), []int{186} } func (x *ApproveDraftChunkRequest) GetName() string { @@ -12848,6 +14483,13 @@ func (x *ApproveDraftChunkRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSel return nil } +func (x *ApproveDraftChunkRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type ApproveDraftChunkResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // New policy version after merge. @@ -12860,7 +14502,7 @@ type ApproveDraftChunkResponse struct { func (x *ApproveDraftChunkResponse) Reset() { *x = ApproveDraftChunkResponse{} - mi := &file_openshell_proto_msgTypes[176] + mi := &file_openshell_proto_msgTypes[187] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12872,7 +14514,7 @@ func (x *ApproveDraftChunkResponse) String() string { func (*ApproveDraftChunkResponse) ProtoMessage() {} func (x *ApproveDraftChunkResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[176] + mi := &file_openshell_proto_msgTypes[187] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12885,7 +14527,7 @@ func (x *ApproveDraftChunkResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveDraftChunkResponse.ProtoReflect.Descriptor instead. func (*ApproveDraftChunkResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{176} + return file_openshell_proto_rawDescGZIP(), []int{187} } func (x *ApproveDraftChunkResponse) GetPolicyVersion() uint32 { @@ -12913,13 +14555,16 @@ type RejectDraftChunkRequest struct { Reason string `protobuf:"bytes,3,opt,name=reason,proto3" json:"reason,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,6,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RejectDraftChunkRequest) Reset() { *x = RejectDraftChunkRequest{} - mi := &file_openshell_proto_msgTypes[177] + mi := &file_openshell_proto_msgTypes[188] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12931,7 +14576,7 @@ func (x *RejectDraftChunkRequest) String() string { func (*RejectDraftChunkRequest) ProtoMessage() {} func (x *RejectDraftChunkRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[177] + mi := &file_openshell_proto_msgTypes[188] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12944,7 +14589,7 @@ func (x *RejectDraftChunkRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RejectDraftChunkRequest.ProtoReflect.Descriptor instead. func (*RejectDraftChunkRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{177} + return file_openshell_proto_rawDescGZIP(), []int{188} } func (x *RejectDraftChunkRequest) GetName() string { @@ -12975,6 +14620,13 @@ func (x *RejectDraftChunkRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSele return nil } +func (x *RejectDraftChunkRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type RejectDraftChunkResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields @@ -12983,7 +14635,7 @@ type RejectDraftChunkResponse struct { func (x *RejectDraftChunkResponse) Reset() { *x = RejectDraftChunkResponse{} - mi := &file_openshell_proto_msgTypes[178] + mi := &file_openshell_proto_msgTypes[189] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12995,7 +14647,7 @@ func (x *RejectDraftChunkResponse) String() string { func (*RejectDraftChunkResponse) ProtoMessage() {} func (x *RejectDraftChunkResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[178] + mi := &file_openshell_proto_msgTypes[189] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13008,7 +14660,7 @@ func (x *RejectDraftChunkResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RejectDraftChunkResponse.ProtoReflect.Descriptor instead. func (*RejectDraftChunkResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{178} + return file_openshell_proto_rawDescGZIP(), []int{189} } // Approve all pending chunks. @@ -13022,7 +14674,7 @@ type DraftChunkApproval struct { func (x *DraftChunkApproval) Reset() { *x = DraftChunkApproval{} - mi := &file_openshell_proto_msgTypes[179] + mi := &file_openshell_proto_msgTypes[190] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13034,7 +14686,7 @@ func (x *DraftChunkApproval) String() string { func (*DraftChunkApproval) ProtoMessage() {} func (x *DraftChunkApproval) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[179] + mi := &file_openshell_proto_msgTypes[190] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13047,7 +14699,7 @@ func (x *DraftChunkApproval) ProtoReflect() protoreflect.Message { // Deprecated: Use DraftChunkApproval.ProtoReflect.Descriptor instead. func (*DraftChunkApproval) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{179} + return file_openshell_proto_rawDescGZIP(), []int{190} } func (x *DraftChunkApproval) GetChunkId() string { @@ -13075,13 +14727,16 @@ type ApproveAllDraftChunksRequest struct { Approvals []*DraftChunkApproval `protobuf:"bytes,4,rep,name=approvals,proto3" json:"approvals,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,6,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ApproveAllDraftChunksRequest) Reset() { *x = ApproveAllDraftChunksRequest{} - mi := &file_openshell_proto_msgTypes[180] + mi := &file_openshell_proto_msgTypes[191] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13093,7 +14748,7 @@ func (x *ApproveAllDraftChunksRequest) String() string { func (*ApproveAllDraftChunksRequest) ProtoMessage() {} func (x *ApproveAllDraftChunksRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[180] + mi := &file_openshell_proto_msgTypes[191] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13106,7 +14761,7 @@ func (x *ApproveAllDraftChunksRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveAllDraftChunksRequest.ProtoReflect.Descriptor instead. func (*ApproveAllDraftChunksRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{180} + return file_openshell_proto_rawDescGZIP(), []int{191} } func (x *ApproveAllDraftChunksRequest) GetName() string { @@ -13137,6 +14792,13 @@ func (x *ApproveAllDraftChunksRequest) GetWorkspaceScope() *datamodelv1.Workspac return nil } +func (x *ApproveAllDraftChunksRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type ApproveAllDraftChunksResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // New policy version after merge. @@ -13154,7 +14816,7 @@ type ApproveAllDraftChunksResponse struct { func (x *ApproveAllDraftChunksResponse) Reset() { *x = ApproveAllDraftChunksResponse{} - mi := &file_openshell_proto_msgTypes[181] + mi := &file_openshell_proto_msgTypes[192] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13166,7 +14828,7 @@ func (x *ApproveAllDraftChunksResponse) String() string { func (*ApproveAllDraftChunksResponse) ProtoMessage() {} func (x *ApproveAllDraftChunksResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[181] + mi := &file_openshell_proto_msgTypes[192] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13179,7 +14841,7 @@ func (x *ApproveAllDraftChunksResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveAllDraftChunksResponse.ProtoReflect.Descriptor instead. func (*ApproveAllDraftChunksResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{181} + return file_openshell_proto_rawDescGZIP(), []int{192} } func (x *ApproveAllDraftChunksResponse) GetPolicyVersion() uint32 { @@ -13221,13 +14883,16 @@ type EditDraftChunkRequest struct { ProposedRule *sandboxv1.NetworkPolicyRule `protobuf:"bytes,3,opt,name=proposed_rule,json=proposedRule,proto3" json:"proposed_rule,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,5,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,6,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *EditDraftChunkRequest) Reset() { *x = EditDraftChunkRequest{} - mi := &file_openshell_proto_msgTypes[182] + mi := &file_openshell_proto_msgTypes[193] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13239,7 +14904,7 @@ func (x *EditDraftChunkRequest) String() string { func (*EditDraftChunkRequest) ProtoMessage() {} func (x *EditDraftChunkRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[182] + mi := &file_openshell_proto_msgTypes[193] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13252,7 +14917,7 @@ func (x *EditDraftChunkRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use EditDraftChunkRequest.ProtoReflect.Descriptor instead. func (*EditDraftChunkRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{182} + return file_openshell_proto_rawDescGZIP(), []int{193} } func (x *EditDraftChunkRequest) GetName() string { @@ -13283,6 +14948,13 @@ func (x *EditDraftChunkRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelect return nil } +func (x *EditDraftChunkRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type EditDraftChunkResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields @@ -13291,7 +14963,7 @@ type EditDraftChunkResponse struct { func (x *EditDraftChunkResponse) Reset() { *x = EditDraftChunkResponse{} - mi := &file_openshell_proto_msgTypes[183] + mi := &file_openshell_proto_msgTypes[194] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13303,7 +14975,7 @@ func (x *EditDraftChunkResponse) String() string { func (*EditDraftChunkResponse) ProtoMessage() {} func (x *EditDraftChunkResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[183] + mi := &file_openshell_proto_msgTypes[194] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13316,7 +14988,7 @@ func (x *EditDraftChunkResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EditDraftChunkResponse.ProtoReflect.Descriptor instead. func (*EditDraftChunkResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{183} + return file_openshell_proto_rawDescGZIP(), []int{194} } // Reverse an approval (remove merged rule from active policy). @@ -13328,13 +15000,16 @@ type UndoDraftChunkRequest struct { ChunkId string `protobuf:"bytes,2,opt,name=chunk_id,json=chunkId,proto3" json:"chunk_id,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,4,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,5,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *UndoDraftChunkRequest) Reset() { *x = UndoDraftChunkRequest{} - mi := &file_openshell_proto_msgTypes[184] + mi := &file_openshell_proto_msgTypes[195] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13346,7 +15021,7 @@ func (x *UndoDraftChunkRequest) String() string { func (*UndoDraftChunkRequest) ProtoMessage() {} func (x *UndoDraftChunkRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[184] + mi := &file_openshell_proto_msgTypes[195] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13359,7 +15034,7 @@ func (x *UndoDraftChunkRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UndoDraftChunkRequest.ProtoReflect.Descriptor instead. func (*UndoDraftChunkRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{184} + return file_openshell_proto_rawDescGZIP(), []int{195} } func (x *UndoDraftChunkRequest) GetName() string { @@ -13383,6 +15058,13 @@ func (x *UndoDraftChunkRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSelect return nil } +func (x *UndoDraftChunkRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type UndoDraftChunkResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // New policy version after removal. @@ -13395,7 +15077,7 @@ type UndoDraftChunkResponse struct { func (x *UndoDraftChunkResponse) Reset() { *x = UndoDraftChunkResponse{} - mi := &file_openshell_proto_msgTypes[185] + mi := &file_openshell_proto_msgTypes[196] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13407,7 +15089,7 @@ func (x *UndoDraftChunkResponse) String() string { func (*UndoDraftChunkResponse) ProtoMessage() {} func (x *UndoDraftChunkResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[185] + mi := &file_openshell_proto_msgTypes[196] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13420,7 +15102,7 @@ func (x *UndoDraftChunkResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UndoDraftChunkResponse.ProtoReflect.Descriptor instead. func (*UndoDraftChunkResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{185} + return file_openshell_proto_rawDescGZIP(), []int{196} } func (x *UndoDraftChunkResponse) GetPolicyVersion() uint32 { @@ -13444,13 +15126,16 @@ type ClearDraftChunksRequest struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Explicit workspace scope. The all-workspaces selection is invalid. WorkspaceScope *datamodelv1.WorkspaceSelector `protobuf:"bytes,3,opt,name=workspace_scope,json=workspaceScope,proto3" json:"workspace_scope,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID for durable at-most-once admission. Successful results + // can be replayed for 24 hours; see the API errors and retries reference. + RequestId string `protobuf:"bytes,4,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ClearDraftChunksRequest) Reset() { *x = ClearDraftChunksRequest{} - mi := &file_openshell_proto_msgTypes[186] + mi := &file_openshell_proto_msgTypes[197] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13462,7 +15147,7 @@ func (x *ClearDraftChunksRequest) String() string { func (*ClearDraftChunksRequest) ProtoMessage() {} func (x *ClearDraftChunksRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[186] + mi := &file_openshell_proto_msgTypes[197] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13475,7 +15160,7 @@ func (x *ClearDraftChunksRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ClearDraftChunksRequest.ProtoReflect.Descriptor instead. func (*ClearDraftChunksRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{186} + return file_openshell_proto_rawDescGZIP(), []int{197} } func (x *ClearDraftChunksRequest) GetName() string { @@ -13492,6 +15177,13 @@ func (x *ClearDraftChunksRequest) GetWorkspaceScope() *datamodelv1.WorkspaceSele return nil } +func (x *ClearDraftChunksRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + type ClearDraftChunksResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // Number of chunks cleared. @@ -13502,7 +15194,7 @@ type ClearDraftChunksResponse struct { func (x *ClearDraftChunksResponse) Reset() { *x = ClearDraftChunksResponse{} - mi := &file_openshell_proto_msgTypes[187] + mi := &file_openshell_proto_msgTypes[198] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13514,7 +15206,7 @@ func (x *ClearDraftChunksResponse) String() string { func (*ClearDraftChunksResponse) ProtoMessage() {} func (x *ClearDraftChunksResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[187] + mi := &file_openshell_proto_msgTypes[198] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13527,7 +15219,7 @@ func (x *ClearDraftChunksResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ClearDraftChunksResponse.ProtoReflect.Descriptor instead. func (*ClearDraftChunksResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{187} + return file_openshell_proto_rawDescGZIP(), []int{198} } func (x *ClearDraftChunksResponse) GetChunksCleared() uint32 { @@ -13550,7 +15242,7 @@ type GetDraftHistoryRequest struct { func (x *GetDraftHistoryRequest) Reset() { *x = GetDraftHistoryRequest{} - mi := &file_openshell_proto_msgTypes[188] + mi := &file_openshell_proto_msgTypes[199] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13562,7 +15254,7 @@ func (x *GetDraftHistoryRequest) String() string { func (*GetDraftHistoryRequest) ProtoMessage() {} func (x *GetDraftHistoryRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[188] + mi := &file_openshell_proto_msgTypes[199] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13575,7 +15267,7 @@ func (x *GetDraftHistoryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetDraftHistoryRequest.ProtoReflect.Descriptor instead. func (*GetDraftHistoryRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{188} + return file_openshell_proto_rawDescGZIP(), []int{199} } func (x *GetDraftHistoryRequest) GetName() string { @@ -13609,7 +15301,7 @@ type DraftHistoryEntry struct { func (x *DraftHistoryEntry) Reset() { *x = DraftHistoryEntry{} - mi := &file_openshell_proto_msgTypes[189] + mi := &file_openshell_proto_msgTypes[200] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13621,7 +15313,7 @@ func (x *DraftHistoryEntry) String() string { func (*DraftHistoryEntry) ProtoMessage() {} func (x *DraftHistoryEntry) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[189] + mi := &file_openshell_proto_msgTypes[200] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13634,7 +15326,7 @@ func (x *DraftHistoryEntry) ProtoReflect() protoreflect.Message { // Deprecated: Use DraftHistoryEntry.ProtoReflect.Descriptor instead. func (*DraftHistoryEntry) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{189} + return file_openshell_proto_rawDescGZIP(), []int{200} } func (x *DraftHistoryEntry) GetEventTime() *timestamppb.Timestamp { @@ -13675,7 +15367,7 @@ type GetDraftHistoryResponse struct { func (x *GetDraftHistoryResponse) Reset() { *x = GetDraftHistoryResponse{} - mi := &file_openshell_proto_msgTypes[190] + mi := &file_openshell_proto_msgTypes[201] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13687,7 +15379,7 @@ func (x *GetDraftHistoryResponse) String() string { func (*GetDraftHistoryResponse) ProtoMessage() {} func (x *GetDraftHistoryResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[190] + mi := &file_openshell_proto_msgTypes[201] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13700,7 +15392,7 @@ func (x *GetDraftHistoryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetDraftHistoryResponse.ProtoReflect.Descriptor instead. func (*GetDraftHistoryResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{190} + return file_openshell_proto_rawDescGZIP(), []int{201} } func (x *GetDraftHistoryResponse) GetEntries() []*DraftHistoryEntry { @@ -13716,14 +15408,16 @@ type CreateWorkspaceRequest struct { // Workspace name. Must be a valid DNS-1123 label. Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Optional labels for the workspace (key-value metadata). - Labels map[string]string `protobuf:"bytes,2,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + Labels map[string]string `protobuf:"bytes,2,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + RequestId string `protobuf:"bytes,3,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *CreateWorkspaceRequest) Reset() { *x = CreateWorkspaceRequest{} - mi := &file_openshell_proto_msgTypes[191] + mi := &file_openshell_proto_msgTypes[202] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13735,7 +15429,7 @@ func (x *CreateWorkspaceRequest) String() string { func (*CreateWorkspaceRequest) ProtoMessage() {} func (x *CreateWorkspaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[191] + mi := &file_openshell_proto_msgTypes[202] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13748,7 +15442,7 @@ func (x *CreateWorkspaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateWorkspaceRequest.ProtoReflect.Descriptor instead. func (*CreateWorkspaceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{191} + return file_openshell_proto_rawDescGZIP(), []int{202} } func (x *CreateWorkspaceRequest) GetName() string { @@ -13765,6 +15459,13 @@ func (x *CreateWorkspaceRequest) GetLabels() map[string]string { return nil } +func (x *CreateWorkspaceRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Create workspace response. type CreateWorkspaceResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -13775,7 +15476,7 @@ type CreateWorkspaceResponse struct { func (x *CreateWorkspaceResponse) Reset() { *x = CreateWorkspaceResponse{} - mi := &file_openshell_proto_msgTypes[192] + mi := &file_openshell_proto_msgTypes[203] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13787,7 +15488,7 @@ func (x *CreateWorkspaceResponse) String() string { func (*CreateWorkspaceResponse) ProtoMessage() {} func (x *CreateWorkspaceResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[192] + mi := &file_openshell_proto_msgTypes[203] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13800,7 +15501,7 @@ func (x *CreateWorkspaceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateWorkspaceResponse.ProtoReflect.Descriptor instead. func (*CreateWorkspaceResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{192} + return file_openshell_proto_rawDescGZIP(), []int{203} } func (x *CreateWorkspaceResponse) GetWorkspace() *datamodelv1.Workspace { @@ -13821,7 +15522,7 @@ type GetWorkspaceRequest struct { func (x *GetWorkspaceRequest) Reset() { *x = GetWorkspaceRequest{} - mi := &file_openshell_proto_msgTypes[193] + mi := &file_openshell_proto_msgTypes[204] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13833,7 +15534,7 @@ func (x *GetWorkspaceRequest) String() string { func (*GetWorkspaceRequest) ProtoMessage() {} func (x *GetWorkspaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[193] + mi := &file_openshell_proto_msgTypes[204] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13846,7 +15547,7 @@ func (x *GetWorkspaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetWorkspaceRequest.ProtoReflect.Descriptor instead. func (*GetWorkspaceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{193} + return file_openshell_proto_rawDescGZIP(), []int{204} } func (x *GetWorkspaceRequest) GetName() string { @@ -13866,7 +15567,7 @@ type GetWorkspaceResponse struct { func (x *GetWorkspaceResponse) Reset() { *x = GetWorkspaceResponse{} - mi := &file_openshell_proto_msgTypes[194] + mi := &file_openshell_proto_msgTypes[205] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13878,7 +15579,7 @@ func (x *GetWorkspaceResponse) String() string { func (*GetWorkspaceResponse) ProtoMessage() {} func (x *GetWorkspaceResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[194] + mi := &file_openshell_proto_msgTypes[205] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13891,7 +15592,7 @@ func (x *GetWorkspaceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetWorkspaceResponse.ProtoReflect.Descriptor instead. func (*GetWorkspaceResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{194} + return file_openshell_proto_rawDescGZIP(), []int{205} } func (x *GetWorkspaceResponse) GetWorkspace() *datamodelv1.Workspace { @@ -13918,7 +15619,7 @@ type ListWorkspacesRequest struct { func (x *ListWorkspacesRequest) Reset() { *x = ListWorkspacesRequest{} - mi := &file_openshell_proto_msgTypes[195] + mi := &file_openshell_proto_msgTypes[206] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13930,7 +15631,7 @@ func (x *ListWorkspacesRequest) String() string { func (*ListWorkspacesRequest) ProtoMessage() {} func (x *ListWorkspacesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[195] + mi := &file_openshell_proto_msgTypes[206] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13943,7 +15644,7 @@ func (x *ListWorkspacesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkspacesRequest.ProtoReflect.Descriptor instead. func (*ListWorkspacesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{195} + return file_openshell_proto_rawDescGZIP(), []int{206} } func (x *ListWorkspacesRequest) GetPageSize() int32 { @@ -13979,7 +15680,7 @@ type ListWorkspacesResponse struct { func (x *ListWorkspacesResponse) Reset() { *x = ListWorkspacesResponse{} - mi := &file_openshell_proto_msgTypes[196] + mi := &file_openshell_proto_msgTypes[207] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13991,7 +15692,7 @@ func (x *ListWorkspacesResponse) String() string { func (*ListWorkspacesResponse) ProtoMessage() {} func (x *ListWorkspacesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[196] + mi := &file_openshell_proto_msgTypes[207] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14004,7 +15705,7 @@ func (x *ListWorkspacesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkspacesResponse.ProtoReflect.Descriptor instead. func (*ListWorkspacesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{196} + return file_openshell_proto_rawDescGZIP(), []int{207} } func (x *ListWorkspacesResponse) GetWorkspaces() []*datamodelv1.Workspace { @@ -14025,15 +15726,17 @@ func (x *ListWorkspacesResponse) GetNextPageToken() string { type DeleteWorkspaceRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Workspace name (canonical lookup key). - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - AllowMissing bool `protobuf:"varint,2,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + AllowMissing bool `protobuf:"varint,2,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + RequestId string `protobuf:"bytes,3,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *DeleteWorkspaceRequest) Reset() { *x = DeleteWorkspaceRequest{} - mi := &file_openshell_proto_msgTypes[197] + mi := &file_openshell_proto_msgTypes[208] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14045,7 +15748,7 @@ func (x *DeleteWorkspaceRequest) String() string { func (*DeleteWorkspaceRequest) ProtoMessage() {} func (x *DeleteWorkspaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[197] + mi := &file_openshell_proto_msgTypes[208] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14058,7 +15761,7 @@ func (x *DeleteWorkspaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteWorkspaceRequest.ProtoReflect.Descriptor instead. func (*DeleteWorkspaceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{197} + return file_openshell_proto_rawDescGZIP(), []int{208} } func (x *DeleteWorkspaceRequest) GetName() string { @@ -14075,6 +15778,13 @@ func (x *DeleteWorkspaceRequest) GetAllowMissing() bool { return false } +func (x *DeleteWorkspaceRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Delete workspace response. type DeleteWorkspaceResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -14085,7 +15795,7 @@ type DeleteWorkspaceResponse struct { func (x *DeleteWorkspaceResponse) Reset() { *x = DeleteWorkspaceResponse{} - mi := &file_openshell_proto_msgTypes[198] + mi := &file_openshell_proto_msgTypes[209] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14097,7 +15807,7 @@ func (x *DeleteWorkspaceResponse) String() string { func (*DeleteWorkspaceResponse) ProtoMessage() {} func (x *DeleteWorkspaceResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[198] + mi := &file_openshell_proto_msgTypes[209] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14110,7 +15820,7 @@ func (x *DeleteWorkspaceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteWorkspaceResponse.ProtoReflect.Descriptor instead. func (*DeleteWorkspaceResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{198} + return file_openshell_proto_rawDescGZIP(), []int{209} } func (x *DeleteWorkspaceResponse) GetOutcome() DeletionOutcome { @@ -14134,7 +15844,7 @@ type WorkspaceMember struct { func (x *WorkspaceMember) Reset() { *x = WorkspaceMember{} - mi := &file_openshell_proto_msgTypes[199] + mi := &file_openshell_proto_msgTypes[210] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14146,7 +15856,7 @@ func (x *WorkspaceMember) String() string { func (*WorkspaceMember) ProtoMessage() {} func (x *WorkspaceMember) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[199] + mi := &file_openshell_proto_msgTypes[210] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14159,7 +15869,7 @@ func (x *WorkspaceMember) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceMember.ProtoReflect.Descriptor instead. func (*WorkspaceMember) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{199} + return file_openshell_proto_rawDescGZIP(), []int{210} } func (x *WorkspaceMember) GetMetadata() *datamodelv1.ObjectMeta { @@ -14191,14 +15901,16 @@ type AddWorkspaceMemberRequest struct { // OIDC subject claim identifying the principal. PrincipalSubject string `protobuf:"bytes,2,opt,name=principal_subject,json=principalSubject,proto3" json:"principal_subject,omitempty"` // Role to assign. - Role WorkspaceRole `protobuf:"varint,3,opt,name=role,proto3,enum=openshell.v1.WorkspaceRole" json:"role,omitempty"` + Role WorkspaceRole `protobuf:"varint,3,opt,name=role,proto3,enum=openshell.v1.WorkspaceRole" json:"role,omitempty"` + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + RequestId string `protobuf:"bytes,4,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AddWorkspaceMemberRequest) Reset() { *x = AddWorkspaceMemberRequest{} - mi := &file_openshell_proto_msgTypes[200] + mi := &file_openshell_proto_msgTypes[211] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14210,7 +15922,7 @@ func (x *AddWorkspaceMemberRequest) String() string { func (*AddWorkspaceMemberRequest) ProtoMessage() {} func (x *AddWorkspaceMemberRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[200] + mi := &file_openshell_proto_msgTypes[211] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14223,7 +15935,7 @@ func (x *AddWorkspaceMemberRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use AddWorkspaceMemberRequest.ProtoReflect.Descriptor instead. func (*AddWorkspaceMemberRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{200} + return file_openshell_proto_rawDescGZIP(), []int{211} } func (x *AddWorkspaceMemberRequest) GetWorkspace() string { @@ -14247,6 +15959,13 @@ func (x *AddWorkspaceMemberRequest) GetRole() WorkspaceRole { return WorkspaceRole_WORKSPACE_ROLE_UNSPECIFIED } +func (x *AddWorkspaceMemberRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Add workspace member response. type AddWorkspaceMemberResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -14257,7 +15976,7 @@ type AddWorkspaceMemberResponse struct { func (x *AddWorkspaceMemberResponse) Reset() { *x = AddWorkspaceMemberResponse{} - mi := &file_openshell_proto_msgTypes[201] + mi := &file_openshell_proto_msgTypes[212] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14269,7 +15988,7 @@ func (x *AddWorkspaceMemberResponse) String() string { func (*AddWorkspaceMemberResponse) ProtoMessage() {} func (x *AddWorkspaceMemberResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[201] + mi := &file_openshell_proto_msgTypes[212] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14282,7 +16001,7 @@ func (x *AddWorkspaceMemberResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use AddWorkspaceMemberResponse.ProtoReflect.Descriptor instead. func (*AddWorkspaceMemberResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{201} + return file_openshell_proto_rawDescGZIP(), []int{212} } func (x *AddWorkspaceMemberResponse) GetMember() *WorkspaceMember { @@ -14300,13 +16019,15 @@ type RemoveWorkspaceMemberRequest struct { // OIDC subject claim identifying the principal to remove. PrincipalSubject string `protobuf:"bytes,2,opt,name=principal_subject,json=principalSubject,proto3" json:"principal_subject,omitempty"` AllowMissing bool `protobuf:"varint,3,opt,name=allow_missing,json=allowMissing,proto3" json:"allow_missing,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Optional nonzero UUID. Same ID and payload replay success for 24 hours. + RequestId string `protobuf:"bytes,4,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RemoveWorkspaceMemberRequest) Reset() { *x = RemoveWorkspaceMemberRequest{} - mi := &file_openshell_proto_msgTypes[202] + mi := &file_openshell_proto_msgTypes[213] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14318,7 +16039,7 @@ func (x *RemoveWorkspaceMemberRequest) String() string { func (*RemoveWorkspaceMemberRequest) ProtoMessage() {} func (x *RemoveWorkspaceMemberRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[202] + mi := &file_openshell_proto_msgTypes[213] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14331,7 +16052,7 @@ func (x *RemoveWorkspaceMemberRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveWorkspaceMemberRequest.ProtoReflect.Descriptor instead. func (*RemoveWorkspaceMemberRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{202} + return file_openshell_proto_rawDescGZIP(), []int{213} } func (x *RemoveWorkspaceMemberRequest) GetWorkspace() string { @@ -14355,6 +16076,13 @@ func (x *RemoveWorkspaceMemberRequest) GetAllowMissing() bool { return false } +func (x *RemoveWorkspaceMemberRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + // Remove workspace member response. type RemoveWorkspaceMemberResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -14365,7 +16093,7 @@ type RemoveWorkspaceMemberResponse struct { func (x *RemoveWorkspaceMemberResponse) Reset() { *x = RemoveWorkspaceMemberResponse{} - mi := &file_openshell_proto_msgTypes[203] + mi := &file_openshell_proto_msgTypes[214] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14377,7 +16105,7 @@ func (x *RemoveWorkspaceMemberResponse) String() string { func (*RemoveWorkspaceMemberResponse) ProtoMessage() {} func (x *RemoveWorkspaceMemberResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[203] + mi := &file_openshell_proto_msgTypes[214] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14390,7 +16118,7 @@ func (x *RemoveWorkspaceMemberResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveWorkspaceMemberResponse.ProtoReflect.Descriptor instead. func (*RemoveWorkspaceMemberResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{203} + return file_openshell_proto_rawDescGZIP(), []int{214} } func (x *RemoveWorkspaceMemberResponse) GetOutcome() DeletionOutcome { @@ -14417,7 +16145,7 @@ type ListWorkspaceMembersRequest struct { func (x *ListWorkspaceMembersRequest) Reset() { *x = ListWorkspaceMembersRequest{} - mi := &file_openshell_proto_msgTypes[204] + mi := &file_openshell_proto_msgTypes[215] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14429,7 +16157,7 @@ func (x *ListWorkspaceMembersRequest) String() string { func (*ListWorkspaceMembersRequest) ProtoMessage() {} func (x *ListWorkspaceMembersRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[204] + mi := &file_openshell_proto_msgTypes[215] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14442,7 +16170,7 @@ func (x *ListWorkspaceMembersRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkspaceMembersRequest.ProtoReflect.Descriptor instead. func (*ListWorkspaceMembersRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{204} + return file_openshell_proto_rawDescGZIP(), []int{215} } func (x *ListWorkspaceMembersRequest) GetWorkspace() string { @@ -14478,7 +16206,7 @@ type ListWorkspaceMembersResponse struct { func (x *ListWorkspaceMembersResponse) Reset() { *x = ListWorkspaceMembersResponse{} - mi := &file_openshell_proto_msgTypes[205] + mi := &file_openshell_proto_msgTypes[216] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14490,7 +16218,7 @@ func (x *ListWorkspaceMembersResponse) String() string { func (*ListWorkspaceMembersResponse) ProtoMessage() {} func (x *ListWorkspaceMembersResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[205] + mi := &file_openshell_proto_msgTypes[216] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14503,7 +16231,7 @@ func (x *ListWorkspaceMembersResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkspaceMembersResponse.ProtoReflect.Descriptor instead. func (*ListWorkspaceMembersResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{205} + return file_openshell_proto_rawDescGZIP(), []int{216} } func (x *ListWorkspaceMembersResponse) GetMembers() []*WorkspaceMember { @@ -14538,7 +16266,7 @@ type ExtensionServiceCredential struct { func (x *ExtensionServiceCredential) Reset() { *x = ExtensionServiceCredential{} - mi := &file_openshell_proto_msgTypes[206] + mi := &file_openshell_proto_msgTypes[217] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14550,7 +16278,7 @@ func (x *ExtensionServiceCredential) String() string { func (*ExtensionServiceCredential) ProtoMessage() {} func (x *ExtensionServiceCredential) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[206] + mi := &file_openshell_proto_msgTypes[217] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14563,7 +16291,7 @@ func (x *ExtensionServiceCredential) ProtoReflect() protoreflect.Message { // Deprecated: Use ExtensionServiceCredential.ProtoReflect.Descriptor instead. func (*ExtensionServiceCredential) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{206} + return file_openshell_proto_rawDescGZIP(), []int{217} } func (x *ExtensionServiceCredential) GetServiceName() string { @@ -14600,7 +16328,7 @@ type EndpointObservation struct { func (x *EndpointObservation) Reset() { *x = EndpointObservation{} - mi := &file_openshell_proto_msgTypes[207] + mi := &file_openshell_proto_msgTypes[218] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14612,7 +16340,7 @@ func (x *EndpointObservation) String() string { func (*EndpointObservation) ProtoMessage() {} func (x *EndpointObservation) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[207] + mi := &file_openshell_proto_msgTypes[218] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14625,7 +16353,7 @@ func (x *EndpointObservation) ProtoReflect() protoreflect.Message { // Deprecated: Use EndpointObservation.ProtoReflect.Descriptor instead. func (*EndpointObservation) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{207} + return file_openshell_proto_rawDescGZIP(), []int{218} } func (x *EndpointObservation) GetEndpointId() string { @@ -14668,7 +16396,7 @@ type ReportEndpointStatusRequest struct { func (x *ReportEndpointStatusRequest) Reset() { *x = ReportEndpointStatusRequest{} - mi := &file_openshell_proto_msgTypes[208] + mi := &file_openshell_proto_msgTypes[219] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14680,7 +16408,7 @@ func (x *ReportEndpointStatusRequest) String() string { func (*ReportEndpointStatusRequest) ProtoMessage() {} func (x *ReportEndpointStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[208] + mi := &file_openshell_proto_msgTypes[219] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14693,7 +16421,7 @@ func (x *ReportEndpointStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportEndpointStatusRequest.ProtoReflect.Descriptor instead. func (*ReportEndpointStatusRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{208} + return file_openshell_proto_rawDescGZIP(), []int{219} } func (x *ReportEndpointStatusRequest) GetSandboxId() string { @@ -14754,7 +16482,7 @@ type ReportEndpointStatusResponse struct { func (x *ReportEndpointStatusResponse) Reset() { *x = ReportEndpointStatusResponse{} - mi := &file_openshell_proto_msgTypes[209] + mi := &file_openshell_proto_msgTypes[220] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14766,7 +16494,7 @@ func (x *ReportEndpointStatusResponse) String() string { func (*ReportEndpointStatusResponse) ProtoMessage() {} func (x *ReportEndpointStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[209] + mi := &file_openshell_proto_msgTypes[220] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14779,7 +16507,7 @@ func (x *ReportEndpointStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportEndpointStatusResponse.ProtoReflect.Descriptor instead. func (*ReportEndpointStatusResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{209} + return file_openshell_proto_rawDescGZIP(), []int{220} } // A configured endpoint and its last accepted network result in one record. @@ -14808,7 +16536,7 @@ type EndpointStatus struct { func (x *EndpointStatus) Reset() { *x = EndpointStatus{} - mi := &file_openshell_proto_msgTypes[210] + mi := &file_openshell_proto_msgTypes[221] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14820,7 +16548,7 @@ func (x *EndpointStatus) String() string { func (*EndpointStatus) ProtoMessage() {} func (x *EndpointStatus) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[210] + mi := &file_openshell_proto_msgTypes[221] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14833,7 +16561,7 @@ func (x *EndpointStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use EndpointStatus.ProtoReflect.Descriptor instead. func (*EndpointStatus) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{210} + return file_openshell_proto_rawDescGZIP(), []int{221} } func (x *EndpointStatus) GetEndpointId() string { @@ -14937,7 +16665,7 @@ const file_openshell_proto_rawDesc = "" + "\bmetadata\x18\x01 \x01(\v2\".openshell.datamodel.v1.ObjectMetaR\bmetadata\x12-\n" + "\x04spec\x18\x02 \x01(\v2\x19.openshell.v1.SandboxSpecR\x04spec\x123\n" + "\x06status\x18\x03 \x01(\v2\x1b.openshell.v1.SandboxStatusR\x06status\x12t\n" + - "\x1ecreated_from_workload_template\x18\x14 \x01(\v2/.openshell.v1.SandboxWorkloadTemplateProvenanceR\x1bcreatedFromWorkloadTemplateJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\x05phaseR\x16current_policy_version\"\x83\x04\n" + + "\x1ecreated_from_workload_template\x18\x14 \x01(\v2/.openshell.v1.SandboxWorkloadTemplateProvenanceR\x1bcreatedFromWorkloadTemplateJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\x05phaseR\x16current_policy_version\"\xbf\x04\n" + "\vSandboxSpec\x12\x1b\n" + "\tlog_level\x18\x01 \x01(\tR\blogLevel\x12L\n" + "\venvironment\x18\x05 \x03(\v2*.openshell.v1.SandboxSpec.EnvironmentEntryR\venvironment\x129\n" + @@ -14946,7 +16674,8 @@ const file_openshell_proto_rawDesc = "" + "\tproviders\x18\b \x03(\tR\tproviders\x12W\n" + "\x15resource_requirements\x18\t \x01(\v2\".openshell.v1.ResourceRequirementsR\x14resourceRequirements\x12\x18\n" + "\acommand\x18\f \x03(\tR\acommand\x12\x10\n" + - "\x03tty\x18\r \x01(\bR\x03tty\x1a>\n" + + "\x03tty\x18\r \x01(\bR\x03tty\x12:\n" + + "\x19provider_attachment_epoch\x18\x0e \x01(\tR\x17providerAttachmentEpoch\x1a>\n" + "\x10EnvironmentEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\n" + @@ -15038,7 +16767,7 @@ const file_openshell_proto_rawDesc = "" + "\bmetadata\x18\x06 \x03(\v2).openshell.v1.PlatformEvent.MetadataEntryR\bmetadata\x1a;\n" + "\rMetadataEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\x01\x10\x02R\ftimestamp_ms\"\xd1\x04\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\x01\x10\x02R\ftimestamp_ms\"\xf0\x04\n" + "\x14CreateSandboxRequest\x12-\n" + "\x04spec\x18\x01 \x01(\v2\x19.openshell.v1.SandboxSpecR\x04spec\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x12F\n" + @@ -15046,16 +16775,20 @@ const file_openshell_proto_rawDesc = "" + "\vannotations\x18\x04 \x03(\v23.openshell.v1.CreateSandboxRequest.AnnotationsEntryR\vannotations\x12A\n" + "\x1dawait_main_process_attachment\x18\x06 \x01(\bR\x1aawaitMainProcessAttachment\x124\n" + "\x16workload_template_name\x18\a \x01(\tR\x14workloadTemplateName\x12R\n" + - "\x0fworkspace_scope\x18\b \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x1a9\n" + + "\x0fworkspace_scope\x18\b \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\t \x01(\tR\trequestId\x1a9\n" + "\vLabelsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1a>\n" + "\x10AnnotationsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\x05\x10\x06R\tworkspace\"\xc6\x01\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\x05\x10\x06R\tworkspace\"\xe5\x01\n" + "\x1cCreateSandboxTemplateRequest\x12A\n" + "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x94\x01\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x04 \x01(\tR\trequestIdJ\x04\b\x02\x10\x03R\tworkspace\"\x94\x01\n" + "\x19GetSandboxTemplateRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xfb\x01\n" + @@ -15064,11 +16797,13 @@ const file_openshell_proto_rawDesc = "" + "\n" + "page_token\x18\x02 \x01(\tR\tpageToken\x12%\n" + "\x0elabel_selector\x18\x05 \x01(\tR\rlabelSelector\x12R\n" + - "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\tworkspaceR\x0eall_workspaces\"\xbc\x01\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\tworkspaceR\x0eall_workspaces\"\xdb\x01\n" + "\x1cDeleteSandboxTemplateRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12#\n" + - "\rallow_missing\x18\x04 \x01(\bR\fallowMissingJ\x04\b\x02\x10\x03R\tworkspace\"\\\n" + + "\rallow_missing\x18\x04 \x01(\bR\fallowMissing\x12\x1d\n" + + "\n" + + "request_id\x18\x05 \x01(\tR\trequestIdJ\x04\b\x02\x10\x03R\tworkspace\"\\\n" + "\x17SandboxTemplateResponse\x12A\n" + "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\"\x8b\x01\n" + "\x1cListSandboxTemplatesResponse\x12C\n" + @@ -15098,40 +16833,139 @@ const file_openshell_proto_rawDesc = "" + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\tworkspaceR\x0eall_workspaces\"\xa5\x01\n" + "\x1bListSandboxProvidersRequest\x12!\n" + "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x87\x02\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xa6\x02\n" + "\x1cAttachSandboxProviderRequest\x12!\n" + "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12#\n" + "\rprovider_name\x18\x02 \x01(\tR\fproviderName\x12:\n" + "\x19expected_resource_version\x18\x03 \x01(\x04R\x17expectedResourceVersion\x12R\n" + - "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x87\x02\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x06 \x01(\tR\trequestIdJ\x04\b\x04\x10\x05R\tworkspace\"\xa6\x02\n" + "\x1cDetachSandboxProviderRequest\x12!\n" + "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12#\n" + "\rprovider_name\x18\x02 \x01(\tR\fproviderName\x12:\n" + "\x19expected_resource_version\x18\x03 \x01(\x04R\x17expectedResourceVersion\x12R\n" + - "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\xb4\x01\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x06 \x01(\tR\trequestIdJ\x04\b\x04\x10\x05R\tworkspace\"\xd3\x01\n" + "\x14DeleteSandboxRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12#\n" + - "\rallow_missing\x18\x04 \x01(\bR\fallowMissingJ\x04\b\x02\x10\x03R\tworkspace\"\x8d\x01\n" + + "\rallow_missing\x18\x04 \x01(\bR\fallowMissing\x12\x1d\n" + + "\n" + + "request_id\x18\x05 \x01(\tR\trequestIdJ\x04\b\x02\x10\x03R\tworkspace\"\xac\x01\n" + "\x12StopSandboxRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x8e\x01\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x04 \x01(\tR\trequestIdJ\x04\b\x02\x10\x03R\tworkspace\"\xad\x01\n" + "\x13StartSandboxRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"B\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x04 \x01(\tR\trequestIdJ\x04\b\x02\x10\x03R\tworkspace\"B\n" + "\x0fSandboxResponse\x12/\n" + "\asandbox\x18\x01 \x01(\v2\x15.openshell.v1.SandboxR\asandbox\"t\n" + "\x15ListSandboxesResponse\x123\n" + "\tsandboxes\x18\x01 \x03(\v2\x15.openshell.v1.SandboxR\tsandboxes\x12&\n" + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"^\n" + "\x1cListSandboxProvidersResponse\x12>\n" + - "\tproviders\x18\x01 \x03(\v2 .openshell.datamodel.v1.ProviderR\tproviders\"l\n" + + "\tproviders\x18\x01 \x03(\v2 .openshell.datamodel.v1.ProviderR\tproviders\"\xad\x01\n" + "\x1dAttachSandboxProviderResponse\x12/\n" + "\asandbox\x18\x01 \x01(\v2\x15.openshell.v1.SandboxR\asandbox\x12\x1a\n" + - "\battached\x18\x02 \x01(\bR\battached\"l\n" + + "\battached\x18\x02 \x01(\bR\battached\x12?\n" + + "\areceipt\x18\x03 \x01(\v2%.openshell.v1.ProviderMutationReceiptR\areceipt\"\xad\x01\n" + "\x1dDetachSandboxProviderResponse\x12/\n" + "\asandbox\x18\x01 \x01(\v2\x15.openshell.v1.SandboxR\asandbox\x12\x1a\n" + - "\bdetached\x18\x02 \x01(\bR\bdetached\"~\n" + + "\bdetached\x18\x02 \x01(\bR\bdetached\x12?\n" + + "\areceipt\x18\x03 \x01(\v2%.openshell.v1.ProviderMutationReceiptR\areceipt\"\xe1\x02\n" + + "\x17ProviderDesiredIdentity\x12\x1d\n" + + "\n" + + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12!\n" + + "\fsandbox_name\x18\x02 \x01(\tR\vsandboxName\x12)\n" + + "\x10attachment_epoch\x18\x03 \x01(\tR\x0fattachmentEpoch\x12\x1f\n" + + "\vprovider_id\x18\x04 \x01(\tR\n" + + "providerId\x12:\n" + + "\x19provider_resource_version\x18\x05 \x01(\x04R\x17providerResourceVersion\x122\n" + + "\x15provider_env_revision\x18\x06 \x01(\x04R\x13providerEnvRevision\x12'\n" + + "\x0fconfig_revision\x18\a \x01(\x04R\x0econfigRevision\x12\x1f\n" + + "\vpolicy_hash\x18\b \x01(\tR\n" + + "policyHash\"\xfa\x01\n" + + "\x16ConfigSnapshotRevision\x12L\n" + + "\x0esandbox_config\x18\x01 \x01(\v2#.openshell.v1.SandboxConfigRevisionH\x00R\rsandboxConfig\x123\n" + + "\x14provider_environment\x18\x02 \x01(\x04H\x00R\x13providerEnvironment\x12P\n" + + "\x0fprovider_target\x18\x03 \x01(\v2%.openshell.v1.ProviderDesiredIdentityH\x00R\x0eproviderTargetB\v\n" + + "\tcomponent\"\x91\x02\n" + + "\x15SandboxConfigRevision\x12'\n" + + "\x0fconfig_revision\x18\x01 \x01(\x04R\x0econfigRevision\x12%\n" + + "\x0epolicy_version\x18\x02 \x01(\rR\rpolicyVersion\x12G\n" + + "\rpolicy_source\x18\x03 \x01(\x0e2\".openshell.sandbox.v1.PolicySourceR\fpolicySource\x122\n" + + "\x15global_policy_version\x18\x04 \x01(\rR\x13globalPolicyVersion\x12+\n" + + "\x11settings_revision\x18\x05 \x01(\x04R\x10settingsRevision\"\x8c\x05\n" + + "\x15ConfigUpdateOperation\x12!\n" + + "\foperation_id\x18\x01 \x01(\tR\voperationId\x12\x1d\n" + + "\n" + + "sandbox_id\x18\x02 \x01(\tR\tsandboxId\x12;\n" + + "\tcomponent\x18\x03 \x01(\x0e2\x1d.openshell.v1.ConfigComponentR\tcomponent\x12M\n" + + "\x0ftarget_revision\x18\x04 \x01(\v2$.openshell.v1.ConfigSnapshotRevisionR\x0etargetRevision\x12>\n" + + "\x05state\x18\x05 \x01(\x0e2(.openshell.v1.ConfigUpdateOperationStateR\x05state\x12:\n" + + "\aoutcome\x18\x06 \x01(\x0e2 .openshell.v1.ConfigApplyOutcomeR\aoutcome\x12'\n" + + "\x0fsanitized_error\x18\a \x01(\tR\x0esanitizedError\x12=\n" + + "\fcreated_time\x18l \x01(\v2\x1a.google.protobuf.TimestampR\vcreatedTime\x12=\n" + + "\fupdated_time\x18m \x01(\v2\x1a.google.protobuf.TimestampR\vupdatedTime\x12A\n" + + "\x0ecompleted_time\x18n \x01(\v2\x1a.google.protobuf.TimestampR\rcompletedTimeJ\x04\b\b\x10\tJ\x04\b\t\x10\n" + + "J\x04\b\n" + + "\x10\vR\rcreated_at_msR\rupdated_at_msR\x0fcompleted_at_ms\"\xef\x02\n" + + "\x17ProviderMutationReceipt\x12\x1d\n" + + "\n" + + "receipt_id\x18\x01 \x01(\tR\treceiptId\x12\x1f\n" + + "\vmutation_id\x18\x02 \x01(\tR\n" + + "mutationId\x12#\n" + + "\rprovider_name\x18\x03 \x01(\tR\fproviderName\x12\x1c\n" + + "\tworkspace\x18\x04 \x01(\tR\tworkspace\x126\n" + + "\x04kind\x18\x05 \x01(\x0e2\".openshell.v1.ProviderMutationKindR\x04kind\x12?\n" + + "\adesired\x18\x06 \x01(\v2%.openshell.v1.ProviderDesiredIdentityR\adesired\x12A\n" + + "\x0epersisted_time\x18k \x01(\v2\x1a.google.protobuf.TimestampR\rpersistedTimeJ\x04\b\a\x10\bR\x0fpersisted_at_ms\"\x8d\x04\n" + + "\x1cProviderReadinessObservation\x12\x1d\n" + + "\n" + + "session_id\x18\x01 \x01(\tR\tsessionId\x12\x1a\n" + + "\bsequence\x18\x02 \x01(\x04R\bsequence\x12)\n" + + "\x10attachment_epoch\x18\x03 \x01(\tR\x0fattachmentEpoch\x122\n" + + "\x15provider_env_revision\x18\x04 \x01(\x04R\x13providerEnvRevision\x12'\n" + + "\x0fconfig_revision\x18\x05 \x01(\x04R\x0econfigRevision\x12\x1f\n" + + "\vpolicy_hash\x18\x06 \x01(\tR\n" + + "policyHash\x123\n" + + "\x15credentials_installed\x18\a \x01(\bR\x14credentialsInstalled\x12#\n" + + "\rpolicy_active\x18\b \x01(\bR\fpolicyActive\x12@\n" + + "\x1claunch_environment_installed\x18\t \x01(\bR\x1alaunchEnvironmentInstalled\x12.\n" + + "\x13process_instance_id\x18\n" + + " \x01(\tR\x11processInstanceId\x12=\n" + + "\x06reason\x18\v \x01(\x0e2%.openshell.v1.ProviderReadinessReasonR\x06reason\"\xc1\x04\n" + + "\x17ProviderReadinessStatus\x12?\n" + + "\areceipt\x18\x01 \x01(\v2%.openshell.v1.ProviderMutationReceiptR\areceipt\x12:\n" + + "\x05state\x18\x02 \x01(\x0e2$.openshell.v1.ProviderReadinessStateR\x05state\x12=\n" + + "\x06reason\x18\x03 \x01(\x0e2%.openshell.v1.ProviderReadinessReasonR\x06reason\x12F\n" + + "\bobserved\x18\x04 \x01(\v2*.openshell.v1.ProviderReadinessObservationR\bobserved\x12.\n" + + "\x13network_instance_id\x18\x05 \x01(\tR\x11networkInstanceId\x12?\n" + + "\robserved_time\x18j \x01(\v2\x1a.google.protobuf.TimestampR\fobservedTime\x12A\n" + + "\x0eevaluated_time\x18k \x01(\v2\x1a.google.protobuf.TimestampR\revaluatedTime\x12A\n" + + "\toperation\x18\b \x01(\v2#.openshell.v1.ConfigUpdateOperationR\toperationJ\x04\b\x06\x10\aJ\x04\b\a\x10\bR\x0eobserved_at_msR\x0fevaluated_at_ms\"\xdc\x01\n" + + "\x1fGetSandboxProviderStatusRequest\x12!\n" + + "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12#\n" + + "\rprovider_name\x18\x02 \x01(\tR\fproviderName\x12\x1d\n" + + "\n" + + "receipt_id\x18\x03 \x01(\tR\treceiptId\x12R\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\"a\n" + + " GetSandboxProviderStatusResponse\x12=\n" + + "\x06status\x18\x01 \x01(\v2%.openshell.v1.ProviderReadinessStatusR\x06status\"\x8d\x01\n" + + "\x1eReportProviderReadinessRequest\x12\x1d\n" + + "\n" + + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12L\n" + + "\vobservation\x18\x02 \x01(\v2*.openshell.v1.ProviderReadinessObservationR\vobservation\"\x94\x02\n" + + "\x1fReportProviderReadinessResponse\x12+\n" + + "\x11accepted_sequence\x18\x01 \x01(\x04R\x10acceptedSequence\x12B\n" + + "\x0freport_interval\x18f \x01(\v2\x19.google.protobuf.DurationR\x0ereportInterval\x12B\n" + + "\x0fobservation_ttl\x18g \x01(\v2\x19.google.protobuf.DurationR\x0eobservationTtlJ\x04\b\x02\x10\x03J\x04\b\x03\x10\x04R\x17report_interval_secondsR\x17observation_ttl_seconds\"~\n" + "\x15DeleteSandboxResponse\x127\n" + "\aoutcome\x18\x02 \x01(\x0e2\x1d.openshell.v1.DeletionOutcomeR\aoutcome\x12\x1d\n" + "\n" + @@ -15147,14 +16981,16 @@ const file_openshell_proto_rawDesc = "" + "\fgateway_port\x18\x04 \x01(\rR\vgatewayPort\x12%\n" + "\x0egateway_scheme\x18\x05 \x01(\tR\rgatewayScheme\x120\n" + "\x14host_key_fingerprint\x18\a \x01(\tR\x12hostKeyFingerprint\x12C\n" + - "\x0fexpiration_time\x18l \x01(\v2\x1a.google.protobuf.TimestampR\x0eexpirationTimeJ\x04\b\b\x10\tR\rexpires_at_ms\"\xe8\x01\n" + + "\x0fexpiration_time\x18l \x01(\v2\x1a.google.protobuf.TimestampR\x0eexpirationTimeJ\x04\b\b\x10\tR\rexpires_at_ms\"\x87\x02\n" + "\x14ExposeServiceRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x18\n" + "\aservice\x18\x02 \x01(\tR\aservice\x12\x1f\n" + "\vtarget_port\x18\x03 \x01(\rR\n" + "targetPort\x12\x16\n" + "\x06domain\x18\x04 \x01(\bR\x06domain\x12R\n" + - "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x05\x10\x06R\tworkspace\"\xac\x01\n" + + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\a \x01(\tR\trequestIdJ\x04\b\x05\x10\x06R\tworkspace\"\xac\x01\n" + "\x11GetServiceRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x18\n" + "\aservice\x18\x02 \x01(\tR\aservice\x12R\n" + @@ -15167,12 +17003,14 @@ const file_openshell_proto_rawDesc = "" + "\x0fworkspace_scope\x18\x06 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\tworkspaceR\x0eall_workspaces\"\x81\x01\n" + "\x14ListServicesResponse\x12A\n" + "\bservices\x18\x01 \x03(\v2%.openshell.v1.ServiceEndpointResponseR\bservices\x12&\n" + - "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xd4\x01\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xf3\x01\n" + "\x14DeleteServiceRequest\x12\x18\n" + "\asandbox\x18\x01 \x01(\tR\asandbox\x12\x18\n" + "\aservice\x18\x02 \x01(\tR\aservice\x12R\n" + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12#\n" + - "\rallow_missing\x18\x05 \x01(\bR\fallowMissingJ\x04\b\x03\x10\x04R\tworkspace\"_\n" + + "\rallow_missing\x18\x05 \x01(\bR\fallowMissing\x12\x1d\n" + + "\n" + + "request_id\x18\x06 \x01(\tR\trequestIdJ\x04\b\x03\x10\x04R\tworkspace\"_\n" + "\x15DeleteServiceResponse\x127\n" + "\aoutcome\x18\x02 \x01(\x0e2\x1d.openshell.v1.DeletionOutcomeR\aoutcomeJ\x04\b\x01\x10\x02R\adeleted\"\xef\x01\n" + "\x0fServiceEndpoint\x12>\n" + @@ -15285,10 +17123,12 @@ const file_openshell_proto_rawDesc = "" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\x02\x10\x03R\ftimestamp_ms\"0\n" + "\x14SandboxStreamWarning\x12\x18\n" + - "\amessage\x18\x01 \x01(\tR\amessage\"\xba\x01\n" + + "\amessage\x18\x01 \x01(\tR\amessage\"\xd9\x01\n" + "\x15CreateProviderRequest\x12<\n" + "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\x8d\x01\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x04 \x01(\tR\trequestIdJ\x04\b\x02\x10\x03R\tworkspace\"\x8d\x01\n" + "\x12GetProviderRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"\xcd\x01\n" + @@ -15296,21 +17136,28 @@ const file_openshell_proto_rawDesc = "" + "\tpage_size\x18\x01 \x01(\x05R\bpageSize\x12\x1d\n" + "\n" + "page_token\x18\x02 \x01(\tR\tpageToken\x12R\n" + - "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\tworkspaceR\x0eall_workspaces\"\x92\x04\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04J\x04\b\x04\x10\x05R\tworkspaceR\x0eall_workspaces\"\xb1\x04\n" + "\x15UpdateProviderRequest\x12<\n" + "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\x12\x82\x01\n" + "\x1bcredential_expiration_times\x18f \x03(\v2B.openshell.v1.UpdateProviderRequest.CredentialExpirationTimesEntryR\x19credentialExpirationTimes\x12G\n" + " clear_credential_expiration_keys\x18g \x03(\tR\x1dclearCredentialExpirationKeys\x12R\n" + - "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x1ah\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x05 \x01(\tR\trequestId\x1ah\n" + "\x1eCredentialExpirationTimesEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x120\n" + - "\x05value\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x05value:\x028\x01J\x04\b\x03\x10\x04J\x04\b\x02\x10\x03R\tworkspaceR\x18credential_expires_at_ms\"\xb5\x01\n" + + "\x05value\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x05value:\x028\x01J\x04\b\x03\x10\x04J\x04\b\x02\x10\x03R\tworkspaceR\x18credential_expires_at_ms\"\xd4\x01\n" + "\x15DeleteProviderRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12#\n" + - "\rallow_missing\x18\x04 \x01(\bR\fallowMissingJ\x04\b\x02\x10\x03R\tworkspace\"P\n" + + "\rallow_missing\x18\x04 \x01(\bR\fallowMissing\x12\x1d\n" + + "\n" + + "request_id\x18\x05 \x01(\tR\trequestIdJ\x04\b\x02\x10\x03R\tworkspace\"\xc1\x01\n" + "\x10ProviderResponse\x12<\n" + - "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\"\x7f\n" + + "\bprovider\x18\x01 \x01(\v2 .openshell.datamodel.v1.ProviderR\bprovider\x12N\n" + + "\x0ftarget_receipts\x18\x02 \x03(\v2%.openshell.v1.ProviderMutationReceiptR\x0etargetReceipts\x12\x1f\n" + + "\vmutation_id\x18\x03 \x01(\tR\n" + + "mutationId\"\x7f\n" + "\x15ListProvidersResponse\x12>\n" + "\tproviders\x18\x01 \x03(\v2 .openshell.datamodel.v1.ProviderR\tproviders\x12&\n" + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"w\n" + @@ -15415,7 +17262,7 @@ const file_openshell_proto_rawDesc = "" + "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12R\n" + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"s\n" + " GetProviderRefreshStatusResponse\x12O\n" + - "\vcredentials\x18\x01 \x03(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\vcredentials\"\xbe\x04\n" + + "\vcredentials\x18\x01 \x03(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\vcredentials\"\xdd\x04\n" + "\x1fConfigureProviderRefreshRequest\x12\x1a\n" + "\bprovider\x18\x01 \x01(\tR\bprovider\x12%\n" + "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12K\n" + @@ -15423,23 +17270,29 @@ const file_openshell_proto_rawDesc = "" + "\bmaterial\x18\x04 \x03(\v2;.openshell.v1.ConfigureProviderRefreshRequest.MaterialEntryB\x04\x88\xb5\x18\x01R\bmaterial\x120\n" + "\x14secret_material_keys\x18\x05 \x03(\tR\x12secretMaterialKeys\x12C\n" + "\x0fexpiration_time\x18j \x01(\v2\x1a.google.protobuf.TimestampR\x0eexpirationTime\x12R\n" + - "\x0fworkspace_scope\x18\b \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x1a;\n" + + "\x0fworkspace_scope\x18\b \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\t \x01(\tR\trequestId\x1a;\n" + "\rMaterialEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\a\x10\bJ\x04\b\x06\x10\aR\tworkspaceR\rexpires_at_ms\"i\n" + " ConfigureProviderRefreshResponse\x12E\n" + - "\x06status\x18\x01 \x01(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\x06status\"\xc9\x01\n" + + "\x06status\x18\x01 \x01(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\x06status\"\xe8\x01\n" + "\x1fRotateProviderCredentialRequest\x12\x1a\n" + "\bprovider\x18\x01 \x01(\tR\bprovider\x12%\n" + "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12R\n" + - "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"i\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x05 \x01(\tR\trequestIdJ\x04\b\x03\x10\x04R\tworkspace\"i\n" + " RotateProviderCredentialResponse\x12E\n" + - "\x06status\x18\x01 \x01(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\x06status\"\xeb\x01\n" + + "\x06status\x18\x01 \x01(\v2-.openshell.v1.ProviderCredentialRefreshStatusR\x06status\"\x8a\x02\n" + "\x1cDeleteProviderRefreshRequest\x12\x1a\n" + "\bprovider\x18\x01 \x01(\tR\bprovider\x12%\n" + "\x0ecredential_key\x18\x02 \x01(\tR\rcredentialKey\x12R\n" + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12#\n" + - "\rallow_missing\x18\x05 \x01(\bR\fallowMissingJ\x04\b\x03\x10\x04R\tworkspace\"g\n" + + "\rallow_missing\x18\x05 \x01(\bR\fallowMissing\x12\x1d\n" + + "\n" + + "request_id\x18\x06 \x01(\tR\trequestIdJ\x04\b\x03\x10\x04R\tworkspace\"g\n" + "\x1dDeleteProviderRefreshResponse\x127\n" + "\aoutcome\x18\x02 \x01(\x0e2\x1d.openshell.v1.DeletionOutcomeR\aoutcomeJ\x04\b\x01\x10\x02R\adeleted\"\xd8\x05\n" + "\x0fProviderProfile\x12\x0e\n" + @@ -15464,19 +17317,23 @@ const file_openshell_proto_rawDesc = "" + "\aprofile\x18\x01 \x01(\v2\x1d.openshell.v1.ProviderProfileR\aprofile\"\x81\x01\n" + "\x1cListProviderProfilesResponse\x129\n" + "\bprofiles\x18\x01 \x03(\v2\x1d.openshell.v1.ProviderProfileR\bprofiles\x12&\n" + - "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x82\x01\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\xa1\x01\n" + "\x1dImportProviderProfilesRequest\x12C\n" + "\bprofiles\x18\x01 \x03(\v2'.openshell.v1.ProviderProfileImportItemR\bprofiles\x12\x1c\n" + - "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\xc2\x01\n" + + "\tworkspace\x18\x02 \x01(\tR\tworkspace\x12\x1d\n" + + "\n" + + "request_id\x18\x03 \x01(\tR\trequestId\"\xc2\x01\n" + "\x1eImportProviderProfilesResponse\x12I\n" + "\vdiagnostics\x18\x01 \x03(\v2'.openshell.v1.ProviderProfileDiagnosticR\vdiagnostics\x129\n" + "\bprofiles\x18\x02 \x03(\v2\x1d.openshell.v1.ProviderProfileR\bprofiles\x12\x1a\n" + - "\bimported\x18\x03 \x01(\bR\bimported\"\xcc\x01\n" + + "\bimported\x18\x03 \x01(\bR\bimported\"\xeb\x01\n" + "\x1dUpdateProviderProfilesRequest\x12A\n" + "\aprofile\x18\x01 \x01(\v2'.openshell.v1.ProviderProfileImportItemR\aprofile\x12:\n" + "\x19expected_resource_version\x18\x02 \x01(\x04R\x17expectedResourceVersion\x12\x0e\n" + "\x02id\x18\x03 \x01(\tR\x02id\x12\x1c\n" + - "\tworkspace\x18\x04 \x01(\tR\tworkspace\"\xbe\x01\n" + + "\tworkspace\x18\x04 \x01(\tR\tworkspace\x12\x1d\n" + + "\n" + + "request_id\x18\x05 \x01(\tR\trequestId\"\xbe\x01\n" + "\x1eUpdateProviderProfilesResponse\x12I\n" + "\vdiagnostics\x18\x01 \x03(\v2'.openshell.v1.ProviderProfileDiagnosticR\vdiagnostics\x127\n" + "\aprofile\x18\x02 \x01(\v2\x1d.openshell.v1.ProviderProfileR\aprofile\x12\x18\n" + @@ -15488,11 +17345,13 @@ const file_openshell_proto_rawDesc = "" + "\vdiagnostics\x18\x01 \x03(\v2'.openshell.v1.ProviderProfileDiagnosticR\vdiagnostics\x12\x14\n" + "\x05valid\x18\x02 \x01(\bR\x05valid\"`\n" + "\x16DeleteProviderResponse\x127\n" + - "\aoutcome\x18\x02 \x01(\x0e2\x1d.openshell.v1.DeletionOutcomeR\aoutcomeJ\x04\b\x01\x10\x02R\adeleted\"q\n" + + "\aoutcome\x18\x02 \x01(\x0e2\x1d.openshell.v1.DeletionOutcomeR\aoutcomeJ\x04\b\x01\x10\x02R\adeleted\"\x90\x01\n" + "\x1cDeleteProviderProfileRequest\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x1c\n" + "\tworkspace\x18\x02 \x01(\tR\tworkspace\x12#\n" + - "\rallow_missing\x18\x03 \x01(\bR\fallowMissing\"g\n" + + "\rallow_missing\x18\x03 \x01(\bR\fallowMissing\x12\x1d\n" + + "\n" + + "request_id\x18\x04 \x01(\tR\trequestId\"g\n" + "\x1dDeleteProviderProfileResponse\x127\n" + "\aoutcome\x18\x02 \x01(\x0e2\x1d.openshell.v1.DeletionOutcomeR\aoutcomeJ\x04\b\x01\x10\x02R\adeleted\"\x94\x01\n" + "$GetSandboxProviderEnvironmentRequest\x12\x1d\n" + @@ -15506,14 +17365,19 @@ const file_openshell_proto_rawDesc = "" + "\x17StaticCredentialBinding\x12K\n" + "\tendpoints\x18\x01 \x03(\v2-.openshell.v1.StaticCredentialEndpointBindingR\tendpoints\x12/\n" + "\x13credential_identity\x18\x02 \x01(\tR\x12credentialIdentity\x12<\n" + - "\x1aworkload_credential_handle\x18\x03 \x01(\tR\x18workloadCredentialHandle\"\xdb\b\n" + + "\x1aworkload_credential_handle\x18\x03 \x01(\tR\x18workloadCredentialHandle\"\x8a\n" + + "\n" + "%GetSandboxProviderEnvironmentResponse\x12l\n" + "\venvironment\x18\x01 \x03(\v2D.openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntryB\x04\x88\xb5\x18\x01R\venvironment\x122\n" + "\x15provider_env_revision\x18\x02 \x01(\x04R\x13providerEnvRevision\x12\x92\x01\n" + "\x1bcredential_expiration_times\x18g \x03(\v2R.openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpirationTimesEntryR\x19credentialExpirationTimes\x12|\n" + "\x13dynamic_credentials\x18\x04 \x03(\v2K.openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntryR\x12dynamicCredentials\x12\x8f\x01\n" + "\x1astatic_credential_bindings\x18\x05 \x03(\v2Q.openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntryR\x18staticCredentialBindings\x12=\n" + - "\x1bnon_secret_environment_keys\x18\x06 \x03(\tR\x18nonSecretEnvironmentKeys\x1a>\n" + + "\x1bnon_secret_environment_keys\x18\x06 \x03(\tR\x18nonSecretEnvironmentKeys\x12:\n" + + "\x19provider_attachment_epoch\x18\a \x01(\tR\x17providerAttachmentEpoch\x12\x1f\n" + + "\vpolicy_hash\x18\b \x01(\tR\n" + + "policyHash\x12P\n" + + "\x10readiness_reason\x18\t \x01(\x0e2%.openshell.v1.ProviderReadinessReasonR\x0freadinessReason\x1a>\n" + "\x10EnvironmentEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1ah\n" + @@ -15537,7 +17401,7 @@ const file_openshell_proto_rawDesc = "" + "\rexpires_after\x18f \x01(\v2\x19.google.protobuf.DurationR\fexpiresAfter\x12\x1d\n" + "\n" + "token_type\x18\x03 \x01(\tR\ttokenTypeJ\x04\b\x02\x10\x03R\n" + - "expires_in\"\x95\x05\n" + + "expires_in\"\xb4\x05\n" + "\x13UpdateConfigRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12;\n" + "\x06policy\x18\x02 \x01(\v2#.openshell.sandbox.v1.SandboxPolicyR\x06policy\x12\x1f\n" + @@ -15549,7 +17413,9 @@ const file_openshell_proto_rawDesc = "" + "\x10merge_operations\x18\a \x03(\v2\".openshell.v1.PolicyMergeOperationR\x0fmergeOperations\x12:\n" + "\x19expected_resource_version\x18\b \x01(\x04R\x17expectedResourceVersion\x12T\n" + "\vannotations\x18\t \x03(\v22.openshell.v1.UpdateConfigRequest.AnnotationsEntryR\vannotations\x12R\n" + - "\x0fworkspace_scope\x18\v \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x1a>\n" + + "\x0fworkspace_scope\x18\v \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\f \x01(\tR\trequestId\x1a>\n" + "\x10AnnotationsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01J\x04\b\n" + @@ -15670,12 +17536,13 @@ const file_openshell_proto_rawDesc = "" + "relay_open\x18\x04 \x01(\v2\x17.openshell.v1.RelayOpenH\x00R\trelayOpen\x12;\n" + "\vrelay_close\x18\x05 \x01(\v2\x18.openshell.v1.RelayCloseH\x00R\n" + "relayCloseB\t\n" + - "\apayload\"Q\n" + + "\apayload\"\x91\x01\n" + "\x0fSupervisorHello\x12\x1d\n" + "\n" + "sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" + "\vinstance_id\x18\x02 \x01(\tR\n" + - "instanceId\"\x99\x01\n" + + "instanceId\x12>\n" + + "\x1bsupports_provider_readiness\x18\x04 \x01(\bR\x19supportsProviderReadiness\"\x99\x01\n" + "\x0fSessionAccepted\x12\x1d\n" + "\n" + "session_id\x18\x01 \x01(\tR\tsessionId\x12H\n" + @@ -15819,53 +17686,65 @@ const file_openshell_proto_rawDesc = "" + "\x06chunks\x18\x01 \x03(\v2\x19.openshell.v1.PolicyChunkR\x06chunks\x12'\n" + "\x0frolling_summary\x18\x02 \x01(\tR\x0erollingSummary\x12#\n" + "\rdraft_version\x18\x03 \x01(\x04R\fdraftVersion\x12H\n" + - "\x12last_analyzed_time\x18h \x01(\v2\x1a.google.protobuf.TimestampR\x10lastAnalyzedTimeJ\x04\b\x04\x10\x05R\x13last_analyzed_at_ms\"\xd1\x01\n" + + "\x12last_analyzed_time\x18h \x01(\v2\x1a.google.protobuf.TimestampR\x10lastAnalyzedTimeJ\x04\b\x04\x10\x05R\x13last_analyzed_at_ms\"\xf0\x01\n" + "\x18ApproveDraftChunkRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" + "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12!\n" + "\freview_token\x18\x04 \x01(\tR\vreviewToken\x12R\n" + - "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"c\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x06 \x01(\tR\trequestIdJ\x04\b\x03\x10\x04R\tworkspace\"c\n" + "\x19ApproveDraftChunkResponse\x12%\n" + "\x0epolicy_version\x18\x01 \x01(\rR\rpolicyVersion\x12\x1f\n" + "\vpolicy_hash\x18\x02 \x01(\tR\n" + - "policyHash\"\xc5\x01\n" + + "policyHash\"\xe4\x01\n" + "\x17RejectDraftChunkRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" + "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12\x16\n" + "\x06reason\x18\x03 \x01(\tR\x06reason\x12R\n" + - "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x1a\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x06 \x01(\tR\trequestIdJ\x04\b\x04\x10\x05R\tworkspace\"\x1a\n" + "\x18RejectDraftChunkResponse\"R\n" + "\x12DraftChunkApproval\x12\x19\n" + "\bchunk_id\x18\x01 \x01(\tR\achunkId\x12!\n" + - "\freview_token\x18\x02 \x01(\tR\vreviewToken\"\x91\x02\n" + + "\freview_token\x18\x02 \x01(\tR\vreviewToken\"\xb0\x02\n" + "\x1cApproveAllDraftChunksRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x128\n" + "\x18include_security_flagged\x18\x02 \x01(\bR\x16includeSecurityFlagged\x12>\n" + "\tapprovals\x18\x04 \x03(\v2 .openshell.v1.DraftChunkApprovalR\tapprovals\x12R\n" + - "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"\xb7\x01\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x06 \x01(\tR\trequestIdJ\x04\b\x03\x10\x04R\tworkspace\"\xb7\x01\n" + "\x1dApproveAllDraftChunksResponse\x12%\n" + "\x0epolicy_version\x18\x01 \x01(\rR\rpolicyVersion\x12\x1f\n" + "\vpolicy_hash\x18\x02 \x01(\tR\n" + "policyHash\x12'\n" + "\x0fchunks_approved\x18\x03 \x01(\rR\x0echunksApproved\x12%\n" + - "\x0echunks_skipped\x18\x04 \x01(\rR\rchunksSkipped\"\xf9\x01\n" + + "\x0echunks_skipped\x18\x04 \x01(\rR\rchunksSkipped\"\x98\x02\n" + "\x15EditDraftChunkRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" + "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12L\n" + "\rproposed_rule\x18\x03 \x01(\v2'.openshell.sandbox.v1.NetworkPolicyRuleR\fproposedRule\x12R\n" + - "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x04\x10\x05R\tworkspace\"\x18\n" + - "\x16EditDraftChunkResponse\"\xab\x01\n" + + "\x0fworkspace_scope\x18\x05 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x06 \x01(\tR\trequestIdJ\x04\b\x04\x10\x05R\tworkspace\"\x18\n" + + "\x16EditDraftChunkResponse\"\xca\x01\n" + "\x15UndoDraftChunkRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x19\n" + "\bchunk_id\x18\x02 \x01(\tR\achunkId\x12R\n" + - "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x03\x10\x04R\tworkspace\"`\n" + + "\x0fworkspace_scope\x18\x04 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x05 \x01(\tR\trequestIdJ\x04\b\x03\x10\x04R\tworkspace\"`\n" + "\x16UndoDraftChunkResponse\x12%\n" + "\x0epolicy_version\x18\x01 \x01(\rR\rpolicyVersion\x12\x1f\n" + "\vpolicy_hash\x18\x02 \x01(\tR\n" + - "policyHash\"\x92\x01\n" + + "policyHash\"\xb1\x01\n" + "\x17ClearDraftChunksRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12R\n" + - "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScopeJ\x04\b\x02\x10\x03R\tworkspace\"A\n" + + "\x0fworkspace_scope\x18\x03 \x01(\v2).openshell.datamodel.v1.WorkspaceSelectorR\x0eworkspaceScope\x12\x1d\n" + + "\n" + + "request_id\x18\x04 \x01(\tR\trequestIdJ\x04\b\x02\x10\x03R\tworkspace\"A\n" + "\x18ClearDraftChunksResponse\x12%\n" + "\x0echunks_cleared\x18\x01 \x01(\rR\rchunksCleared\"\x91\x01\n" + "\x16GetDraftHistoryRequest\x12\x12\n" + @@ -15879,10 +17758,12 @@ const file_openshell_proto_rawDesc = "" + "\vdescription\x18\x03 \x01(\tR\vdescription\x12\x19\n" + "\bchunk_id\x18\x04 \x01(\tR\achunkIdJ\x04\b\x01\x10\x02R\ftimestamp_ms\"T\n" + "\x17GetDraftHistoryResponse\x129\n" + - "\aentries\x18\x01 \x03(\v2\x1f.openshell.v1.DraftHistoryEntryR\aentries\"\xb1\x01\n" + + "\aentries\x18\x01 \x03(\v2\x1f.openshell.v1.DraftHistoryEntryR\aentries\"\xd0\x01\n" + "\x16CreateWorkspaceRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12H\n" + - "\x06labels\x18\x02 \x03(\v20.openshell.v1.CreateWorkspaceRequest.LabelsEntryR\x06labels\x1a9\n" + + "\x06labels\x18\x02 \x03(\v20.openshell.v1.CreateWorkspaceRequest.LabelsEntryR\x06labels\x12\x1d\n" + + "\n" + + "request_id\x18\x03 \x01(\tR\trequestId\x1a9\n" + "\vLabelsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"Z\n" + @@ -15901,26 +17782,32 @@ const file_openshell_proto_rawDesc = "" + "\n" + "workspaces\x18\x01 \x03(\v2!.openshell.datamodel.v1.WorkspaceR\n" + "workspaces\x12&\n" + - "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"Q\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"p\n" + "\x16DeleteWorkspaceRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12#\n" + - "\rallow_missing\x18\x02 \x01(\bR\fallowMissing\"a\n" + + "\rallow_missing\x18\x02 \x01(\bR\fallowMissing\x12\x1d\n" + + "\n" + + "request_id\x18\x03 \x01(\tR\trequestId\"a\n" + "\x17DeleteWorkspaceResponse\x127\n" + "\aoutcome\x18\x02 \x01(\x0e2\x1d.openshell.v1.DeletionOutcomeR\aoutcomeJ\x04\b\x01\x10\x02R\adeleted\"\xaf\x01\n" + "\x0fWorkspaceMember\x12>\n" + "\bmetadata\x18\x01 \x01(\v2\".openshell.datamodel.v1.ObjectMetaR\bmetadata\x12+\n" + "\x11principal_subject\x18\x02 \x01(\tR\x10principalSubject\x12/\n" + - "\x04role\x18\x03 \x01(\x0e2\x1b.openshell.v1.WorkspaceRoleR\x04role\"\x97\x01\n" + + "\x04role\x18\x03 \x01(\x0e2\x1b.openshell.v1.WorkspaceRoleR\x04role\"\xb6\x01\n" + "\x19AddWorkspaceMemberRequest\x12\x1c\n" + "\tworkspace\x18\x01 \x01(\tR\tworkspace\x12+\n" + "\x11principal_subject\x18\x02 \x01(\tR\x10principalSubject\x12/\n" + - "\x04role\x18\x03 \x01(\x0e2\x1b.openshell.v1.WorkspaceRoleR\x04role\"S\n" + + "\x04role\x18\x03 \x01(\x0e2\x1b.openshell.v1.WorkspaceRoleR\x04role\x12\x1d\n" + + "\n" + + "request_id\x18\x04 \x01(\tR\trequestId\"S\n" + "\x1aAddWorkspaceMemberResponse\x125\n" + - "\x06member\x18\x01 \x01(\v2\x1d.openshell.v1.WorkspaceMemberR\x06member\"\x8e\x01\n" + + "\x06member\x18\x01 \x01(\v2\x1d.openshell.v1.WorkspaceMemberR\x06member\"\xad\x01\n" + "\x1cRemoveWorkspaceMemberRequest\x12\x1c\n" + "\tworkspace\x18\x01 \x01(\tR\tworkspace\x12+\n" + "\x11principal_subject\x18\x02 \x01(\tR\x10principalSubject\x12#\n" + - "\rallow_missing\x18\x03 \x01(\bR\fallowMissing\"g\n" + + "\rallow_missing\x18\x03 \x01(\bR\fallowMissing\x12\x1d\n" + + "\n" + + "request_id\x18\x04 \x01(\tR\trequestId\"g\n" + "\x1dRemoveWorkspaceMemberResponse\x127\n" + "\aoutcome\x18\x02 \x01(\x0e2\x1d.openshell.v1.DeletionOutcomeR\aoutcomeJ\x04\b\x01\x10\x02R\aremoved\"w\n" + "\x1bListWorkspaceMembersRequest\x12\x1c\n" + @@ -15969,7 +17856,62 @@ const file_openshell_proto_rawDesc = "" + "\x16SANDBOX_PHASE_STOPPING\x10\x06\x12\x19\n" + "\x15SANDBOX_PHASE_STOPPED\x10\a\x12\x1a\n" + "\x16SANDBOX_PHASE_STARTING\x10\b\x12\x1b\n" + - "\x17SANDBOX_PHASE_COMPLETED\x10\t*\xce\x01\n" + + "\x17SANDBOX_PHASE_COMPLETED\x10\t*\xcb\x01\n" + + "\x14ProviderMutationKind\x12&\n" + + "\"PROVIDER_MUTATION_KIND_UNSPECIFIED\x10\x00\x12!\n" + + "\x1dPROVIDER_MUTATION_KIND_ATTACH\x10\x01\x12!\n" + + "\x1dPROVIDER_MUTATION_KIND_DETACH\x10\x02\x12!\n" + + "\x1dPROVIDER_MUTATION_KIND_UPDATE\x10\x03\x12\"\n" + + "\x1ePROVIDER_MUTATION_KIND_OBSERVE\x10\x04*\xcf\x02\n" + + "\x16ProviderReadinessState\x12(\n" + + "$PROVIDER_READINESS_STATE_UNSPECIFIED\x10\x00\x12&\n" + + "\"PROVIDER_READINESS_STATE_PERSISTED\x10\x01\x12$\n" + + " PROVIDER_READINESS_STATE_PENDING\x10\x02\x12\"\n" + + "\x1ePROVIDER_READINESS_STATE_READY\x10\x03\x12%\n" + + "!PROVIDER_READINESS_STATE_WITHHELD\x10\x04\x12$\n" + + " PROVIDER_READINESS_STATE_REVOKED\x10\x05\x12#\n" + + "\x1fPROVIDER_READINESS_STATE_FAILED\x10\x06\x12'\n" + + "#PROVIDER_READINESS_STATE_SUPERSEDED\x10\a*\xda\x06\n" + + "\x17ProviderReadinessReason\x12)\n" + + "%PROVIDER_READINESS_REASON_UNSPECIFIED\x10\x00\x124\n" + + "0PROVIDER_READINESS_REASON_WAITING_FOR_SUPERVISOR\x10\x01\x125\n" + + "1PROVIDER_READINESS_REASON_WAITING_FOR_CREDENTIALS\x10\x02\x120\n" + + ",PROVIDER_READINESS_REASON_WAITING_FOR_POLICY\x10\x03\x121\n" + + "-PROVIDER_READINESS_REASON_WAITING_FOR_PROCESS\x10\x04\x124\n" + + "0PROVIDER_READINESS_REASON_UNSUPPORTED_SUPERVISOR\x10\x05\x122\n" + + ".PROVIDER_READINESS_REASON_CREDENTIALS_WITHHELD\x10\x06\x127\n" + + "3PROVIDER_READINESS_REASON_CREDENTIAL_INSTALL_FAILED\x10\a\x126\n" + + "2PROVIDER_READINESS_REASON_POLICY_ACTIVATION_FAILED\x10\b\x124\n" + + "0PROVIDER_READINESS_REASON_PROCESS_INSTALL_FAILED\x10\t\x125\n" + + "1PROVIDER_READINESS_REASON_SUPERVISOR_DISCONNECTED\x10\n" + + "\x126\n" + + "2PROVIDER_READINESS_REASON_SUPERVISOR_LEASE_EXPIRED\x10\v\x123\n" + + "/PROVIDER_READINESS_REASON_DESIRED_STATE_CHANGED\x10\f\x120\n" + + ",PROVIDER_READINESS_REASON_CREDENTIAL_EXPIRED\x10\r\x12*\n" + + "&PROVIDER_READINESS_REASON_LOCAL_POLICY\x10\x0e\x12/\n" + + "+PROVIDER_READINESS_REASON_SNAPSHOT_MISMATCH\x10\x0f*\x83\x01\n" + + "\x0fConfigComponent\x12 \n" + + "\x1cCONFIG_COMPONENT_UNSPECIFIED\x10\x00\x12#\n" + + "\x1fCONFIG_COMPONENT_SANDBOX_CONFIG\x10\x01\x12)\n" + + "%CONFIG_COMPONENT_PROVIDER_ENVIRONMENT\x10\x02*\x8d\x03\n" + + "\x12ConfigApplyOutcome\x12$\n" + + " CONFIG_APPLY_OUTCOME_UNSPECIFIED\x10\x00\x12 \n" + + "\x1cCONFIG_APPLY_OUTCOME_APPLIED\x10\x01\x12*\n" + + "&CONFIG_APPLY_OUTCOME_IGNORED_DUPLICATE\x10\x02\x12&\n" + + "\"CONFIG_APPLY_OUTCOME_IGNORED_STALE\x10\x03\x120\n" + + ",CONFIG_APPLY_OUTCOME_RETAINED_LOCAL_OVERRIDE\x10\x04\x12!\n" + + "\x1dCONFIG_APPLY_OUTCOME_DEGRADED\x10\x05\x128\n" + + "4CONFIG_APPLY_OUTCOME_FAILED_RETAINED_LAST_KNOWN_GOOD\x10\x06\x12&\n" + + "\"CONFIG_APPLY_OUTCOME_FAILED_CLOSED\x10\a\x12$\n" + + " CONFIG_APPLY_OUTCOME_UNSUPPORTED\x10\b*\xd2\x02\n" + + "\x1aConfigUpdateOperationState\x12-\n" + + ")CONFIG_UPDATE_OPERATION_STATE_UNSPECIFIED\x10\x00\x12)\n" + + "%CONFIG_UPDATE_OPERATION_STATE_PENDING\x10\x01\x12)\n" + + "%CONFIG_UPDATE_OPERATION_STATE_APPLIED\x10\x02\x12*\n" + + "&CONFIG_UPDATE_OPERATION_STATE_INACTIVE\x10\x03\x12(\n" + + "$CONFIG_UPDATE_OPERATION_STATE_FAILED\x10\x04\x12,\n" + + "(CONFIG_UPDATE_OPERATION_STATE_SUPERSEDED\x10\x05\x12+\n" + + "'CONFIG_UPDATE_OPERATION_STATE_CANCELLED\x10\x06*\xce\x01\n" + " ProviderCredentialTokenGrantType\x124\n" + "0PROVIDER_CREDENTIAL_TOKEN_GRANT_TYPE_UNSPECIFIED\x10\x00\x12;\n" + "7PROVIDER_CREDENTIAL_TOKEN_GRANT_TYPE_CLIENT_CREDENTIALS\x10\x01\x127\n" + @@ -16025,7 +17967,7 @@ const file_openshell_proto_rawDesc = "" + "&ENDPOINT_RESULT_CREDENTIAL_UNAVAILABLE\x10\x04\x12\x1e\n" + "\x1aENDPOINT_RESULT_TLS_FAILED\x10\x05\x12$\n" + " ENDPOINT_RESULT_TRANSPORT_FAILED\x10\x06\x12%\n" + - "!ENDPOINT_RESULT_UPSTREAM_REJECTED\x10\a2\x8bN\n" + + "!ENDPOINT_RESULT_UPSTREAM_REJECTED\x10\a2\xb1P\n" + "\tOpenShell\x12Z\n" + "\x06Health\x12\x1b.openshell.v1.HealthRequest\x1a\x1c.openshell.v1.HealthResponse\"\x15\x82\xb5\x18\x11\n" + "\x0funauthenticated\x12i\n" + @@ -16055,7 +17997,9 @@ const file_openshell_proto_rawDesc = "" + "\x15AttachSandboxProvider\x12*.openshell.v1.AttachSandboxProviderRequest\x1a+.openshell.v1.AttachSandboxProviderResponse\"!\x82\xb5\x18\x1d\n" + "\x06bearer\x12\x04user\"\rsandbox:write\x12\x93\x01\n" + "\x15DetachSandboxProvider\x12*.openshell.v1.DetachSandboxProviderRequest\x1a+.openshell.v1.DetachSandboxProviderResponse\"!\x82\xb5\x18\x1d\n" + - "\x06bearer\x12\x04user\"\rsandbox:write\x12{\n" + + "\x06bearer\x12\x04user\"\rsandbox:write\x12\x9b\x01\n" + + "\x18GetSandboxProviderStatus\x12-.openshell.v1.GetSandboxProviderStatusRequest\x1a..openshell.v1.GetSandboxProviderStatusResponse\" \x82\xb5\x18\x1c\n" + + "\x06bearer\x12\x04user\"\fsandbox:read\x12{\n" + "\rDeleteSandbox\x12\".openshell.v1.DeleteSandboxRequest\x1a#.openshell.v1.DeleteSandboxResponse\"!\x82\xb5\x18\x1d\n" + "\x06bearer\x12\x04user\"\rsandbox:write\x12q\n" + "\vStopSandbox\x12 .openshell.v1.StopSandboxRequest\x1a\x1d.openshell.v1.SandboxResponse\"!\x82\xb5\x18\x1d\n" + @@ -16125,6 +18069,8 @@ const file_openshell_proto_rawDesc = "" + "\x12ReportPolicyStatus\x12'.openshell.v1.ReportPolicyStatusRequest\x1a(.openshell.v1.ReportPolicyStatusResponse\"\r\x82\xb5\x18\t\n" + "\asandbox\x12|\n" + "\x14ReportEndpointStatus\x12).openshell.v1.ReportEndpointStatusRequest\x1a*.openshell.v1.ReportEndpointStatusResponse\"\r\x82\xb5\x18\t\n" + + "\asandbox\x12\x85\x01\n" + + "\x17ReportProviderReadiness\x12,.openshell.v1.ReportProviderReadinessRequest\x1a-.openshell.v1.ReportProviderReadinessResponse\"\r\x82\xb5\x18\t\n" + "\asandbox\x12\x97\x01\n" + "\x1dGetSandboxProviderEnvironment\x122.openshell.v1.GetSandboxProviderEnvironmentRequest\x1a3.openshell.v1.GetSandboxProviderEnvironmentResponse\"\r\x82\xb5\x18\t\n" + "\asandbox\x12\x94\x01\n" + @@ -16193,679 +18139,731 @@ func file_openshell_proto_rawDescGZIP() []byte { return file_openshell_proto_rawDescData } -var file_openshell_proto_enumTypes = make([]protoimpl.EnumInfo, 10) -var file_openshell_proto_msgTypes = make([]protoimpl.MessageInfo, 232) +var file_openshell_proto_enumTypes = make([]protoimpl.EnumInfo, 16) +var file_openshell_proto_msgTypes = make([]protoimpl.MessageInfo, 243) var file_openshell_proto_goTypes = []any{ (SandboxPhase)(0), // 0: openshell.v1.SandboxPhase - (ProviderCredentialTokenGrantType)(0), // 1: openshell.v1.ProviderCredentialTokenGrantType - (ProviderCredentialRefreshStrategy)(0), // 2: openshell.v1.ProviderCredentialRefreshStrategy - (ProviderProfileCategory)(0), // 3: openshell.v1.ProviderProfileCategory - (PolicyStatus)(0), // 4: openshell.v1.PolicyStatus - (ServiceStatus)(0), // 5: openshell.v1.ServiceStatus - (WorkspaceRole)(0), // 6: openshell.v1.WorkspaceRole - (ProviderCredentialRefreshRecoveryAction)(0), // 7: openshell.v1.ProviderCredentialRefreshRecoveryAction - (DeletionOutcome)(0), // 8: openshell.v1.DeletionOutcome - (EndpointResult)(0), // 9: openshell.v1.EndpointResult - (*IssueSandboxTokenRequest)(nil), // 10: openshell.v1.IssueSandboxTokenRequest - (*IssueSandboxTokenResponse)(nil), // 11: openshell.v1.IssueSandboxTokenResponse - (*RefreshSandboxTokenRequest)(nil), // 12: openshell.v1.RefreshSandboxTokenRequest - (*RefreshSandboxTokenResponse)(nil), // 13: openshell.v1.RefreshSandboxTokenResponse - (*HealthRequest)(nil), // 14: openshell.v1.HealthRequest - (*HealthResponse)(nil), // 15: openshell.v1.HealthResponse - (*GetCurrentUserRequest)(nil), // 16: openshell.v1.GetCurrentUserRequest - (*GetCurrentUserResponse)(nil), // 17: openshell.v1.GetCurrentUserResponse - (*GetGatewayInfoRequest)(nil), // 18: openshell.v1.GetGatewayInfoRequest - (*GetGatewayInfoResponse)(nil), // 19: openshell.v1.GetGatewayInfoResponse - (*ComputeDriverInfo)(nil), // 20: openshell.v1.ComputeDriverInfo - (*ComputeDriverCapabilities)(nil), // 21: openshell.v1.ComputeDriverCapabilities - (*ResourceCapabilities)(nil), // 22: openshell.v1.ResourceCapabilities - (*CpuResourceCapabilities)(nil), // 23: openshell.v1.CpuResourceCapabilities - (*MemoryResourceCapabilities)(nil), // 24: openshell.v1.MemoryResourceCapabilities - (*GpuResourceCapabilities)(nil), // 25: openshell.v1.GpuResourceCapabilities - (*Sandbox)(nil), // 26: openshell.v1.Sandbox - (*SandboxSpec)(nil), // 27: openshell.v1.SandboxSpec - (*ResourceRequirements)(nil), // 28: openshell.v1.ResourceRequirements - (*GpuResourceRequirements)(nil), // 29: openshell.v1.GpuResourceRequirements - (*SandboxTemplate)(nil), // 30: openshell.v1.SandboxTemplate - (*SandboxWorkloadTemplate)(nil), // 31: openshell.v1.SandboxWorkloadTemplate - (*SandboxWorkloadTemplateSpec)(nil), // 32: openshell.v1.SandboxWorkloadTemplateSpec - (*SandboxWorkloadConfig)(nil), // 33: openshell.v1.SandboxWorkloadConfig - (*SandboxResources)(nil), // 34: openshell.v1.SandboxResources - (*SandboxServiceLevel)(nil), // 35: openshell.v1.SandboxServiceLevel - (*SandboxStartup)(nil), // 36: openshell.v1.SandboxStartup - (*SandboxWorkloadTemplateProvenance)(nil), // 37: openshell.v1.SandboxWorkloadTemplateProvenance - (*SandboxStatus)(nil), // 38: openshell.v1.SandboxStatus - (*SandboxCondition)(nil), // 39: openshell.v1.SandboxCondition - (*PlatformEvent)(nil), // 40: openshell.v1.PlatformEvent - (*CreateSandboxRequest)(nil), // 41: openshell.v1.CreateSandboxRequest - (*CreateSandboxTemplateRequest)(nil), // 42: openshell.v1.CreateSandboxTemplateRequest - (*GetSandboxTemplateRequest)(nil), // 43: openshell.v1.GetSandboxTemplateRequest - (*ListSandboxTemplatesRequest)(nil), // 44: openshell.v1.ListSandboxTemplatesRequest - (*DeleteSandboxTemplateRequest)(nil), // 45: openshell.v1.DeleteSandboxTemplateRequest - (*SandboxTemplateResponse)(nil), // 46: openshell.v1.SandboxTemplateResponse - (*ListSandboxTemplatesResponse)(nil), // 47: openshell.v1.ListSandboxTemplatesResponse - (*DeleteSandboxTemplateResponse)(nil), // 48: openshell.v1.DeleteSandboxTemplateResponse - (*BeginRootfsTarStagingRequest)(nil), // 49: openshell.v1.BeginRootfsTarStagingRequest - (*BeginRootfsTarStagingResponse)(nil), // 50: openshell.v1.BeginRootfsTarStagingResponse - (*GetSandboxRequest)(nil), // 51: openshell.v1.GetSandboxRequest - (*ListSandboxesRequest)(nil), // 52: openshell.v1.ListSandboxesRequest - (*ListSandboxProvidersRequest)(nil), // 53: openshell.v1.ListSandboxProvidersRequest - (*AttachSandboxProviderRequest)(nil), // 54: openshell.v1.AttachSandboxProviderRequest - (*DetachSandboxProviderRequest)(nil), // 55: openshell.v1.DetachSandboxProviderRequest - (*DeleteSandboxRequest)(nil), // 56: openshell.v1.DeleteSandboxRequest - (*StopSandboxRequest)(nil), // 57: openshell.v1.StopSandboxRequest - (*StartSandboxRequest)(nil), // 58: openshell.v1.StartSandboxRequest - (*SandboxResponse)(nil), // 59: openshell.v1.SandboxResponse - (*ListSandboxesResponse)(nil), // 60: openshell.v1.ListSandboxesResponse - (*ListSandboxProvidersResponse)(nil), // 61: openshell.v1.ListSandboxProvidersResponse - (*AttachSandboxProviderResponse)(nil), // 62: openshell.v1.AttachSandboxProviderResponse - (*DetachSandboxProviderResponse)(nil), // 63: openshell.v1.DetachSandboxProviderResponse - (*DeleteSandboxResponse)(nil), // 64: openshell.v1.DeleteSandboxResponse - (*CreateSshSessionRequest)(nil), // 65: openshell.v1.CreateSshSessionRequest - (*CreateSshSessionResponse)(nil), // 66: openshell.v1.CreateSshSessionResponse - (*ExposeServiceRequest)(nil), // 67: openshell.v1.ExposeServiceRequest - (*GetServiceRequest)(nil), // 68: openshell.v1.GetServiceRequest - (*ListServicesRequest)(nil), // 69: openshell.v1.ListServicesRequest - (*ListServicesResponse)(nil), // 70: openshell.v1.ListServicesResponse - (*DeleteServiceRequest)(nil), // 71: openshell.v1.DeleteServiceRequest - (*DeleteServiceResponse)(nil), // 72: openshell.v1.DeleteServiceResponse - (*ServiceEndpoint)(nil), // 73: openshell.v1.ServiceEndpoint - (*ServiceEndpointResponse)(nil), // 74: openshell.v1.ServiceEndpointResponse - (*RevokeSshSessionRequest)(nil), // 75: openshell.v1.RevokeSshSessionRequest - (*RevokeSshSessionResponse)(nil), // 76: openshell.v1.RevokeSshSessionResponse - (*ExecSandboxRequest)(nil), // 77: openshell.v1.ExecSandboxRequest - (*ExecSandboxStdout)(nil), // 78: openshell.v1.ExecSandboxStdout - (*ExecSandboxStderr)(nil), // 79: openshell.v1.ExecSandboxStderr - (*ExecSandboxExit)(nil), // 80: openshell.v1.ExecSandboxExit - (*ExecSandboxEvent)(nil), // 81: openshell.v1.ExecSandboxEvent - (*TcpForwardInit)(nil), // 82: openshell.v1.TcpForwardInit - (*TcpForwardFrame)(nil), // 83: openshell.v1.TcpForwardFrame - (*ExecSandboxInput)(nil), // 84: openshell.v1.ExecSandboxInput - (*ExecSandboxWindowResize)(nil), // 85: openshell.v1.ExecSandboxWindowResize - (*SshSession)(nil), // 86: openshell.v1.SshSession - (*WatchSandboxRequest)(nil), // 87: openshell.v1.WatchSandboxRequest - (*SandboxStreamEvent)(nil), // 88: openshell.v1.SandboxStreamEvent - (*SandboxLogLine)(nil), // 89: openshell.v1.SandboxLogLine - (*SandboxStreamWarning)(nil), // 90: openshell.v1.SandboxStreamWarning - (*CreateProviderRequest)(nil), // 91: openshell.v1.CreateProviderRequest - (*GetProviderRequest)(nil), // 92: openshell.v1.GetProviderRequest - (*ListProvidersRequest)(nil), // 93: openshell.v1.ListProvidersRequest - (*UpdateProviderRequest)(nil), // 94: openshell.v1.UpdateProviderRequest - (*DeleteProviderRequest)(nil), // 95: openshell.v1.DeleteProviderRequest - (*ProviderResponse)(nil), // 96: openshell.v1.ProviderResponse - (*ListProvidersResponse)(nil), // 97: openshell.v1.ListProvidersResponse - (*ListProviderProfilesRequest)(nil), // 98: openshell.v1.ListProviderProfilesRequest - (*GetProviderProfileRequest)(nil), // 99: openshell.v1.GetProviderProfileRequest - (*ProviderProfileImportItem)(nil), // 100: openshell.v1.ProviderProfileImportItem - (*ProviderProfileDiagnostic)(nil), // 101: openshell.v1.ProviderProfileDiagnostic - (*ProviderCredentialTokenGrantAudienceOverride)(nil), // 102: openshell.v1.ProviderCredentialTokenGrantAudienceOverride - (*ProviderCredentialTokenGrantSubjectToken)(nil), // 103: openshell.v1.ProviderCredentialTokenGrantSubjectToken - (*ProviderCredentialTokenGrant)(nil), // 104: openshell.v1.ProviderCredentialTokenGrant - (*ProviderProfileCredential)(nil), // 105: openshell.v1.ProviderProfileCredential - (*ProviderCredentialRefreshMaterial)(nil), // 106: openshell.v1.ProviderCredentialRefreshMaterial - (*ProviderCredentialRefreshOutput)(nil), // 107: openshell.v1.ProviderCredentialRefreshOutput - (*ProviderCredentialRefresh)(nil), // 108: openshell.v1.ProviderCredentialRefresh - (*ProviderCredentialRefreshStatus)(nil), // 109: openshell.v1.ProviderCredentialRefreshStatus - (*ProviderProfileDiscovery)(nil), // 110: openshell.v1.ProviderProfileDiscovery - (*GetProviderRefreshStatusRequest)(nil), // 111: openshell.v1.GetProviderRefreshStatusRequest - (*GetProviderRefreshStatusResponse)(nil), // 112: openshell.v1.GetProviderRefreshStatusResponse - (*ConfigureProviderRefreshRequest)(nil), // 113: openshell.v1.ConfigureProviderRefreshRequest - (*ConfigureProviderRefreshResponse)(nil), // 114: openshell.v1.ConfigureProviderRefreshResponse - (*RotateProviderCredentialRequest)(nil), // 115: openshell.v1.RotateProviderCredentialRequest - (*RotateProviderCredentialResponse)(nil), // 116: openshell.v1.RotateProviderCredentialResponse - (*DeleteProviderRefreshRequest)(nil), // 117: openshell.v1.DeleteProviderRefreshRequest - (*DeleteProviderRefreshResponse)(nil), // 118: openshell.v1.DeleteProviderRefreshResponse - (*ProviderProfile)(nil), // 119: openshell.v1.ProviderProfile - (*ProviderProfileResponse)(nil), // 120: openshell.v1.ProviderProfileResponse - (*ListProviderProfilesResponse)(nil), // 121: openshell.v1.ListProviderProfilesResponse - (*ImportProviderProfilesRequest)(nil), // 122: openshell.v1.ImportProviderProfilesRequest - (*ImportProviderProfilesResponse)(nil), // 123: openshell.v1.ImportProviderProfilesResponse - (*UpdateProviderProfilesRequest)(nil), // 124: openshell.v1.UpdateProviderProfilesRequest - (*UpdateProviderProfilesResponse)(nil), // 125: openshell.v1.UpdateProviderProfilesResponse - (*LintProviderProfilesRequest)(nil), // 126: openshell.v1.LintProviderProfilesRequest - (*LintProviderProfilesResponse)(nil), // 127: openshell.v1.LintProviderProfilesResponse - (*DeleteProviderResponse)(nil), // 128: openshell.v1.DeleteProviderResponse - (*DeleteProviderProfileRequest)(nil), // 129: openshell.v1.DeleteProviderProfileRequest - (*DeleteProviderProfileResponse)(nil), // 130: openshell.v1.DeleteProviderProfileResponse - (*GetSandboxProviderEnvironmentRequest)(nil), // 131: openshell.v1.GetSandboxProviderEnvironmentRequest - (*StaticCredentialEndpointBinding)(nil), // 132: openshell.v1.StaticCredentialEndpointBinding - (*StaticCredentialBinding)(nil), // 133: openshell.v1.StaticCredentialBinding - (*GetSandboxProviderEnvironmentResponse)(nil), // 134: openshell.v1.GetSandboxProviderEnvironmentResponse - (*ExchangeProviderSubjectTokenRequest)(nil), // 135: openshell.v1.ExchangeProviderSubjectTokenRequest - (*ExchangeProviderSubjectTokenResponse)(nil), // 136: openshell.v1.ExchangeProviderSubjectTokenResponse - (*UpdateConfigRequest)(nil), // 137: openshell.v1.UpdateConfigRequest - (*PolicyMergeOperation)(nil), // 138: openshell.v1.PolicyMergeOperation - (*AddNetworkRule)(nil), // 139: openshell.v1.AddNetworkRule - (*RemoveNetworkEndpoint)(nil), // 140: openshell.v1.RemoveNetworkEndpoint - (*RemoveNetworkRule)(nil), // 141: openshell.v1.RemoveNetworkRule - (*AddDenyRules)(nil), // 142: openshell.v1.AddDenyRules - (*AddAllowRules)(nil), // 143: openshell.v1.AddAllowRules - (*RemoveNetworkBinary)(nil), // 144: openshell.v1.RemoveNetworkBinary - (*UpdateConfigResponse)(nil), // 145: openshell.v1.UpdateConfigResponse - (*GetSandboxPolicyStatusRequest)(nil), // 146: openshell.v1.GetSandboxPolicyStatusRequest - (*GetSandboxPolicyStatusResponse)(nil), // 147: openshell.v1.GetSandboxPolicyStatusResponse - (*ListSandboxPoliciesRequest)(nil), // 148: openshell.v1.ListSandboxPoliciesRequest - (*ListSandboxPoliciesResponse)(nil), // 149: openshell.v1.ListSandboxPoliciesResponse - (*ReportPolicyStatusRequest)(nil), // 150: openshell.v1.ReportPolicyStatusRequest - (*ReportPolicyStatusResponse)(nil), // 151: openshell.v1.ReportPolicyStatusResponse - (*SandboxPolicyRevision)(nil), // 152: openshell.v1.SandboxPolicyRevision - (*GetSandboxLogsRequest)(nil), // 153: openshell.v1.GetSandboxLogsRequest - (*PushSandboxLogsRequest)(nil), // 154: openshell.v1.PushSandboxLogsRequest - (*PushSandboxLogsResponse)(nil), // 155: openshell.v1.PushSandboxLogsResponse - (*GetSandboxLogsResponse)(nil), // 156: openshell.v1.GetSandboxLogsResponse - (*SupervisorMessage)(nil), // 157: openshell.v1.SupervisorMessage - (*GatewayMessage)(nil), // 158: openshell.v1.GatewayMessage - (*SupervisorHello)(nil), // 159: openshell.v1.SupervisorHello - (*SessionAccepted)(nil), // 160: openshell.v1.SessionAccepted - (*SessionRejected)(nil), // 161: openshell.v1.SessionRejected - (*SupervisorHeartbeat)(nil), // 162: openshell.v1.SupervisorHeartbeat - (*GatewayHeartbeat)(nil), // 163: openshell.v1.GatewayHeartbeat - (*ReportMainProcessExitRequest)(nil), // 164: openshell.v1.ReportMainProcessExitRequest - (*ReportMainProcessExitResponse)(nil), // 165: openshell.v1.ReportMainProcessExitResponse - (*FinalizeMainProcessExitRequest)(nil), // 166: openshell.v1.FinalizeMainProcessExitRequest - (*FinalizeMainProcessExitResponse)(nil), // 167: openshell.v1.FinalizeMainProcessExitResponse - (*RelayOpen)(nil), // 168: openshell.v1.RelayOpen - (*SshRelayTarget)(nil), // 169: openshell.v1.SshRelayTarget - (*TcpRelayTarget)(nil), // 170: openshell.v1.TcpRelayTarget - (*RelayInit)(nil), // 171: openshell.v1.RelayInit - (*RelayFrame)(nil), // 172: openshell.v1.RelayFrame - (*RelayOpenResult)(nil), // 173: openshell.v1.RelayOpenResult - (*RelayClose)(nil), // 174: openshell.v1.RelayClose - (*L7RequestSample)(nil), // 175: openshell.v1.L7RequestSample - (*DenialSummary)(nil), // 176: openshell.v1.DenialSummary - (*DenialGroupCount)(nil), // 177: openshell.v1.DenialGroupCount - (*NetworkActivitySummary)(nil), // 178: openshell.v1.NetworkActivitySummary - (*PolicyChunk)(nil), // 179: openshell.v1.PolicyChunk - (*DraftPolicyUpdate)(nil), // 180: openshell.v1.DraftPolicyUpdate - (*SubmitPolicyAnalysisRequest)(nil), // 181: openshell.v1.SubmitPolicyAnalysisRequest - (*SubmitPolicyAnalysisResponse)(nil), // 182: openshell.v1.SubmitPolicyAnalysisResponse - (*GetDraftPolicyRequest)(nil), // 183: openshell.v1.GetDraftPolicyRequest - (*GetDraftPolicyResponse)(nil), // 184: openshell.v1.GetDraftPolicyResponse - (*ApproveDraftChunkRequest)(nil), // 185: openshell.v1.ApproveDraftChunkRequest - (*ApproveDraftChunkResponse)(nil), // 186: openshell.v1.ApproveDraftChunkResponse - (*RejectDraftChunkRequest)(nil), // 187: openshell.v1.RejectDraftChunkRequest - (*RejectDraftChunkResponse)(nil), // 188: openshell.v1.RejectDraftChunkResponse - (*DraftChunkApproval)(nil), // 189: openshell.v1.DraftChunkApproval - (*ApproveAllDraftChunksRequest)(nil), // 190: openshell.v1.ApproveAllDraftChunksRequest - (*ApproveAllDraftChunksResponse)(nil), // 191: openshell.v1.ApproveAllDraftChunksResponse - (*EditDraftChunkRequest)(nil), // 192: openshell.v1.EditDraftChunkRequest - (*EditDraftChunkResponse)(nil), // 193: openshell.v1.EditDraftChunkResponse - (*UndoDraftChunkRequest)(nil), // 194: openshell.v1.UndoDraftChunkRequest - (*UndoDraftChunkResponse)(nil), // 195: openshell.v1.UndoDraftChunkResponse - (*ClearDraftChunksRequest)(nil), // 196: openshell.v1.ClearDraftChunksRequest - (*ClearDraftChunksResponse)(nil), // 197: openshell.v1.ClearDraftChunksResponse - (*GetDraftHistoryRequest)(nil), // 198: openshell.v1.GetDraftHistoryRequest - (*DraftHistoryEntry)(nil), // 199: openshell.v1.DraftHistoryEntry - (*GetDraftHistoryResponse)(nil), // 200: openshell.v1.GetDraftHistoryResponse - (*CreateWorkspaceRequest)(nil), // 201: openshell.v1.CreateWorkspaceRequest - (*CreateWorkspaceResponse)(nil), // 202: openshell.v1.CreateWorkspaceResponse - (*GetWorkspaceRequest)(nil), // 203: openshell.v1.GetWorkspaceRequest - (*GetWorkspaceResponse)(nil), // 204: openshell.v1.GetWorkspaceResponse - (*ListWorkspacesRequest)(nil), // 205: openshell.v1.ListWorkspacesRequest - (*ListWorkspacesResponse)(nil), // 206: openshell.v1.ListWorkspacesResponse - (*DeleteWorkspaceRequest)(nil), // 207: openshell.v1.DeleteWorkspaceRequest - (*DeleteWorkspaceResponse)(nil), // 208: openshell.v1.DeleteWorkspaceResponse - (*WorkspaceMember)(nil), // 209: openshell.v1.WorkspaceMember - (*AddWorkspaceMemberRequest)(nil), // 210: openshell.v1.AddWorkspaceMemberRequest - (*AddWorkspaceMemberResponse)(nil), // 211: openshell.v1.AddWorkspaceMemberResponse - (*RemoveWorkspaceMemberRequest)(nil), // 212: openshell.v1.RemoveWorkspaceMemberRequest - (*RemoveWorkspaceMemberResponse)(nil), // 213: openshell.v1.RemoveWorkspaceMemberResponse - (*ListWorkspaceMembersRequest)(nil), // 214: openshell.v1.ListWorkspaceMembersRequest - (*ListWorkspaceMembersResponse)(nil), // 215: openshell.v1.ListWorkspaceMembersResponse - (*ExtensionServiceCredential)(nil), // 216: openshell.v1.ExtensionServiceCredential - (*EndpointObservation)(nil), // 217: openshell.v1.EndpointObservation - (*ReportEndpointStatusRequest)(nil), // 218: openshell.v1.ReportEndpointStatusRequest - (*ReportEndpointStatusResponse)(nil), // 219: openshell.v1.ReportEndpointStatusResponse - (*EndpointStatus)(nil), // 220: openshell.v1.EndpointStatus - nil, // 221: openshell.v1.SandboxSpec.EnvironmentEntry - nil, // 222: openshell.v1.SandboxTemplate.LabelsEntry - nil, // 223: openshell.v1.SandboxTemplate.AnnotationsEntry - nil, // 224: openshell.v1.SandboxTemplate.EnvironmentEntry - nil, // 225: openshell.v1.SandboxWorkloadConfig.EnvironmentEntry - nil, // 226: openshell.v1.PlatformEvent.MetadataEntry - nil, // 227: openshell.v1.CreateSandboxRequest.LabelsEntry - nil, // 228: openshell.v1.CreateSandboxRequest.AnnotationsEntry - nil, // 229: openshell.v1.ExecSandboxRequest.EnvironmentEntry - nil, // 230: openshell.v1.SandboxLogLine.FieldsEntry - nil, // 231: openshell.v1.UpdateProviderRequest.CredentialExpirationTimesEntry - nil, // 232: openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - nil, // 233: openshell.v1.ProviderProfile.AnnotationsEntry - nil, // 234: openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - nil, // 235: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpirationTimesEntry - nil, // 236: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - nil, // 237: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - nil, // 238: openshell.v1.UpdateConfigRequest.AnnotationsEntry - nil, // 239: openshell.v1.UpdateConfigResponse.AnnotationsEntry - nil, // 240: openshell.v1.SandboxPolicyRevision.ProvenanceEntry - nil, // 241: openshell.v1.CreateWorkspaceRequest.LabelsEntry - (*timestamppb.Timestamp)(nil), // 242: google.protobuf.Timestamp - (*datamodelv1.ObjectMeta)(nil), // 243: openshell.datamodel.v1.ObjectMeta - (*sandboxv1.SandboxPolicy)(nil), // 244: openshell.sandbox.v1.SandboxPolicy - (*structpb.Struct)(nil), // 245: google.protobuf.Struct - (*durationpb.Duration)(nil), // 246: google.protobuf.Duration - (*datamodelv1.WorkspaceSelector)(nil), // 247: openshell.datamodel.v1.WorkspaceSelector - (*datamodelv1.Provider)(nil), // 248: openshell.datamodel.v1.Provider - (*sandboxv1.NetworkEndpoint)(nil), // 249: openshell.sandbox.v1.NetworkEndpoint - (*sandboxv1.NetworkBinary)(nil), // 250: openshell.sandbox.v1.NetworkBinary - (*sandboxv1.SettingValue)(nil), // 251: openshell.sandbox.v1.SettingValue - (*sandboxv1.NetworkPolicyRule)(nil), // 252: openshell.sandbox.v1.NetworkPolicyRule - (*sandboxv1.L7DenyRule)(nil), // 253: openshell.sandbox.v1.L7DenyRule - (*sandboxv1.L7Rule)(nil), // 254: openshell.sandbox.v1.L7Rule - (*datamodelv1.Workspace)(nil), // 255: openshell.datamodel.v1.Workspace - (*sandboxv1.GetSandboxConfigRequest)(nil), // 256: openshell.sandbox.v1.GetSandboxConfigRequest - (*sandboxv1.GetGatewayConfigRequest)(nil), // 257: openshell.sandbox.v1.GetGatewayConfigRequest - (*sandboxv1.GetSandboxConfigResponse)(nil), // 258: openshell.sandbox.v1.GetSandboxConfigResponse - (*sandboxv1.GetGatewayConfigResponse)(nil), // 259: openshell.sandbox.v1.GetGatewayConfigResponse + (ProviderMutationKind)(0), // 1: openshell.v1.ProviderMutationKind + (ProviderReadinessState)(0), // 2: openshell.v1.ProviderReadinessState + (ProviderReadinessReason)(0), // 3: openshell.v1.ProviderReadinessReason + (ConfigComponent)(0), // 4: openshell.v1.ConfigComponent + (ConfigApplyOutcome)(0), // 5: openshell.v1.ConfigApplyOutcome + (ConfigUpdateOperationState)(0), // 6: openshell.v1.ConfigUpdateOperationState + (ProviderCredentialTokenGrantType)(0), // 7: openshell.v1.ProviderCredentialTokenGrantType + (ProviderCredentialRefreshStrategy)(0), // 8: openshell.v1.ProviderCredentialRefreshStrategy + (ProviderProfileCategory)(0), // 9: openshell.v1.ProviderProfileCategory + (PolicyStatus)(0), // 10: openshell.v1.PolicyStatus + (ServiceStatus)(0), // 11: openshell.v1.ServiceStatus + (WorkspaceRole)(0), // 12: openshell.v1.WorkspaceRole + (ProviderCredentialRefreshRecoveryAction)(0), // 13: openshell.v1.ProviderCredentialRefreshRecoveryAction + (DeletionOutcome)(0), // 14: openshell.v1.DeletionOutcome + (EndpointResult)(0), // 15: openshell.v1.EndpointResult + (*IssueSandboxTokenRequest)(nil), // 16: openshell.v1.IssueSandboxTokenRequest + (*IssueSandboxTokenResponse)(nil), // 17: openshell.v1.IssueSandboxTokenResponse + (*RefreshSandboxTokenRequest)(nil), // 18: openshell.v1.RefreshSandboxTokenRequest + (*RefreshSandboxTokenResponse)(nil), // 19: openshell.v1.RefreshSandboxTokenResponse + (*HealthRequest)(nil), // 20: openshell.v1.HealthRequest + (*HealthResponse)(nil), // 21: openshell.v1.HealthResponse + (*GetCurrentUserRequest)(nil), // 22: openshell.v1.GetCurrentUserRequest + (*GetCurrentUserResponse)(nil), // 23: openshell.v1.GetCurrentUserResponse + (*GetGatewayInfoRequest)(nil), // 24: openshell.v1.GetGatewayInfoRequest + (*GetGatewayInfoResponse)(nil), // 25: openshell.v1.GetGatewayInfoResponse + (*ComputeDriverInfo)(nil), // 26: openshell.v1.ComputeDriverInfo + (*ComputeDriverCapabilities)(nil), // 27: openshell.v1.ComputeDriverCapabilities + (*ResourceCapabilities)(nil), // 28: openshell.v1.ResourceCapabilities + (*CpuResourceCapabilities)(nil), // 29: openshell.v1.CpuResourceCapabilities + (*MemoryResourceCapabilities)(nil), // 30: openshell.v1.MemoryResourceCapabilities + (*GpuResourceCapabilities)(nil), // 31: openshell.v1.GpuResourceCapabilities + (*Sandbox)(nil), // 32: openshell.v1.Sandbox + (*SandboxSpec)(nil), // 33: openshell.v1.SandboxSpec + (*ResourceRequirements)(nil), // 34: openshell.v1.ResourceRequirements + (*GpuResourceRequirements)(nil), // 35: openshell.v1.GpuResourceRequirements + (*SandboxTemplate)(nil), // 36: openshell.v1.SandboxTemplate + (*SandboxWorkloadTemplate)(nil), // 37: openshell.v1.SandboxWorkloadTemplate + (*SandboxWorkloadTemplateSpec)(nil), // 38: openshell.v1.SandboxWorkloadTemplateSpec + (*SandboxWorkloadConfig)(nil), // 39: openshell.v1.SandboxWorkloadConfig + (*SandboxResources)(nil), // 40: openshell.v1.SandboxResources + (*SandboxServiceLevel)(nil), // 41: openshell.v1.SandboxServiceLevel + (*SandboxStartup)(nil), // 42: openshell.v1.SandboxStartup + (*SandboxWorkloadTemplateProvenance)(nil), // 43: openshell.v1.SandboxWorkloadTemplateProvenance + (*SandboxStatus)(nil), // 44: openshell.v1.SandboxStatus + (*SandboxCondition)(nil), // 45: openshell.v1.SandboxCondition + (*PlatformEvent)(nil), // 46: openshell.v1.PlatformEvent + (*CreateSandboxRequest)(nil), // 47: openshell.v1.CreateSandboxRequest + (*CreateSandboxTemplateRequest)(nil), // 48: openshell.v1.CreateSandboxTemplateRequest + (*GetSandboxTemplateRequest)(nil), // 49: openshell.v1.GetSandboxTemplateRequest + (*ListSandboxTemplatesRequest)(nil), // 50: openshell.v1.ListSandboxTemplatesRequest + (*DeleteSandboxTemplateRequest)(nil), // 51: openshell.v1.DeleteSandboxTemplateRequest + (*SandboxTemplateResponse)(nil), // 52: openshell.v1.SandboxTemplateResponse + (*ListSandboxTemplatesResponse)(nil), // 53: openshell.v1.ListSandboxTemplatesResponse + (*DeleteSandboxTemplateResponse)(nil), // 54: openshell.v1.DeleteSandboxTemplateResponse + (*BeginRootfsTarStagingRequest)(nil), // 55: openshell.v1.BeginRootfsTarStagingRequest + (*BeginRootfsTarStagingResponse)(nil), // 56: openshell.v1.BeginRootfsTarStagingResponse + (*GetSandboxRequest)(nil), // 57: openshell.v1.GetSandboxRequest + (*ListSandboxesRequest)(nil), // 58: openshell.v1.ListSandboxesRequest + (*ListSandboxProvidersRequest)(nil), // 59: openshell.v1.ListSandboxProvidersRequest + (*AttachSandboxProviderRequest)(nil), // 60: openshell.v1.AttachSandboxProviderRequest + (*DetachSandboxProviderRequest)(nil), // 61: openshell.v1.DetachSandboxProviderRequest + (*DeleteSandboxRequest)(nil), // 62: openshell.v1.DeleteSandboxRequest + (*StopSandboxRequest)(nil), // 63: openshell.v1.StopSandboxRequest + (*StartSandboxRequest)(nil), // 64: openshell.v1.StartSandboxRequest + (*SandboxResponse)(nil), // 65: openshell.v1.SandboxResponse + (*ListSandboxesResponse)(nil), // 66: openshell.v1.ListSandboxesResponse + (*ListSandboxProvidersResponse)(nil), // 67: openshell.v1.ListSandboxProvidersResponse + (*AttachSandboxProviderResponse)(nil), // 68: openshell.v1.AttachSandboxProviderResponse + (*DetachSandboxProviderResponse)(nil), // 69: openshell.v1.DetachSandboxProviderResponse + (*ProviderDesiredIdentity)(nil), // 70: openshell.v1.ProviderDesiredIdentity + (*ConfigSnapshotRevision)(nil), // 71: openshell.v1.ConfigSnapshotRevision + (*SandboxConfigRevision)(nil), // 72: openshell.v1.SandboxConfigRevision + (*ConfigUpdateOperation)(nil), // 73: openshell.v1.ConfigUpdateOperation + (*ProviderMutationReceipt)(nil), // 74: openshell.v1.ProviderMutationReceipt + (*ProviderReadinessObservation)(nil), // 75: openshell.v1.ProviderReadinessObservation + (*ProviderReadinessStatus)(nil), // 76: openshell.v1.ProviderReadinessStatus + (*GetSandboxProviderStatusRequest)(nil), // 77: openshell.v1.GetSandboxProviderStatusRequest + (*GetSandboxProviderStatusResponse)(nil), // 78: openshell.v1.GetSandboxProviderStatusResponse + (*ReportProviderReadinessRequest)(nil), // 79: openshell.v1.ReportProviderReadinessRequest + (*ReportProviderReadinessResponse)(nil), // 80: openshell.v1.ReportProviderReadinessResponse + (*DeleteSandboxResponse)(nil), // 81: openshell.v1.DeleteSandboxResponse + (*CreateSshSessionRequest)(nil), // 82: openshell.v1.CreateSshSessionRequest + (*CreateSshSessionResponse)(nil), // 83: openshell.v1.CreateSshSessionResponse + (*ExposeServiceRequest)(nil), // 84: openshell.v1.ExposeServiceRequest + (*GetServiceRequest)(nil), // 85: openshell.v1.GetServiceRequest + (*ListServicesRequest)(nil), // 86: openshell.v1.ListServicesRequest + (*ListServicesResponse)(nil), // 87: openshell.v1.ListServicesResponse + (*DeleteServiceRequest)(nil), // 88: openshell.v1.DeleteServiceRequest + (*DeleteServiceResponse)(nil), // 89: openshell.v1.DeleteServiceResponse + (*ServiceEndpoint)(nil), // 90: openshell.v1.ServiceEndpoint + (*ServiceEndpointResponse)(nil), // 91: openshell.v1.ServiceEndpointResponse + (*RevokeSshSessionRequest)(nil), // 92: openshell.v1.RevokeSshSessionRequest + (*RevokeSshSessionResponse)(nil), // 93: openshell.v1.RevokeSshSessionResponse + (*ExecSandboxRequest)(nil), // 94: openshell.v1.ExecSandboxRequest + (*ExecSandboxStdout)(nil), // 95: openshell.v1.ExecSandboxStdout + (*ExecSandboxStderr)(nil), // 96: openshell.v1.ExecSandboxStderr + (*ExecSandboxExit)(nil), // 97: openshell.v1.ExecSandboxExit + (*ExecSandboxEvent)(nil), // 98: openshell.v1.ExecSandboxEvent + (*TcpForwardInit)(nil), // 99: openshell.v1.TcpForwardInit + (*TcpForwardFrame)(nil), // 100: openshell.v1.TcpForwardFrame + (*ExecSandboxInput)(nil), // 101: openshell.v1.ExecSandboxInput + (*ExecSandboxWindowResize)(nil), // 102: openshell.v1.ExecSandboxWindowResize + (*SshSession)(nil), // 103: openshell.v1.SshSession + (*WatchSandboxRequest)(nil), // 104: openshell.v1.WatchSandboxRequest + (*SandboxStreamEvent)(nil), // 105: openshell.v1.SandboxStreamEvent + (*SandboxLogLine)(nil), // 106: openshell.v1.SandboxLogLine + (*SandboxStreamWarning)(nil), // 107: openshell.v1.SandboxStreamWarning + (*CreateProviderRequest)(nil), // 108: openshell.v1.CreateProviderRequest + (*GetProviderRequest)(nil), // 109: openshell.v1.GetProviderRequest + (*ListProvidersRequest)(nil), // 110: openshell.v1.ListProvidersRequest + (*UpdateProviderRequest)(nil), // 111: openshell.v1.UpdateProviderRequest + (*DeleteProviderRequest)(nil), // 112: openshell.v1.DeleteProviderRequest + (*ProviderResponse)(nil), // 113: openshell.v1.ProviderResponse + (*ListProvidersResponse)(nil), // 114: openshell.v1.ListProvidersResponse + (*ListProviderProfilesRequest)(nil), // 115: openshell.v1.ListProviderProfilesRequest + (*GetProviderProfileRequest)(nil), // 116: openshell.v1.GetProviderProfileRequest + (*ProviderProfileImportItem)(nil), // 117: openshell.v1.ProviderProfileImportItem + (*ProviderProfileDiagnostic)(nil), // 118: openshell.v1.ProviderProfileDiagnostic + (*ProviderCredentialTokenGrantAudienceOverride)(nil), // 119: openshell.v1.ProviderCredentialTokenGrantAudienceOverride + (*ProviderCredentialTokenGrantSubjectToken)(nil), // 120: openshell.v1.ProviderCredentialTokenGrantSubjectToken + (*ProviderCredentialTokenGrant)(nil), // 121: openshell.v1.ProviderCredentialTokenGrant + (*ProviderProfileCredential)(nil), // 122: openshell.v1.ProviderProfileCredential + (*ProviderCredentialRefreshMaterial)(nil), // 123: openshell.v1.ProviderCredentialRefreshMaterial + (*ProviderCredentialRefreshOutput)(nil), // 124: openshell.v1.ProviderCredentialRefreshOutput + (*ProviderCredentialRefresh)(nil), // 125: openshell.v1.ProviderCredentialRefresh + (*ProviderCredentialRefreshStatus)(nil), // 126: openshell.v1.ProviderCredentialRefreshStatus + (*ProviderProfileDiscovery)(nil), // 127: openshell.v1.ProviderProfileDiscovery + (*GetProviderRefreshStatusRequest)(nil), // 128: openshell.v1.GetProviderRefreshStatusRequest + (*GetProviderRefreshStatusResponse)(nil), // 129: openshell.v1.GetProviderRefreshStatusResponse + (*ConfigureProviderRefreshRequest)(nil), // 130: openshell.v1.ConfigureProviderRefreshRequest + (*ConfigureProviderRefreshResponse)(nil), // 131: openshell.v1.ConfigureProviderRefreshResponse + (*RotateProviderCredentialRequest)(nil), // 132: openshell.v1.RotateProviderCredentialRequest + (*RotateProviderCredentialResponse)(nil), // 133: openshell.v1.RotateProviderCredentialResponse + (*DeleteProviderRefreshRequest)(nil), // 134: openshell.v1.DeleteProviderRefreshRequest + (*DeleteProviderRefreshResponse)(nil), // 135: openshell.v1.DeleteProviderRefreshResponse + (*ProviderProfile)(nil), // 136: openshell.v1.ProviderProfile + (*ProviderProfileResponse)(nil), // 137: openshell.v1.ProviderProfileResponse + (*ListProviderProfilesResponse)(nil), // 138: openshell.v1.ListProviderProfilesResponse + (*ImportProviderProfilesRequest)(nil), // 139: openshell.v1.ImportProviderProfilesRequest + (*ImportProviderProfilesResponse)(nil), // 140: openshell.v1.ImportProviderProfilesResponse + (*UpdateProviderProfilesRequest)(nil), // 141: openshell.v1.UpdateProviderProfilesRequest + (*UpdateProviderProfilesResponse)(nil), // 142: openshell.v1.UpdateProviderProfilesResponse + (*LintProviderProfilesRequest)(nil), // 143: openshell.v1.LintProviderProfilesRequest + (*LintProviderProfilesResponse)(nil), // 144: openshell.v1.LintProviderProfilesResponse + (*DeleteProviderResponse)(nil), // 145: openshell.v1.DeleteProviderResponse + (*DeleteProviderProfileRequest)(nil), // 146: openshell.v1.DeleteProviderProfileRequest + (*DeleteProviderProfileResponse)(nil), // 147: openshell.v1.DeleteProviderProfileResponse + (*GetSandboxProviderEnvironmentRequest)(nil), // 148: openshell.v1.GetSandboxProviderEnvironmentRequest + (*StaticCredentialEndpointBinding)(nil), // 149: openshell.v1.StaticCredentialEndpointBinding + (*StaticCredentialBinding)(nil), // 150: openshell.v1.StaticCredentialBinding + (*GetSandboxProviderEnvironmentResponse)(nil), // 151: openshell.v1.GetSandboxProviderEnvironmentResponse + (*ExchangeProviderSubjectTokenRequest)(nil), // 152: openshell.v1.ExchangeProviderSubjectTokenRequest + (*ExchangeProviderSubjectTokenResponse)(nil), // 153: openshell.v1.ExchangeProviderSubjectTokenResponse + (*UpdateConfigRequest)(nil), // 154: openshell.v1.UpdateConfigRequest + (*PolicyMergeOperation)(nil), // 155: openshell.v1.PolicyMergeOperation + (*AddNetworkRule)(nil), // 156: openshell.v1.AddNetworkRule + (*RemoveNetworkEndpoint)(nil), // 157: openshell.v1.RemoveNetworkEndpoint + (*RemoveNetworkRule)(nil), // 158: openshell.v1.RemoveNetworkRule + (*AddDenyRules)(nil), // 159: openshell.v1.AddDenyRules + (*AddAllowRules)(nil), // 160: openshell.v1.AddAllowRules + (*RemoveNetworkBinary)(nil), // 161: openshell.v1.RemoveNetworkBinary + (*UpdateConfigResponse)(nil), // 162: openshell.v1.UpdateConfigResponse + (*GetSandboxPolicyStatusRequest)(nil), // 163: openshell.v1.GetSandboxPolicyStatusRequest + (*GetSandboxPolicyStatusResponse)(nil), // 164: openshell.v1.GetSandboxPolicyStatusResponse + (*ListSandboxPoliciesRequest)(nil), // 165: openshell.v1.ListSandboxPoliciesRequest + (*ListSandboxPoliciesResponse)(nil), // 166: openshell.v1.ListSandboxPoliciesResponse + (*ReportPolicyStatusRequest)(nil), // 167: openshell.v1.ReportPolicyStatusRequest + (*ReportPolicyStatusResponse)(nil), // 168: openshell.v1.ReportPolicyStatusResponse + (*SandboxPolicyRevision)(nil), // 169: openshell.v1.SandboxPolicyRevision + (*GetSandboxLogsRequest)(nil), // 170: openshell.v1.GetSandboxLogsRequest + (*PushSandboxLogsRequest)(nil), // 171: openshell.v1.PushSandboxLogsRequest + (*PushSandboxLogsResponse)(nil), // 172: openshell.v1.PushSandboxLogsResponse + (*GetSandboxLogsResponse)(nil), // 173: openshell.v1.GetSandboxLogsResponse + (*SupervisorMessage)(nil), // 174: openshell.v1.SupervisorMessage + (*GatewayMessage)(nil), // 175: openshell.v1.GatewayMessage + (*SupervisorHello)(nil), // 176: openshell.v1.SupervisorHello + (*SessionAccepted)(nil), // 177: openshell.v1.SessionAccepted + (*SessionRejected)(nil), // 178: openshell.v1.SessionRejected + (*SupervisorHeartbeat)(nil), // 179: openshell.v1.SupervisorHeartbeat + (*GatewayHeartbeat)(nil), // 180: openshell.v1.GatewayHeartbeat + (*ReportMainProcessExitRequest)(nil), // 181: openshell.v1.ReportMainProcessExitRequest + (*ReportMainProcessExitResponse)(nil), // 182: openshell.v1.ReportMainProcessExitResponse + (*FinalizeMainProcessExitRequest)(nil), // 183: openshell.v1.FinalizeMainProcessExitRequest + (*FinalizeMainProcessExitResponse)(nil), // 184: openshell.v1.FinalizeMainProcessExitResponse + (*RelayOpen)(nil), // 185: openshell.v1.RelayOpen + (*SshRelayTarget)(nil), // 186: openshell.v1.SshRelayTarget + (*TcpRelayTarget)(nil), // 187: openshell.v1.TcpRelayTarget + (*RelayInit)(nil), // 188: openshell.v1.RelayInit + (*RelayFrame)(nil), // 189: openshell.v1.RelayFrame + (*RelayOpenResult)(nil), // 190: openshell.v1.RelayOpenResult + (*RelayClose)(nil), // 191: openshell.v1.RelayClose + (*L7RequestSample)(nil), // 192: openshell.v1.L7RequestSample + (*DenialSummary)(nil), // 193: openshell.v1.DenialSummary + (*DenialGroupCount)(nil), // 194: openshell.v1.DenialGroupCount + (*NetworkActivitySummary)(nil), // 195: openshell.v1.NetworkActivitySummary + (*PolicyChunk)(nil), // 196: openshell.v1.PolicyChunk + (*DraftPolicyUpdate)(nil), // 197: openshell.v1.DraftPolicyUpdate + (*SubmitPolicyAnalysisRequest)(nil), // 198: openshell.v1.SubmitPolicyAnalysisRequest + (*SubmitPolicyAnalysisResponse)(nil), // 199: openshell.v1.SubmitPolicyAnalysisResponse + (*GetDraftPolicyRequest)(nil), // 200: openshell.v1.GetDraftPolicyRequest + (*GetDraftPolicyResponse)(nil), // 201: openshell.v1.GetDraftPolicyResponse + (*ApproveDraftChunkRequest)(nil), // 202: openshell.v1.ApproveDraftChunkRequest + (*ApproveDraftChunkResponse)(nil), // 203: openshell.v1.ApproveDraftChunkResponse + (*RejectDraftChunkRequest)(nil), // 204: openshell.v1.RejectDraftChunkRequest + (*RejectDraftChunkResponse)(nil), // 205: openshell.v1.RejectDraftChunkResponse + (*DraftChunkApproval)(nil), // 206: openshell.v1.DraftChunkApproval + (*ApproveAllDraftChunksRequest)(nil), // 207: openshell.v1.ApproveAllDraftChunksRequest + (*ApproveAllDraftChunksResponse)(nil), // 208: openshell.v1.ApproveAllDraftChunksResponse + (*EditDraftChunkRequest)(nil), // 209: openshell.v1.EditDraftChunkRequest + (*EditDraftChunkResponse)(nil), // 210: openshell.v1.EditDraftChunkResponse + (*UndoDraftChunkRequest)(nil), // 211: openshell.v1.UndoDraftChunkRequest + (*UndoDraftChunkResponse)(nil), // 212: openshell.v1.UndoDraftChunkResponse + (*ClearDraftChunksRequest)(nil), // 213: openshell.v1.ClearDraftChunksRequest + (*ClearDraftChunksResponse)(nil), // 214: openshell.v1.ClearDraftChunksResponse + (*GetDraftHistoryRequest)(nil), // 215: openshell.v1.GetDraftHistoryRequest + (*DraftHistoryEntry)(nil), // 216: openshell.v1.DraftHistoryEntry + (*GetDraftHistoryResponse)(nil), // 217: openshell.v1.GetDraftHistoryResponse + (*CreateWorkspaceRequest)(nil), // 218: openshell.v1.CreateWorkspaceRequest + (*CreateWorkspaceResponse)(nil), // 219: openshell.v1.CreateWorkspaceResponse + (*GetWorkspaceRequest)(nil), // 220: openshell.v1.GetWorkspaceRequest + (*GetWorkspaceResponse)(nil), // 221: openshell.v1.GetWorkspaceResponse + (*ListWorkspacesRequest)(nil), // 222: openshell.v1.ListWorkspacesRequest + (*ListWorkspacesResponse)(nil), // 223: openshell.v1.ListWorkspacesResponse + (*DeleteWorkspaceRequest)(nil), // 224: openshell.v1.DeleteWorkspaceRequest + (*DeleteWorkspaceResponse)(nil), // 225: openshell.v1.DeleteWorkspaceResponse + (*WorkspaceMember)(nil), // 226: openshell.v1.WorkspaceMember + (*AddWorkspaceMemberRequest)(nil), // 227: openshell.v1.AddWorkspaceMemberRequest + (*AddWorkspaceMemberResponse)(nil), // 228: openshell.v1.AddWorkspaceMemberResponse + (*RemoveWorkspaceMemberRequest)(nil), // 229: openshell.v1.RemoveWorkspaceMemberRequest + (*RemoveWorkspaceMemberResponse)(nil), // 230: openshell.v1.RemoveWorkspaceMemberResponse + (*ListWorkspaceMembersRequest)(nil), // 231: openshell.v1.ListWorkspaceMembersRequest + (*ListWorkspaceMembersResponse)(nil), // 232: openshell.v1.ListWorkspaceMembersResponse + (*ExtensionServiceCredential)(nil), // 233: openshell.v1.ExtensionServiceCredential + (*EndpointObservation)(nil), // 234: openshell.v1.EndpointObservation + (*ReportEndpointStatusRequest)(nil), // 235: openshell.v1.ReportEndpointStatusRequest + (*ReportEndpointStatusResponse)(nil), // 236: openshell.v1.ReportEndpointStatusResponse + (*EndpointStatus)(nil), // 237: openshell.v1.EndpointStatus + nil, // 238: openshell.v1.SandboxSpec.EnvironmentEntry + nil, // 239: openshell.v1.SandboxTemplate.LabelsEntry + nil, // 240: openshell.v1.SandboxTemplate.AnnotationsEntry + nil, // 241: openshell.v1.SandboxTemplate.EnvironmentEntry + nil, // 242: openshell.v1.SandboxWorkloadConfig.EnvironmentEntry + nil, // 243: openshell.v1.PlatformEvent.MetadataEntry + nil, // 244: openshell.v1.CreateSandboxRequest.LabelsEntry + nil, // 245: openshell.v1.CreateSandboxRequest.AnnotationsEntry + nil, // 246: openshell.v1.ExecSandboxRequest.EnvironmentEntry + nil, // 247: openshell.v1.SandboxLogLine.FieldsEntry + nil, // 248: openshell.v1.UpdateProviderRequest.CredentialExpirationTimesEntry + nil, // 249: openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + nil, // 250: openshell.v1.ProviderProfile.AnnotationsEntry + nil, // 251: openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + nil, // 252: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpirationTimesEntry + nil, // 253: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + nil, // 254: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + nil, // 255: openshell.v1.UpdateConfigRequest.AnnotationsEntry + nil, // 256: openshell.v1.UpdateConfigResponse.AnnotationsEntry + nil, // 257: openshell.v1.SandboxPolicyRevision.ProvenanceEntry + nil, // 258: openshell.v1.CreateWorkspaceRequest.LabelsEntry + (*timestamppb.Timestamp)(nil), // 259: google.protobuf.Timestamp + (*datamodelv1.ObjectMeta)(nil), // 260: openshell.datamodel.v1.ObjectMeta + (*sandboxv1.SandboxPolicy)(nil), // 261: openshell.sandbox.v1.SandboxPolicy + (*structpb.Struct)(nil), // 262: google.protobuf.Struct + (*durationpb.Duration)(nil), // 263: google.protobuf.Duration + (*datamodelv1.WorkspaceSelector)(nil), // 264: openshell.datamodel.v1.WorkspaceSelector + (*datamodelv1.Provider)(nil), // 265: openshell.datamodel.v1.Provider + (sandboxv1.PolicySource)(0), // 266: openshell.sandbox.v1.PolicySource + (*sandboxv1.NetworkEndpoint)(nil), // 267: openshell.sandbox.v1.NetworkEndpoint + (*sandboxv1.NetworkBinary)(nil), // 268: openshell.sandbox.v1.NetworkBinary + (*sandboxv1.SettingValue)(nil), // 269: openshell.sandbox.v1.SettingValue + (*sandboxv1.NetworkPolicyRule)(nil), // 270: openshell.sandbox.v1.NetworkPolicyRule + (*sandboxv1.L7DenyRule)(nil), // 271: openshell.sandbox.v1.L7DenyRule + (*sandboxv1.L7Rule)(nil), // 272: openshell.sandbox.v1.L7Rule + (*datamodelv1.Workspace)(nil), // 273: openshell.datamodel.v1.Workspace + (*sandboxv1.GetSandboxConfigRequest)(nil), // 274: openshell.sandbox.v1.GetSandboxConfigRequest + (*sandboxv1.GetGatewayConfigRequest)(nil), // 275: openshell.sandbox.v1.GetGatewayConfigRequest + (*sandboxv1.GetSandboxConfigResponse)(nil), // 276: openshell.sandbox.v1.GetSandboxConfigResponse + (*sandboxv1.GetGatewayConfigResponse)(nil), // 277: openshell.sandbox.v1.GetGatewayConfigResponse } var file_openshell_proto_depIdxs = []int32{ - 242, // 0: openshell.v1.IssueSandboxTokenResponse.expiration_time:type_name -> google.protobuf.Timestamp - 242, // 1: openshell.v1.RefreshSandboxTokenResponse.expiration_time:type_name -> google.protobuf.Timestamp - 216, // 2: openshell.v1.RefreshSandboxTokenResponse.extension_credentials:type_name -> openshell.v1.ExtensionServiceCredential - 242, // 3: openshell.v1.RefreshSandboxTokenResponse.sandbox_expiration_time:type_name -> google.protobuf.Timestamp - 5, // 4: openshell.v1.HealthResponse.status:type_name -> openshell.v1.ServiceStatus - 5, // 5: openshell.v1.GetGatewayInfoResponse.status:type_name -> openshell.v1.ServiceStatus - 20, // 6: openshell.v1.GetGatewayInfoResponse.compute_drivers:type_name -> openshell.v1.ComputeDriverInfo - 21, // 7: openshell.v1.ComputeDriverInfo.capabilities:type_name -> openshell.v1.ComputeDriverCapabilities - 22, // 8: openshell.v1.ComputeDriverCapabilities.resource_capabilities:type_name -> openshell.v1.ResourceCapabilities - 23, // 9: openshell.v1.ResourceCapabilities.cpu:type_name -> openshell.v1.CpuResourceCapabilities - 24, // 10: openshell.v1.ResourceCapabilities.memory:type_name -> openshell.v1.MemoryResourceCapabilities - 25, // 11: openshell.v1.ResourceCapabilities.gpu:type_name -> openshell.v1.GpuResourceCapabilities - 243, // 12: openshell.v1.Sandbox.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 27, // 13: openshell.v1.Sandbox.spec:type_name -> openshell.v1.SandboxSpec - 38, // 14: openshell.v1.Sandbox.status:type_name -> openshell.v1.SandboxStatus - 37, // 15: openshell.v1.Sandbox.created_from_workload_template:type_name -> openshell.v1.SandboxWorkloadTemplateProvenance - 221, // 16: openshell.v1.SandboxSpec.environment:type_name -> openshell.v1.SandboxSpec.EnvironmentEntry - 30, // 17: openshell.v1.SandboxSpec.template:type_name -> openshell.v1.SandboxTemplate - 244, // 18: openshell.v1.SandboxSpec.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 28, // 19: openshell.v1.SandboxSpec.resource_requirements:type_name -> openshell.v1.ResourceRequirements - 29, // 20: openshell.v1.ResourceRequirements.gpu:type_name -> openshell.v1.GpuResourceRequirements - 222, // 21: openshell.v1.SandboxTemplate.labels:type_name -> openshell.v1.SandboxTemplate.LabelsEntry - 223, // 22: openshell.v1.SandboxTemplate.annotations:type_name -> openshell.v1.SandboxTemplate.AnnotationsEntry - 224, // 23: openshell.v1.SandboxTemplate.environment:type_name -> openshell.v1.SandboxTemplate.EnvironmentEntry - 245, // 24: openshell.v1.SandboxTemplate.resources:type_name -> google.protobuf.Struct - 245, // 25: openshell.v1.SandboxTemplate.driver_config:type_name -> google.protobuf.Struct - 243, // 26: openshell.v1.SandboxWorkloadTemplate.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 32, // 27: openshell.v1.SandboxWorkloadTemplate.spec:type_name -> openshell.v1.SandboxWorkloadTemplateSpec - 33, // 28: openshell.v1.SandboxWorkloadTemplateSpec.workload:type_name -> openshell.v1.SandboxWorkloadConfig - 245, // 29: openshell.v1.SandboxWorkloadTemplateSpec.driver_config:type_name -> google.protobuf.Struct - 35, // 30: openshell.v1.SandboxWorkloadTemplateSpec.desired_service_level:type_name -> openshell.v1.SandboxServiceLevel - 225, // 31: openshell.v1.SandboxWorkloadConfig.environment:type_name -> openshell.v1.SandboxWorkloadConfig.EnvironmentEntry - 34, // 32: openshell.v1.SandboxWorkloadConfig.resources:type_name -> openshell.v1.SandboxResources - 29, // 33: openshell.v1.SandboxResources.gpu:type_name -> openshell.v1.GpuResourceRequirements - 36, // 34: openshell.v1.SandboxServiceLevel.startup:type_name -> openshell.v1.SandboxStartup - 246, // 35: openshell.v1.SandboxStartup.ready_within:type_name -> google.protobuf.Duration - 39, // 36: openshell.v1.SandboxStatus.conditions:type_name -> openshell.v1.SandboxCondition + 259, // 0: openshell.v1.IssueSandboxTokenResponse.expiration_time:type_name -> google.protobuf.Timestamp + 259, // 1: openshell.v1.RefreshSandboxTokenResponse.expiration_time:type_name -> google.protobuf.Timestamp + 233, // 2: openshell.v1.RefreshSandboxTokenResponse.extension_credentials:type_name -> openshell.v1.ExtensionServiceCredential + 259, // 3: openshell.v1.RefreshSandboxTokenResponse.sandbox_expiration_time:type_name -> google.protobuf.Timestamp + 11, // 4: openshell.v1.HealthResponse.status:type_name -> openshell.v1.ServiceStatus + 11, // 5: openshell.v1.GetGatewayInfoResponse.status:type_name -> openshell.v1.ServiceStatus + 26, // 6: openshell.v1.GetGatewayInfoResponse.compute_drivers:type_name -> openshell.v1.ComputeDriverInfo + 27, // 7: openshell.v1.ComputeDriverInfo.capabilities:type_name -> openshell.v1.ComputeDriverCapabilities + 28, // 8: openshell.v1.ComputeDriverCapabilities.resource_capabilities:type_name -> openshell.v1.ResourceCapabilities + 29, // 9: openshell.v1.ResourceCapabilities.cpu:type_name -> openshell.v1.CpuResourceCapabilities + 30, // 10: openshell.v1.ResourceCapabilities.memory:type_name -> openshell.v1.MemoryResourceCapabilities + 31, // 11: openshell.v1.ResourceCapabilities.gpu:type_name -> openshell.v1.GpuResourceCapabilities + 260, // 12: openshell.v1.Sandbox.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 33, // 13: openshell.v1.Sandbox.spec:type_name -> openshell.v1.SandboxSpec + 44, // 14: openshell.v1.Sandbox.status:type_name -> openshell.v1.SandboxStatus + 43, // 15: openshell.v1.Sandbox.created_from_workload_template:type_name -> openshell.v1.SandboxWorkloadTemplateProvenance + 238, // 16: openshell.v1.SandboxSpec.environment:type_name -> openshell.v1.SandboxSpec.EnvironmentEntry + 36, // 17: openshell.v1.SandboxSpec.template:type_name -> openshell.v1.SandboxTemplate + 261, // 18: openshell.v1.SandboxSpec.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 34, // 19: openshell.v1.SandboxSpec.resource_requirements:type_name -> openshell.v1.ResourceRequirements + 35, // 20: openshell.v1.ResourceRequirements.gpu:type_name -> openshell.v1.GpuResourceRequirements + 239, // 21: openshell.v1.SandboxTemplate.labels:type_name -> openshell.v1.SandboxTemplate.LabelsEntry + 240, // 22: openshell.v1.SandboxTemplate.annotations:type_name -> openshell.v1.SandboxTemplate.AnnotationsEntry + 241, // 23: openshell.v1.SandboxTemplate.environment:type_name -> openshell.v1.SandboxTemplate.EnvironmentEntry + 262, // 24: openshell.v1.SandboxTemplate.resources:type_name -> google.protobuf.Struct + 262, // 25: openshell.v1.SandboxTemplate.driver_config:type_name -> google.protobuf.Struct + 260, // 26: openshell.v1.SandboxWorkloadTemplate.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 38, // 27: openshell.v1.SandboxWorkloadTemplate.spec:type_name -> openshell.v1.SandboxWorkloadTemplateSpec + 39, // 28: openshell.v1.SandboxWorkloadTemplateSpec.workload:type_name -> openshell.v1.SandboxWorkloadConfig + 262, // 29: openshell.v1.SandboxWorkloadTemplateSpec.driver_config:type_name -> google.protobuf.Struct + 41, // 30: openshell.v1.SandboxWorkloadTemplateSpec.desired_service_level:type_name -> openshell.v1.SandboxServiceLevel + 242, // 31: openshell.v1.SandboxWorkloadConfig.environment:type_name -> openshell.v1.SandboxWorkloadConfig.EnvironmentEntry + 40, // 32: openshell.v1.SandboxWorkloadConfig.resources:type_name -> openshell.v1.SandboxResources + 35, // 33: openshell.v1.SandboxResources.gpu:type_name -> openshell.v1.GpuResourceRequirements + 42, // 34: openshell.v1.SandboxServiceLevel.startup:type_name -> openshell.v1.SandboxStartup + 263, // 35: openshell.v1.SandboxStartup.ready_within:type_name -> google.protobuf.Duration + 45, // 36: openshell.v1.SandboxStatus.conditions:type_name -> openshell.v1.SandboxCondition 0, // 37: openshell.v1.SandboxStatus.phase:type_name -> openshell.v1.SandboxPhase - 220, // 38: openshell.v1.SandboxStatus.endpoint_statuses:type_name -> openshell.v1.EndpointStatus - 242, // 39: openshell.v1.SandboxCondition.transition_time:type_name -> google.protobuf.Timestamp - 242, // 40: openshell.v1.PlatformEvent.event_time:type_name -> google.protobuf.Timestamp - 226, // 41: openshell.v1.PlatformEvent.metadata:type_name -> openshell.v1.PlatformEvent.MetadataEntry - 27, // 42: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec - 227, // 43: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry - 228, // 44: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry - 247, // 45: openshell.v1.CreateSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 31, // 46: openshell.v1.CreateSandboxTemplateRequest.template:type_name -> openshell.v1.SandboxWorkloadTemplate - 247, // 47: openshell.v1.CreateSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 48: openshell.v1.GetSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 49: openshell.v1.ListSandboxTemplatesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 50: openshell.v1.DeleteSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 31, // 51: openshell.v1.SandboxTemplateResponse.template:type_name -> openshell.v1.SandboxWorkloadTemplate - 31, // 52: openshell.v1.ListSandboxTemplatesResponse.templates:type_name -> openshell.v1.SandboxWorkloadTemplate - 8, // 53: openshell.v1.DeleteSandboxTemplateResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 247, // 54: openshell.v1.BeginRootfsTarStagingRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 242, // 55: openshell.v1.BeginRootfsTarStagingResponse.expiration_time:type_name -> google.protobuf.Timestamp - 247, // 56: openshell.v1.GetSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 57: openshell.v1.ListSandboxesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 58: openshell.v1.ListSandboxProvidersRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 59: openshell.v1.AttachSandboxProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 60: openshell.v1.DetachSandboxProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 61: openshell.v1.DeleteSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 62: openshell.v1.StopSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 63: openshell.v1.StartSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 26, // 64: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox - 26, // 65: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox - 248, // 66: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 26, // 67: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 26, // 68: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 8, // 69: openshell.v1.DeleteSandboxResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 242, // 70: openshell.v1.CreateSshSessionResponse.expiration_time:type_name -> google.protobuf.Timestamp - 247, // 71: openshell.v1.ExposeServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 72: openshell.v1.GetServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 73: openshell.v1.ListServicesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 74, // 74: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse - 247, // 75: openshell.v1.DeleteServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 8, // 76: openshell.v1.DeleteServiceResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 243, // 77: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 73, // 78: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint - 8, // 79: openshell.v1.RevokeSshSessionResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 229, // 80: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry - 246, // 81: openshell.v1.ExecSandboxRequest.execution_timeout:type_name -> google.protobuf.Duration - 78, // 82: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout - 79, // 83: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr - 80, // 84: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit - 169, // 85: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget - 170, // 86: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget - 82, // 87: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit - 77, // 88: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest - 85, // 89: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize - 243, // 90: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 242, // 91: openshell.v1.SshSession.expiration_time:type_name -> google.protobuf.Timestamp - 242, // 92: openshell.v1.WatchSandboxRequest.since_time:type_name -> google.protobuf.Timestamp - 26, // 93: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox - 89, // 94: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine - 40, // 95: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent - 90, // 96: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning - 180, // 97: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate - 242, // 98: openshell.v1.SandboxLogLine.event_time:type_name -> google.protobuf.Timestamp - 230, // 99: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry - 248, // 100: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 247, // 101: openshell.v1.CreateProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 102: openshell.v1.GetProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 103: openshell.v1.ListProvidersRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 248, // 104: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 231, // 105: openshell.v1.UpdateProviderRequest.credential_expiration_times:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpirationTimesEntry - 247, // 106: openshell.v1.UpdateProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 107: openshell.v1.DeleteProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 248, // 108: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider - 248, // 109: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 119, // 110: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile - 246, // 111: openshell.v1.ProviderCredentialTokenGrant.cache_ttl:type_name -> google.protobuf.Duration - 102, // 112: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride - 1, // 113: openshell.v1.ProviderCredentialTokenGrant.grant_type:type_name -> openshell.v1.ProviderCredentialTokenGrantType - 103, // 114: openshell.v1.ProviderCredentialTokenGrant.subject_token:type_name -> openshell.v1.ProviderCredentialTokenGrantSubjectToken - 108, // 115: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh - 104, // 116: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant - 2, // 117: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 246, // 118: openshell.v1.ProviderCredentialRefresh.refresh_before:type_name -> google.protobuf.Duration - 246, // 119: openshell.v1.ProviderCredentialRefresh.max_lifetime:type_name -> google.protobuf.Duration - 106, // 120: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial - 107, // 121: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput - 2, // 122: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 242, // 123: openshell.v1.ProviderCredentialRefreshStatus.expiration_time:type_name -> google.protobuf.Timestamp - 242, // 124: openshell.v1.ProviderCredentialRefreshStatus.next_refresh_time:type_name -> google.protobuf.Timestamp - 242, // 125: openshell.v1.ProviderCredentialRefreshStatus.last_refresh_time:type_name -> google.protobuf.Timestamp - 7, // 126: openshell.v1.ProviderCredentialRefreshStatus.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction - 242, // 127: openshell.v1.ProviderCredentialRefreshStatus.last_error_time:type_name -> google.protobuf.Timestamp - 247, // 128: openshell.v1.GetProviderRefreshStatusRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 109, // 129: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 2, // 130: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 232, // 131: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - 242, // 132: openshell.v1.ConfigureProviderRefreshRequest.expiration_time:type_name -> google.protobuf.Timestamp - 247, // 133: openshell.v1.ConfigureProviderRefreshRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 109, // 134: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 247, // 135: openshell.v1.RotateProviderCredentialRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 109, // 136: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 247, // 137: openshell.v1.DeleteProviderRefreshRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 8, // 138: openshell.v1.DeleteProviderRefreshResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 3, // 139: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory - 105, // 140: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential - 249, // 141: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint - 250, // 142: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary - 110, // 143: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery - 233, // 144: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry - 119, // 145: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile - 119, // 146: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 100, // 147: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 101, // 148: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 119, // 149: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 100, // 150: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem - 101, // 151: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 119, // 152: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile - 100, // 153: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 101, // 154: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 8, // 155: openshell.v1.DeleteProviderResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 8, // 156: openshell.v1.DeleteProviderProfileResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 132, // 157: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding - 234, // 158: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - 235, // 159: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expiration_times:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpirationTimesEntry - 236, // 160: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - 237, // 161: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - 246, // 162: openshell.v1.ExchangeProviderSubjectTokenResponse.expires_after:type_name -> google.protobuf.Duration - 244, // 163: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 251, // 164: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue - 138, // 165: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation - 238, // 166: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry - 247, // 167: openshell.v1.UpdateConfigRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 139, // 168: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule - 140, // 169: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint - 141, // 170: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule - 142, // 171: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules - 143, // 172: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules - 144, // 173: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary - 252, // 174: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 253, // 175: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule - 254, // 176: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule - 239, // 177: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry - 247, // 178: openshell.v1.GetSandboxPolicyStatusRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 152, // 179: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision - 247, // 180: openshell.v1.ListSandboxPoliciesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 152, // 181: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision - 4, // 182: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus - 4, // 183: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus - 242, // 184: openshell.v1.SandboxPolicyRevision.created_time:type_name -> google.protobuf.Timestamp - 242, // 185: openshell.v1.SandboxPolicyRevision.loaded_time:type_name -> google.protobuf.Timestamp - 244, // 186: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 240, // 187: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry - 242, // 188: openshell.v1.GetSandboxLogsRequest.since_time:type_name -> google.protobuf.Timestamp - 247, // 189: openshell.v1.GetSandboxLogsRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 89, // 190: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine - 89, // 191: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine - 159, // 192: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello - 162, // 193: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat - 173, // 194: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult - 174, // 195: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose - 160, // 196: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted - 161, // 197: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected - 163, // 198: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat - 168, // 199: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen - 174, // 200: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose - 246, // 201: openshell.v1.SessionAccepted.heartbeat_interval:type_name -> google.protobuf.Duration - 169, // 202: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget - 170, // 203: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget - 171, // 204: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit - 242, // 205: openshell.v1.DenialSummary.first_seen_time:type_name -> google.protobuf.Timestamp - 242, // 206: openshell.v1.DenialSummary.last_seen_time:type_name -> google.protobuf.Timestamp - 175, // 207: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample - 177, // 208: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount - 252, // 209: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 242, // 210: openshell.v1.PolicyChunk.created_time:type_name -> google.protobuf.Timestamp - 242, // 211: openshell.v1.PolicyChunk.decided_time:type_name -> google.protobuf.Timestamp - 242, // 212: openshell.v1.PolicyChunk.first_seen_time:type_name -> google.protobuf.Timestamp - 242, // 213: openshell.v1.PolicyChunk.last_seen_time:type_name -> google.protobuf.Timestamp - 244, // 214: openshell.v1.PolicyChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 244, // 215: openshell.v1.PolicyChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 176, // 216: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary - 179, // 217: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk - 178, // 218: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary - 247, // 219: openshell.v1.GetDraftPolicyRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 179, // 220: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk - 242, // 221: openshell.v1.GetDraftPolicyResponse.last_analyzed_time:type_name -> google.protobuf.Timestamp - 247, // 222: openshell.v1.ApproveDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 223: openshell.v1.RejectDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 189, // 224: openshell.v1.ApproveAllDraftChunksRequest.approvals:type_name -> openshell.v1.DraftChunkApproval - 247, // 225: openshell.v1.ApproveAllDraftChunksRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 252, // 226: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 247, // 227: openshell.v1.EditDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 228: openshell.v1.UndoDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 229: openshell.v1.ClearDraftChunksRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 247, // 230: openshell.v1.GetDraftHistoryRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector - 242, // 231: openshell.v1.DraftHistoryEntry.event_time:type_name -> google.protobuf.Timestamp - 199, // 232: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry - 241, // 233: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry - 255, // 234: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 255, // 235: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 255, // 236: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace - 8, // 237: openshell.v1.DeleteWorkspaceResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 243, // 238: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 6, // 239: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole - 6, // 240: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole - 209, // 241: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember - 8, // 242: openshell.v1.RemoveWorkspaceMemberResponse.outcome:type_name -> openshell.v1.DeletionOutcome - 209, // 243: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember - 242, // 244: openshell.v1.ExtensionServiceCredential.expiration_time:type_name -> google.protobuf.Timestamp - 9, // 245: openshell.v1.EndpointObservation.result:type_name -> openshell.v1.EndpointResult - 217, // 246: openshell.v1.ReportEndpointStatusRequest.observations:type_name -> openshell.v1.EndpointObservation - 9, // 247: openshell.v1.EndpointStatus.last_result:type_name -> openshell.v1.EndpointResult - 242, // 248: openshell.v1.EndpointStatus.last_reported_time:type_name -> google.protobuf.Timestamp - 242, // 249: openshell.v1.UpdateProviderRequest.CredentialExpirationTimesEntry.value:type_name -> google.protobuf.Timestamp - 242, // 250: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpirationTimesEntry.value:type_name -> google.protobuf.Timestamp - 105, // 251: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential - 133, // 252: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding - 14, // 253: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest - 16, // 254: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest - 18, // 255: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest - 41, // 256: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest - 49, // 257: openshell.v1.OpenShell.BeginRootfsTarStaging:input_type -> openshell.v1.BeginRootfsTarStagingRequest - 51, // 258: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest - 52, // 259: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest - 42, // 260: openshell.v1.OpenShell.CreateSandboxTemplate:input_type -> openshell.v1.CreateSandboxTemplateRequest - 43, // 261: openshell.v1.OpenShell.GetSandboxTemplate:input_type -> openshell.v1.GetSandboxTemplateRequest - 44, // 262: openshell.v1.OpenShell.ListSandboxTemplates:input_type -> openshell.v1.ListSandboxTemplatesRequest - 45, // 263: openshell.v1.OpenShell.DeleteSandboxTemplate:input_type -> openshell.v1.DeleteSandboxTemplateRequest - 53, // 264: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest - 54, // 265: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest - 55, // 266: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest - 56, // 267: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest - 57, // 268: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest - 58, // 269: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest - 65, // 270: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest - 67, // 271: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest - 68, // 272: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest - 69, // 273: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest - 71, // 274: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest - 75, // 275: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest - 77, // 276: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest - 83, // 277: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame - 84, // 278: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput - 91, // 279: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest - 92, // 280: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest - 93, // 281: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest - 98, // 282: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest - 99, // 283: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest - 122, // 284: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest - 124, // 285: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest - 126, // 286: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest - 94, // 287: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest - 111, // 288: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest - 113, // 289: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest - 115, // 290: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest - 117, // 291: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest - 95, // 292: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest - 129, // 293: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest - 256, // 294: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest - 257, // 295: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest - 137, // 296: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest - 146, // 297: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest - 148, // 298: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest - 150, // 299: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest - 218, // 300: openshell.v1.OpenShell.ReportEndpointStatus:input_type -> openshell.v1.ReportEndpointStatusRequest - 131, // 301: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest - 135, // 302: openshell.v1.OpenShell.ExchangeProviderSubjectToken:input_type -> openshell.v1.ExchangeProviderSubjectTokenRequest - 153, // 303: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest - 154, // 304: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest - 157, // 305: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage - 164, // 306: openshell.v1.OpenShell.ReportMainProcessExit:input_type -> openshell.v1.ReportMainProcessExitRequest - 166, // 307: openshell.v1.OpenShell.FinalizeMainProcessExit:input_type -> openshell.v1.FinalizeMainProcessExitRequest - 172, // 308: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame - 87, // 309: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest - 181, // 310: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest - 183, // 311: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest - 185, // 312: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest - 187, // 313: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest - 190, // 314: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest - 192, // 315: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest - 194, // 316: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest - 196, // 317: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest - 198, // 318: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest - 10, // 319: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest - 12, // 320: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest - 201, // 321: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest - 203, // 322: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest - 205, // 323: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest - 207, // 324: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest - 210, // 325: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest - 212, // 326: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest - 214, // 327: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest - 15, // 328: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse - 17, // 329: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse - 19, // 330: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse - 59, // 331: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse - 50, // 332: openshell.v1.OpenShell.BeginRootfsTarStaging:output_type -> openshell.v1.BeginRootfsTarStagingResponse - 59, // 333: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse - 60, // 334: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse - 46, // 335: openshell.v1.OpenShell.CreateSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse - 46, // 336: openshell.v1.OpenShell.GetSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse - 47, // 337: openshell.v1.OpenShell.ListSandboxTemplates:output_type -> openshell.v1.ListSandboxTemplatesResponse - 48, // 338: openshell.v1.OpenShell.DeleteSandboxTemplate:output_type -> openshell.v1.DeleteSandboxTemplateResponse - 61, // 339: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse - 62, // 340: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse - 63, // 341: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse - 64, // 342: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse - 59, // 343: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse - 59, // 344: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse - 66, // 345: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse - 74, // 346: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse - 74, // 347: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse - 70, // 348: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse - 72, // 349: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse - 76, // 350: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse - 81, // 351: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent - 83, // 352: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame - 81, // 353: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent - 96, // 354: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse - 96, // 355: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse - 97, // 356: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse - 121, // 357: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse - 120, // 358: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse - 123, // 359: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse - 125, // 360: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse - 127, // 361: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse - 96, // 362: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse - 112, // 363: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse - 114, // 364: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse - 116, // 365: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse - 118, // 366: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse - 128, // 367: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse - 130, // 368: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse - 258, // 369: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse - 259, // 370: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse - 145, // 371: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse - 147, // 372: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse - 149, // 373: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse - 151, // 374: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse - 219, // 375: openshell.v1.OpenShell.ReportEndpointStatus:output_type -> openshell.v1.ReportEndpointStatusResponse - 134, // 376: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse - 136, // 377: openshell.v1.OpenShell.ExchangeProviderSubjectToken:output_type -> openshell.v1.ExchangeProviderSubjectTokenResponse - 156, // 378: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse - 155, // 379: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse - 158, // 380: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage - 165, // 381: openshell.v1.OpenShell.ReportMainProcessExit:output_type -> openshell.v1.ReportMainProcessExitResponse - 167, // 382: openshell.v1.OpenShell.FinalizeMainProcessExit:output_type -> openshell.v1.FinalizeMainProcessExitResponse - 172, // 383: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame - 88, // 384: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent - 182, // 385: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse - 184, // 386: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse - 186, // 387: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse - 188, // 388: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse - 191, // 389: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse - 193, // 390: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse - 195, // 391: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse - 197, // 392: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse - 200, // 393: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse - 11, // 394: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse - 13, // 395: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse - 202, // 396: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse - 204, // 397: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse - 206, // 398: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse - 208, // 399: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse - 211, // 400: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse - 213, // 401: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse - 215, // 402: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse - 328, // [328:403] is the sub-list for method output_type - 253, // [253:328] is the sub-list for method input_type - 253, // [253:253] is the sub-list for extension type_name - 253, // [253:253] is the sub-list for extension extendee - 0, // [0:253] is the sub-list for field type_name + 237, // 38: openshell.v1.SandboxStatus.endpoint_statuses:type_name -> openshell.v1.EndpointStatus + 259, // 39: openshell.v1.SandboxCondition.transition_time:type_name -> google.protobuf.Timestamp + 259, // 40: openshell.v1.PlatformEvent.event_time:type_name -> google.protobuf.Timestamp + 243, // 41: openshell.v1.PlatformEvent.metadata:type_name -> openshell.v1.PlatformEvent.MetadataEntry + 33, // 42: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec + 244, // 43: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry + 245, // 44: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry + 264, // 45: openshell.v1.CreateSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 37, // 46: openshell.v1.CreateSandboxTemplateRequest.template:type_name -> openshell.v1.SandboxWorkloadTemplate + 264, // 47: openshell.v1.CreateSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 48: openshell.v1.GetSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 49: openshell.v1.ListSandboxTemplatesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 50: openshell.v1.DeleteSandboxTemplateRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 37, // 51: openshell.v1.SandboxTemplateResponse.template:type_name -> openshell.v1.SandboxWorkloadTemplate + 37, // 52: openshell.v1.ListSandboxTemplatesResponse.templates:type_name -> openshell.v1.SandboxWorkloadTemplate + 14, // 53: openshell.v1.DeleteSandboxTemplateResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 264, // 54: openshell.v1.BeginRootfsTarStagingRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 259, // 55: openshell.v1.BeginRootfsTarStagingResponse.expiration_time:type_name -> google.protobuf.Timestamp + 264, // 56: openshell.v1.GetSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 57: openshell.v1.ListSandboxesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 58: openshell.v1.ListSandboxProvidersRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 59: openshell.v1.AttachSandboxProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 60: openshell.v1.DetachSandboxProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 61: openshell.v1.DeleteSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 62: openshell.v1.StopSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 63: openshell.v1.StartSandboxRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 32, // 64: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox + 32, // 65: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox + 265, // 66: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 32, // 67: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 74, // 68: openshell.v1.AttachSandboxProviderResponse.receipt:type_name -> openshell.v1.ProviderMutationReceipt + 32, // 69: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 74, // 70: openshell.v1.DetachSandboxProviderResponse.receipt:type_name -> openshell.v1.ProviderMutationReceipt + 72, // 71: openshell.v1.ConfigSnapshotRevision.sandbox_config:type_name -> openshell.v1.SandboxConfigRevision + 70, // 72: openshell.v1.ConfigSnapshotRevision.provider_target:type_name -> openshell.v1.ProviderDesiredIdentity + 266, // 73: openshell.v1.SandboxConfigRevision.policy_source:type_name -> openshell.sandbox.v1.PolicySource + 4, // 74: openshell.v1.ConfigUpdateOperation.component:type_name -> openshell.v1.ConfigComponent + 71, // 75: openshell.v1.ConfigUpdateOperation.target_revision:type_name -> openshell.v1.ConfigSnapshotRevision + 6, // 76: openshell.v1.ConfigUpdateOperation.state:type_name -> openshell.v1.ConfigUpdateOperationState + 5, // 77: openshell.v1.ConfigUpdateOperation.outcome:type_name -> openshell.v1.ConfigApplyOutcome + 259, // 78: openshell.v1.ConfigUpdateOperation.created_time:type_name -> google.protobuf.Timestamp + 259, // 79: openshell.v1.ConfigUpdateOperation.updated_time:type_name -> google.protobuf.Timestamp + 259, // 80: openshell.v1.ConfigUpdateOperation.completed_time:type_name -> google.protobuf.Timestamp + 1, // 81: openshell.v1.ProviderMutationReceipt.kind:type_name -> openshell.v1.ProviderMutationKind + 70, // 82: openshell.v1.ProviderMutationReceipt.desired:type_name -> openshell.v1.ProviderDesiredIdentity + 259, // 83: openshell.v1.ProviderMutationReceipt.persisted_time:type_name -> google.protobuf.Timestamp + 3, // 84: openshell.v1.ProviderReadinessObservation.reason:type_name -> openshell.v1.ProviderReadinessReason + 74, // 85: openshell.v1.ProviderReadinessStatus.receipt:type_name -> openshell.v1.ProviderMutationReceipt + 2, // 86: openshell.v1.ProviderReadinessStatus.state:type_name -> openshell.v1.ProviderReadinessState + 3, // 87: openshell.v1.ProviderReadinessStatus.reason:type_name -> openshell.v1.ProviderReadinessReason + 75, // 88: openshell.v1.ProviderReadinessStatus.observed:type_name -> openshell.v1.ProviderReadinessObservation + 259, // 89: openshell.v1.ProviderReadinessStatus.observed_time:type_name -> google.protobuf.Timestamp + 259, // 90: openshell.v1.ProviderReadinessStatus.evaluated_time:type_name -> google.protobuf.Timestamp + 73, // 91: openshell.v1.ProviderReadinessStatus.operation:type_name -> openshell.v1.ConfigUpdateOperation + 264, // 92: openshell.v1.GetSandboxProviderStatusRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 76, // 93: openshell.v1.GetSandboxProviderStatusResponse.status:type_name -> openshell.v1.ProviderReadinessStatus + 75, // 94: openshell.v1.ReportProviderReadinessRequest.observation:type_name -> openshell.v1.ProviderReadinessObservation + 263, // 95: openshell.v1.ReportProviderReadinessResponse.report_interval:type_name -> google.protobuf.Duration + 263, // 96: openshell.v1.ReportProviderReadinessResponse.observation_ttl:type_name -> google.protobuf.Duration + 14, // 97: openshell.v1.DeleteSandboxResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 259, // 98: openshell.v1.CreateSshSessionResponse.expiration_time:type_name -> google.protobuf.Timestamp + 264, // 99: openshell.v1.ExposeServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 100: openshell.v1.GetServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 101: openshell.v1.ListServicesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 91, // 102: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse + 264, // 103: openshell.v1.DeleteServiceRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 14, // 104: openshell.v1.DeleteServiceResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 260, // 105: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 90, // 106: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint + 14, // 107: openshell.v1.RevokeSshSessionResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 246, // 108: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry + 263, // 109: openshell.v1.ExecSandboxRequest.execution_timeout:type_name -> google.protobuf.Duration + 95, // 110: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout + 96, // 111: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr + 97, // 112: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit + 186, // 113: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget + 187, // 114: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget + 99, // 115: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit + 94, // 116: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest + 102, // 117: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize + 260, // 118: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 259, // 119: openshell.v1.SshSession.expiration_time:type_name -> google.protobuf.Timestamp + 259, // 120: openshell.v1.WatchSandboxRequest.since_time:type_name -> google.protobuf.Timestamp + 32, // 121: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox + 106, // 122: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine + 46, // 123: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent + 107, // 124: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning + 197, // 125: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate + 259, // 126: openshell.v1.SandboxLogLine.event_time:type_name -> google.protobuf.Timestamp + 247, // 127: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry + 265, // 128: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 264, // 129: openshell.v1.CreateProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 130: openshell.v1.GetProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 131: openshell.v1.ListProvidersRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 265, // 132: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 248, // 133: openshell.v1.UpdateProviderRequest.credential_expiration_times:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpirationTimesEntry + 264, // 134: openshell.v1.UpdateProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 135: openshell.v1.DeleteProviderRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 265, // 136: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider + 74, // 137: openshell.v1.ProviderResponse.target_receipts:type_name -> openshell.v1.ProviderMutationReceipt + 265, // 138: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 136, // 139: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile + 263, // 140: openshell.v1.ProviderCredentialTokenGrant.cache_ttl:type_name -> google.protobuf.Duration + 119, // 141: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride + 7, // 142: openshell.v1.ProviderCredentialTokenGrant.grant_type:type_name -> openshell.v1.ProviderCredentialTokenGrantType + 120, // 143: openshell.v1.ProviderCredentialTokenGrant.subject_token:type_name -> openshell.v1.ProviderCredentialTokenGrantSubjectToken + 125, // 144: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh + 121, // 145: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant + 8, // 146: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 263, // 147: openshell.v1.ProviderCredentialRefresh.refresh_before:type_name -> google.protobuf.Duration + 263, // 148: openshell.v1.ProviderCredentialRefresh.max_lifetime:type_name -> google.protobuf.Duration + 123, // 149: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial + 124, // 150: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput + 8, // 151: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 259, // 152: openshell.v1.ProviderCredentialRefreshStatus.expiration_time:type_name -> google.protobuf.Timestamp + 259, // 153: openshell.v1.ProviderCredentialRefreshStatus.next_refresh_time:type_name -> google.protobuf.Timestamp + 259, // 154: openshell.v1.ProviderCredentialRefreshStatus.last_refresh_time:type_name -> google.protobuf.Timestamp + 13, // 155: openshell.v1.ProviderCredentialRefreshStatus.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction + 259, // 156: openshell.v1.ProviderCredentialRefreshStatus.last_error_time:type_name -> google.protobuf.Timestamp + 264, // 157: openshell.v1.GetProviderRefreshStatusRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 126, // 158: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 8, // 159: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 249, // 160: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + 259, // 161: openshell.v1.ConfigureProviderRefreshRequest.expiration_time:type_name -> google.protobuf.Timestamp + 264, // 162: openshell.v1.ConfigureProviderRefreshRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 126, // 163: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 264, // 164: openshell.v1.RotateProviderCredentialRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 126, // 165: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 264, // 166: openshell.v1.DeleteProviderRefreshRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 14, // 167: openshell.v1.DeleteProviderRefreshResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 9, // 168: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory + 122, // 169: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential + 267, // 170: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint + 268, // 171: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary + 127, // 172: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery + 250, // 173: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry + 136, // 174: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile + 136, // 175: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 117, // 176: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 118, // 177: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 136, // 178: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 117, // 179: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem + 118, // 180: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 136, // 181: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile + 117, // 182: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 118, // 183: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 14, // 184: openshell.v1.DeleteProviderResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 14, // 185: openshell.v1.DeleteProviderProfileResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 149, // 186: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding + 251, // 187: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + 252, // 188: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expiration_times:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpirationTimesEntry + 253, // 189: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + 254, // 190: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + 3, // 191: openshell.v1.GetSandboxProviderEnvironmentResponse.readiness_reason:type_name -> openshell.v1.ProviderReadinessReason + 263, // 192: openshell.v1.ExchangeProviderSubjectTokenResponse.expires_after:type_name -> google.protobuf.Duration + 261, // 193: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 269, // 194: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue + 155, // 195: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation + 255, // 196: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry + 264, // 197: openshell.v1.UpdateConfigRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 156, // 198: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule + 157, // 199: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint + 158, // 200: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule + 159, // 201: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules + 160, // 202: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules + 161, // 203: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary + 270, // 204: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 271, // 205: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule + 272, // 206: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule + 256, // 207: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry + 264, // 208: openshell.v1.GetSandboxPolicyStatusRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 169, // 209: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision + 264, // 210: openshell.v1.ListSandboxPoliciesRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 169, // 211: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision + 10, // 212: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus + 10, // 213: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus + 259, // 214: openshell.v1.SandboxPolicyRevision.created_time:type_name -> google.protobuf.Timestamp + 259, // 215: openshell.v1.SandboxPolicyRevision.loaded_time:type_name -> google.protobuf.Timestamp + 261, // 216: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 257, // 217: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry + 259, // 218: openshell.v1.GetSandboxLogsRequest.since_time:type_name -> google.protobuf.Timestamp + 264, // 219: openshell.v1.GetSandboxLogsRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 106, // 220: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine + 106, // 221: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine + 176, // 222: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello + 179, // 223: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat + 190, // 224: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult + 191, // 225: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose + 177, // 226: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted + 178, // 227: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected + 180, // 228: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat + 185, // 229: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen + 191, // 230: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose + 263, // 231: openshell.v1.SessionAccepted.heartbeat_interval:type_name -> google.protobuf.Duration + 186, // 232: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget + 187, // 233: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget + 188, // 234: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit + 259, // 235: openshell.v1.DenialSummary.first_seen_time:type_name -> google.protobuf.Timestamp + 259, // 236: openshell.v1.DenialSummary.last_seen_time:type_name -> google.protobuf.Timestamp + 192, // 237: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample + 194, // 238: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount + 270, // 239: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 259, // 240: openshell.v1.PolicyChunk.created_time:type_name -> google.protobuf.Timestamp + 259, // 241: openshell.v1.PolicyChunk.decided_time:type_name -> google.protobuf.Timestamp + 259, // 242: openshell.v1.PolicyChunk.first_seen_time:type_name -> google.protobuf.Timestamp + 259, // 243: openshell.v1.PolicyChunk.last_seen_time:type_name -> google.protobuf.Timestamp + 261, // 244: openshell.v1.PolicyChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 261, // 245: openshell.v1.PolicyChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 193, // 246: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary + 196, // 247: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk + 195, // 248: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary + 264, // 249: openshell.v1.GetDraftPolicyRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 196, // 250: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk + 259, // 251: openshell.v1.GetDraftPolicyResponse.last_analyzed_time:type_name -> google.protobuf.Timestamp + 264, // 252: openshell.v1.ApproveDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 253: openshell.v1.RejectDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 206, // 254: openshell.v1.ApproveAllDraftChunksRequest.approvals:type_name -> openshell.v1.DraftChunkApproval + 264, // 255: openshell.v1.ApproveAllDraftChunksRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 270, // 256: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 264, // 257: openshell.v1.EditDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 258: openshell.v1.UndoDraftChunkRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 259: openshell.v1.ClearDraftChunksRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 264, // 260: openshell.v1.GetDraftHistoryRequest.workspace_scope:type_name -> openshell.datamodel.v1.WorkspaceSelector + 259, // 261: openshell.v1.DraftHistoryEntry.event_time:type_name -> google.protobuf.Timestamp + 216, // 262: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry + 258, // 263: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry + 273, // 264: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 273, // 265: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 273, // 266: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace + 14, // 267: openshell.v1.DeleteWorkspaceResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 260, // 268: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 12, // 269: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole + 12, // 270: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole + 226, // 271: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember + 14, // 272: openshell.v1.RemoveWorkspaceMemberResponse.outcome:type_name -> openshell.v1.DeletionOutcome + 226, // 273: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember + 259, // 274: openshell.v1.ExtensionServiceCredential.expiration_time:type_name -> google.protobuf.Timestamp + 15, // 275: openshell.v1.EndpointObservation.result:type_name -> openshell.v1.EndpointResult + 234, // 276: openshell.v1.ReportEndpointStatusRequest.observations:type_name -> openshell.v1.EndpointObservation + 15, // 277: openshell.v1.EndpointStatus.last_result:type_name -> openshell.v1.EndpointResult + 259, // 278: openshell.v1.EndpointStatus.last_reported_time:type_name -> google.protobuf.Timestamp + 259, // 279: openshell.v1.UpdateProviderRequest.CredentialExpirationTimesEntry.value:type_name -> google.protobuf.Timestamp + 259, // 280: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpirationTimesEntry.value:type_name -> google.protobuf.Timestamp + 122, // 281: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential + 150, // 282: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding + 20, // 283: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest + 22, // 284: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest + 24, // 285: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest + 47, // 286: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest + 55, // 287: openshell.v1.OpenShell.BeginRootfsTarStaging:input_type -> openshell.v1.BeginRootfsTarStagingRequest + 57, // 288: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest + 58, // 289: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest + 48, // 290: openshell.v1.OpenShell.CreateSandboxTemplate:input_type -> openshell.v1.CreateSandboxTemplateRequest + 49, // 291: openshell.v1.OpenShell.GetSandboxTemplate:input_type -> openshell.v1.GetSandboxTemplateRequest + 50, // 292: openshell.v1.OpenShell.ListSandboxTemplates:input_type -> openshell.v1.ListSandboxTemplatesRequest + 51, // 293: openshell.v1.OpenShell.DeleteSandboxTemplate:input_type -> openshell.v1.DeleteSandboxTemplateRequest + 59, // 294: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest + 60, // 295: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest + 61, // 296: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest + 77, // 297: openshell.v1.OpenShell.GetSandboxProviderStatus:input_type -> openshell.v1.GetSandboxProviderStatusRequest + 62, // 298: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest + 63, // 299: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest + 64, // 300: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest + 82, // 301: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest + 84, // 302: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest + 85, // 303: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest + 86, // 304: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest + 88, // 305: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest + 92, // 306: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest + 94, // 307: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest + 100, // 308: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame + 101, // 309: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput + 108, // 310: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest + 109, // 311: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest + 110, // 312: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest + 115, // 313: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest + 116, // 314: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest + 139, // 315: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest + 141, // 316: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest + 143, // 317: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest + 111, // 318: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest + 128, // 319: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest + 130, // 320: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest + 132, // 321: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest + 134, // 322: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest + 112, // 323: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest + 146, // 324: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest + 274, // 325: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest + 275, // 326: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest + 154, // 327: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest + 163, // 328: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest + 165, // 329: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest + 167, // 330: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest + 235, // 331: openshell.v1.OpenShell.ReportEndpointStatus:input_type -> openshell.v1.ReportEndpointStatusRequest + 79, // 332: openshell.v1.OpenShell.ReportProviderReadiness:input_type -> openshell.v1.ReportProviderReadinessRequest + 148, // 333: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest + 152, // 334: openshell.v1.OpenShell.ExchangeProviderSubjectToken:input_type -> openshell.v1.ExchangeProviderSubjectTokenRequest + 170, // 335: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest + 171, // 336: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest + 174, // 337: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage + 181, // 338: openshell.v1.OpenShell.ReportMainProcessExit:input_type -> openshell.v1.ReportMainProcessExitRequest + 183, // 339: openshell.v1.OpenShell.FinalizeMainProcessExit:input_type -> openshell.v1.FinalizeMainProcessExitRequest + 189, // 340: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame + 104, // 341: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest + 198, // 342: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest + 200, // 343: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest + 202, // 344: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest + 204, // 345: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest + 207, // 346: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest + 209, // 347: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest + 211, // 348: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest + 213, // 349: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest + 215, // 350: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest + 16, // 351: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest + 18, // 352: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest + 218, // 353: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest + 220, // 354: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest + 222, // 355: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest + 224, // 356: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest + 227, // 357: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest + 229, // 358: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest + 231, // 359: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest + 21, // 360: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse + 23, // 361: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse + 25, // 362: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse + 65, // 363: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse + 56, // 364: openshell.v1.OpenShell.BeginRootfsTarStaging:output_type -> openshell.v1.BeginRootfsTarStagingResponse + 65, // 365: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse + 66, // 366: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse + 52, // 367: openshell.v1.OpenShell.CreateSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse + 52, // 368: openshell.v1.OpenShell.GetSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse + 53, // 369: openshell.v1.OpenShell.ListSandboxTemplates:output_type -> openshell.v1.ListSandboxTemplatesResponse + 54, // 370: openshell.v1.OpenShell.DeleteSandboxTemplate:output_type -> openshell.v1.DeleteSandboxTemplateResponse + 67, // 371: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse + 68, // 372: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse + 69, // 373: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse + 78, // 374: openshell.v1.OpenShell.GetSandboxProviderStatus:output_type -> openshell.v1.GetSandboxProviderStatusResponse + 81, // 375: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse + 65, // 376: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse + 65, // 377: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse + 83, // 378: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse + 91, // 379: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse + 91, // 380: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse + 87, // 381: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse + 89, // 382: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse + 93, // 383: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse + 98, // 384: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent + 100, // 385: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame + 98, // 386: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent + 113, // 387: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse + 113, // 388: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse + 114, // 389: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse + 138, // 390: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse + 137, // 391: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse + 140, // 392: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse + 142, // 393: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse + 144, // 394: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse + 113, // 395: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse + 129, // 396: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse + 131, // 397: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse + 133, // 398: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse + 135, // 399: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse + 145, // 400: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse + 147, // 401: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse + 276, // 402: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse + 277, // 403: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse + 162, // 404: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse + 164, // 405: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse + 166, // 406: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse + 168, // 407: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse + 236, // 408: openshell.v1.OpenShell.ReportEndpointStatus:output_type -> openshell.v1.ReportEndpointStatusResponse + 80, // 409: openshell.v1.OpenShell.ReportProviderReadiness:output_type -> openshell.v1.ReportProviderReadinessResponse + 151, // 410: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse + 153, // 411: openshell.v1.OpenShell.ExchangeProviderSubjectToken:output_type -> openshell.v1.ExchangeProviderSubjectTokenResponse + 173, // 412: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse + 172, // 413: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse + 175, // 414: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage + 182, // 415: openshell.v1.OpenShell.ReportMainProcessExit:output_type -> openshell.v1.ReportMainProcessExitResponse + 184, // 416: openshell.v1.OpenShell.FinalizeMainProcessExit:output_type -> openshell.v1.FinalizeMainProcessExitResponse + 189, // 417: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame + 105, // 418: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent + 199, // 419: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse + 201, // 420: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse + 203, // 421: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse + 205, // 422: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse + 208, // 423: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse + 210, // 424: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse + 212, // 425: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse + 214, // 426: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse + 217, // 427: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse + 17, // 428: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse + 19, // 429: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse + 219, // 430: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse + 221, // 431: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse + 223, // 432: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse + 225, // 433: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse + 228, // 434: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse + 230, // 435: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse + 232, // 436: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse + 360, // [360:437] is the sub-list for method output_type + 283, // [283:360] is the sub-list for method input_type + 283, // [283:283] is the sub-list for extension type_name + 283, // [283:283] is the sub-list for extension extendee + 0, // [0:283] is the sub-list for field type_name } func init() { file_openshell_proto_init() } @@ -16876,32 +18874,37 @@ func file_openshell_proto_init() { file_openshell_proto_msgTypes[19].OneofWrappers = []any{} file_openshell_proto_msgTypes[20].OneofWrappers = []any{} file_openshell_proto_msgTypes[28].OneofWrappers = []any{} - file_openshell_proto_msgTypes[71].OneofWrappers = []any{ + file_openshell_proto_msgTypes[55].OneofWrappers = []any{ + (*ConfigSnapshotRevision_SandboxConfig)(nil), + (*ConfigSnapshotRevision_ProviderEnvironment)(nil), + (*ConfigSnapshotRevision_ProviderTarget)(nil), + } + file_openshell_proto_msgTypes[82].OneofWrappers = []any{ (*ExecSandboxEvent_Stdout)(nil), (*ExecSandboxEvent_Stderr)(nil), (*ExecSandboxEvent_Exit)(nil), } - file_openshell_proto_msgTypes[72].OneofWrappers = []any{ + file_openshell_proto_msgTypes[83].OneofWrappers = []any{ (*TcpForwardInit_Ssh)(nil), (*TcpForwardInit_Tcp)(nil), } - file_openshell_proto_msgTypes[73].OneofWrappers = []any{ + file_openshell_proto_msgTypes[84].OneofWrappers = []any{ (*TcpForwardFrame_Init)(nil), (*TcpForwardFrame_Data)(nil), } - file_openshell_proto_msgTypes[74].OneofWrappers = []any{ + file_openshell_proto_msgTypes[85].OneofWrappers = []any{ (*ExecSandboxInput_Start)(nil), (*ExecSandboxInput_Stdin)(nil), (*ExecSandboxInput_Resize)(nil), } - file_openshell_proto_msgTypes[78].OneofWrappers = []any{ + file_openshell_proto_msgTypes[89].OneofWrappers = []any{ (*SandboxStreamEvent_Sandbox)(nil), (*SandboxStreamEvent_Log)(nil), (*SandboxStreamEvent_Event)(nil), (*SandboxStreamEvent_Warning)(nil), (*SandboxStreamEvent_DraftPolicyUpdate)(nil), } - file_openshell_proto_msgTypes[128].OneofWrappers = []any{ + file_openshell_proto_msgTypes[139].OneofWrappers = []any{ (*PolicyMergeOperation_AddRule)(nil), (*PolicyMergeOperation_RemoveEndpoint)(nil), (*PolicyMergeOperation_RemoveRule)(nil), @@ -16909,24 +18912,24 @@ func file_openshell_proto_init() { (*PolicyMergeOperation_AddAllowRules)(nil), (*PolicyMergeOperation_RemoveBinary)(nil), } - file_openshell_proto_msgTypes[147].OneofWrappers = []any{ + file_openshell_proto_msgTypes[158].OneofWrappers = []any{ (*SupervisorMessage_Hello)(nil), (*SupervisorMessage_Heartbeat)(nil), (*SupervisorMessage_RelayOpenResult)(nil), (*SupervisorMessage_RelayClose)(nil), } - file_openshell_proto_msgTypes[148].OneofWrappers = []any{ + file_openshell_proto_msgTypes[159].OneofWrappers = []any{ (*GatewayMessage_SessionAccepted)(nil), (*GatewayMessage_SessionRejected)(nil), (*GatewayMessage_Heartbeat)(nil), (*GatewayMessage_RelayOpen)(nil), (*GatewayMessage_RelayClose)(nil), } - file_openshell_proto_msgTypes[158].OneofWrappers = []any{ + file_openshell_proto_msgTypes[169].OneofWrappers = []any{ (*RelayOpen_Ssh)(nil), (*RelayOpen_Tcp)(nil), } - file_openshell_proto_msgTypes[162].OneofWrappers = []any{ + file_openshell_proto_msgTypes[173].OneofWrappers = []any{ (*RelayFrame_Init)(nil), (*RelayFrame_Data)(nil), } @@ -16935,8 +18938,8 @@ func file_openshell_proto_init() { File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_openshell_proto_rawDesc), len(file_openshell_proto_rawDesc)), - NumEnums: 10, - NumMessages: 232, + NumEnums: 16, + NumMessages: 243, NumExtensions: 0, NumServices: 1, }, diff --git a/sdk/go/proto/openshellv1/openshell_grpc.pb.go b/sdk/go/proto/openshellv1/openshell_grpc.pb.go index 42587e10ef..fab991628c 100644 --- a/sdk/go/proto/openshellv1/openshell_grpc.pb.go +++ b/sdk/go/proto/openshellv1/openshell_grpc.pb.go @@ -37,6 +37,7 @@ const ( OpenShell_ListSandboxProviders_FullMethodName = "/openshell.v1.OpenShell/ListSandboxProviders" OpenShell_AttachSandboxProvider_FullMethodName = "/openshell.v1.OpenShell/AttachSandboxProvider" OpenShell_DetachSandboxProvider_FullMethodName = "/openshell.v1.OpenShell/DetachSandboxProvider" + OpenShell_GetSandboxProviderStatus_FullMethodName = "/openshell.v1.OpenShell/GetSandboxProviderStatus" OpenShell_DeleteSandbox_FullMethodName = "/openshell.v1.OpenShell/DeleteSandbox" OpenShell_StopSandbox_FullMethodName = "/openshell.v1.OpenShell/StopSandbox" OpenShell_StartSandbox_FullMethodName = "/openshell.v1.OpenShell/StartSandbox" @@ -71,6 +72,7 @@ const ( OpenShell_ListSandboxPolicies_FullMethodName = "/openshell.v1.OpenShell/ListSandboxPolicies" OpenShell_ReportPolicyStatus_FullMethodName = "/openshell.v1.OpenShell/ReportPolicyStatus" OpenShell_ReportEndpointStatus_FullMethodName = "/openshell.v1.OpenShell/ReportEndpointStatus" + OpenShell_ReportProviderReadiness_FullMethodName = "/openshell.v1.OpenShell/ReportProviderReadiness" OpenShell_GetSandboxProviderEnvironment_FullMethodName = "/openshell.v1.OpenShell/GetSandboxProviderEnvironment" OpenShell_ExchangeProviderSubjectToken_FullMethodName = "/openshell.v1.OpenShell/ExchangeProviderSubjectToken" OpenShell_GetSandboxLogs_FullMethodName = "/openshell.v1.OpenShell/GetSandboxLogs" @@ -148,6 +150,8 @@ type OpenShellClient interface { AttachSandboxProvider(ctx context.Context, in *AttachSandboxProviderRequest, opts ...grpc.CallOption) (*AttachSandboxProviderResponse, error) // Detach a provider record from an existing sandbox. DetachSandboxProvider(ctx context.Context, in *DetachSandboxProviderRequest, opts ...grpc.CallOption) (*DetachSandboxProviderResponse, error) + // Inspect the installed authority for one sandbox provider mutation. + GetSandboxProviderStatus(ctx context.Context, in *GetSandboxProviderStatusRequest, opts ...grpc.CallOption) (*GetSandboxProviderStatusResponse, error) // Delete a sandbox by name. DeleteSandbox(ctx context.Context, in *DeleteSandboxRequest, opts ...grpc.CallOption) (*DeleteSandboxResponse, error) // Stop a sandbox while retaining its persistent state. @@ -224,6 +228,9 @@ type OpenShellClient interface { ReportPolicyStatus(ctx context.Context, in *ReportPolicyStatusRequest, opts ...grpc.CallOption) (*ReportPolicyStatusResponse, error) // Replace the gateway's observed tool server endpoint status for one sandbox. ReportEndpointStatus(ctx context.Context, in *ReportEndpointStatusRequest, opts ...grpc.CallOption) (*ReportEndpointStatusResponse, error) + // Report installed provider state for the current ConnectSupervisor session. + // Replacing or losing that session invalidates its observations. + ReportProviderReadiness(ctx context.Context, in *ReportProviderReadinessRequest, opts ...grpc.CallOption) (*ReportProviderReadinessResponse, error) // Get provider environment for a sandbox (called by sandbox supervisor at startup). GetSandboxProviderEnvironment(ctx context.Context, in *GetSandboxProviderEnvironmentRequest, opts ...grpc.CallOption) (*GetSandboxProviderEnvironmentResponse, error) // Exchange a stored provider subject token for an intermediate token scoped @@ -459,6 +466,16 @@ func (c *openShellClient) DetachSandboxProvider(ctx context.Context, in *DetachS return out, nil } +func (c *openShellClient) GetSandboxProviderStatus(ctx context.Context, in *GetSandboxProviderStatusRequest, opts ...grpc.CallOption) (*GetSandboxProviderStatusResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetSandboxProviderStatusResponse) + err := c.cc.Invoke(ctx, OpenShell_GetSandboxProviderStatus_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *openShellClient) DeleteSandbox(ctx context.Context, in *DeleteSandboxRequest, opts ...grpc.CallOption) (*DeleteSandboxResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(DeleteSandboxResponse) @@ -814,6 +831,16 @@ func (c *openShellClient) ReportEndpointStatus(ctx context.Context, in *ReportEn return out, nil } +func (c *openShellClient) ReportProviderReadiness(ctx context.Context, in *ReportProviderReadinessRequest, opts ...grpc.CallOption) (*ReportProviderReadinessResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ReportProviderReadinessResponse) + err := c.cc.Invoke(ctx, OpenShell_ReportProviderReadiness_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *openShellClient) GetSandboxProviderEnvironment(ctx context.Context, in *GetSandboxProviderEnvironmentRequest, opts ...grpc.CallOption) (*GetSandboxProviderEnvironmentResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(GetSandboxProviderEnvironmentResponse) @@ -1150,6 +1177,8 @@ type OpenShellServer interface { AttachSandboxProvider(context.Context, *AttachSandboxProviderRequest) (*AttachSandboxProviderResponse, error) // Detach a provider record from an existing sandbox. DetachSandboxProvider(context.Context, *DetachSandboxProviderRequest) (*DetachSandboxProviderResponse, error) + // Inspect the installed authority for one sandbox provider mutation. + GetSandboxProviderStatus(context.Context, *GetSandboxProviderStatusRequest) (*GetSandboxProviderStatusResponse, error) // Delete a sandbox by name. DeleteSandbox(context.Context, *DeleteSandboxRequest) (*DeleteSandboxResponse, error) // Stop a sandbox while retaining its persistent state. @@ -1226,6 +1255,9 @@ type OpenShellServer interface { ReportPolicyStatus(context.Context, *ReportPolicyStatusRequest) (*ReportPolicyStatusResponse, error) // Replace the gateway's observed tool server endpoint status for one sandbox. ReportEndpointStatus(context.Context, *ReportEndpointStatusRequest) (*ReportEndpointStatusResponse, error) + // Report installed provider state for the current ConnectSupervisor session. + // Replacing or losing that session invalidates its observations. + ReportProviderReadiness(context.Context, *ReportProviderReadinessRequest) (*ReportProviderReadinessResponse, error) // Get provider environment for a sandbox (called by sandbox supervisor at startup). GetSandboxProviderEnvironment(context.Context, *GetSandboxProviderEnvironmentRequest) (*GetSandboxProviderEnvironmentResponse, error) // Exchange a stored provider subject token for an intermediate token scoped @@ -1363,6 +1395,9 @@ func (UnimplementedOpenShellServer) AttachSandboxProvider(context.Context, *Atta func (UnimplementedOpenShellServer) DetachSandboxProvider(context.Context, *DetachSandboxProviderRequest) (*DetachSandboxProviderResponse, error) { return nil, status.Error(codes.Unimplemented, "method DetachSandboxProvider not implemented") } +func (UnimplementedOpenShellServer) GetSandboxProviderStatus(context.Context, *GetSandboxProviderStatusRequest) (*GetSandboxProviderStatusResponse, error) { + return nil, status.Error(codes.Unimplemented, "method GetSandboxProviderStatus not implemented") +} func (UnimplementedOpenShellServer) DeleteSandbox(context.Context, *DeleteSandboxRequest) (*DeleteSandboxResponse, error) { return nil, status.Error(codes.Unimplemented, "method DeleteSandbox not implemented") } @@ -1465,6 +1500,9 @@ func (UnimplementedOpenShellServer) ReportPolicyStatus(context.Context, *ReportP func (UnimplementedOpenShellServer) ReportEndpointStatus(context.Context, *ReportEndpointStatusRequest) (*ReportEndpointStatusResponse, error) { return nil, status.Error(codes.Unimplemented, "method ReportEndpointStatus not implemented") } +func (UnimplementedOpenShellServer) ReportProviderReadiness(context.Context, *ReportProviderReadinessRequest) (*ReportProviderReadinessResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ReportProviderReadiness not implemented") +} func (UnimplementedOpenShellServer) GetSandboxProviderEnvironment(context.Context, *GetSandboxProviderEnvironmentRequest) (*GetSandboxProviderEnvironmentResponse, error) { return nil, status.Error(codes.Unimplemented, "method GetSandboxProviderEnvironment not implemented") } @@ -1819,6 +1857,24 @@ func _OpenShell_DetachSandboxProvider_Handler(srv interface{}, ctx context.Conte return interceptor(ctx, in, info, handler) } +func _OpenShell_GetSandboxProviderStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetSandboxProviderStatusRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OpenShellServer).GetSandboxProviderStatus(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OpenShell_GetSandboxProviderStatus_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OpenShellServer).GetSandboxProviderStatus(ctx, req.(*GetSandboxProviderStatusRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _OpenShell_DeleteSandbox_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeleteSandboxRequest) if err := dec(in); err != nil { @@ -2402,6 +2458,24 @@ func _OpenShell_ReportEndpointStatus_Handler(srv interface{}, ctx context.Contex return interceptor(ctx, in, info, handler) } +func _OpenShell_ReportProviderReadiness_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ReportProviderReadinessRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OpenShellServer).ReportProviderReadiness(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OpenShell_ReportProviderReadiness_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OpenShellServer).ReportProviderReadiness(ctx, req.(*ReportProviderReadinessRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _OpenShell_GetSandboxProviderEnvironment_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetSandboxProviderEnvironmentRequest) if err := dec(in); err != nil { @@ -2911,6 +2985,10 @@ var OpenShell_ServiceDesc = grpc.ServiceDesc{ MethodName: "DetachSandboxProvider", Handler: _OpenShell_DetachSandboxProvider_Handler, }, + { + MethodName: "GetSandboxProviderStatus", + Handler: _OpenShell_GetSandboxProviderStatus_Handler, + }, { MethodName: "DeleteSandbox", Handler: _OpenShell_DeleteSandbox_Handler, @@ -3035,6 +3113,10 @@ var OpenShell_ServiceDesc = grpc.ServiceDesc{ MethodName: "ReportEndpointStatus", Handler: _OpenShell_ReportEndpointStatus_Handler, }, + { + MethodName: "ReportProviderReadiness", + Handler: _OpenShell_ReportProviderReadiness_Handler, + }, { MethodName: "GetSandboxProviderEnvironment", Handler: _OpenShell_GetSandboxProviderEnvironment_Handler, diff --git a/sdk/go/proto/sandboxv1/sandbox.pb.go b/sdk/go/proto/sandboxv1/sandbox.pb.go index 6cbbd5fbda..c4a7d5f417 100644 --- a/sdk/go/proto/sandboxv1/sandbox.pb.go +++ b/sdk/go/proto/sandboxv1/sandbox.pb.go @@ -1826,8 +1826,11 @@ type GetSandboxConfigResponse struct { // False also covers older gateways that do not advertise this capability; // supervisors preserve their legacy unauthenticated connection behavior. ExtensionAuthenticationEnabled bool `protobuf:"varint,12,opt,name=extension_authentication_enabled,json=extensionAuthenticationEnabled,proto3" json:"extension_authentication_enabled,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Gateway-owned attachment identity captured with this desired configuration. + // Compare for equality; reattachment invalidates previous installation evidence. + ProviderAttachmentEpoch string `protobuf:"bytes,14,opt,name=provider_attachment_epoch,json=providerAttachmentEpoch,proto3" json:"provider_attachment_epoch,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetSandboxConfigResponse) Reset() { @@ -1944,6 +1947,13 @@ func (x *GetSandboxConfigResponse) GetExtensionAuthenticationEnabled() bool { return false } +func (x *GetSandboxConfigResponse) GetProviderAttachmentEpoch() string { + if x != nil { + return x.ProviderAttachmentEpoch + } + return "" +} + // Connection details for one operator-registered supervisor middleware service. // V1 supports plaintext and server-authenticated TLS gRPC. type SupervisorMiddlewareService struct { @@ -2207,7 +2217,7 @@ const file_sandbox_proto_rawDesc = "" + "\x05value\"\x86\x01\n" + "\x10EffectiveSetting\x128\n" + "\x05value\x18\x01 \x01(\v2\".openshell.sandbox.v1.SettingValueR\x05value\x128\n" + - "\x05scope\x18\x02 \x01(\x0e2\".openshell.sandbox.v1.SettingScopeR\x05scope\"\xd1\x06\n" + + "\x05scope\x18\x02 \x01(\x0e2\".openshell.sandbox.v1.SettingScopeR\x05scope\"\x8d\a\n" + "\x18GetSandboxConfigResponse\x12;\n" + "\x06policy\x18\x01 \x01(\v2#.openshell.sandbox.v1.SandboxPolicyR\x06policy\x12\x18\n" + "\aversion\x18\x02 \x01(\rR\aversion\x12\x1f\n" + @@ -2222,7 +2232,8 @@ const file_sandbox_proto_rawDesc = "" + "\tworkspace\x18\n" + " \x01(\tR\tworkspace\x12C\n" + "\x1epolicy_validation_failure_mode\x18\v \x01(\tR\x1bpolicyValidationFailureMode\x12H\n" + - " extension_authentication_enabled\x18\f \x01(\bR\x1eextensionAuthenticationEnabled\x1ac\n" + + " extension_authentication_enabled\x18\f \x01(\bR\x1eextensionAuthenticationEnabled\x12:\n" + + "\x19provider_attachment_epoch\x18\x0e \x01(\tR\x17providerAttachmentEpoch\x1ac\n" + "\rSettingsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12<\n" + "\x05value\x18\x02 \x01(\v2&.openshell.sandbox.v1.EffectiveSettingR\x05value:\x028\x01\"\xd2\x02\n" + diff --git a/skills/debug-inference/SKILL.md b/skills/debug-inference/SKILL.md index 1ba416ce3e..6c9580a9f6 100644 --- a/skills/debug-inference/SKILL.md +++ b/skills/debug-inference/SKILL.md @@ -62,21 +62,23 @@ binding error. ```bash openshell sandbox provider list -openshell sandbox provider attach +openshell sandbox provider attach --wait --timeout 30 ``` -Launch a new process after attaching a provider so it inherits newly available -credential placeholders: +Save the change's `receipt_id` and use `openshell sandbox provider status --receipt --wait --timeout 30` to check when it takes effect. Success confirms that the sandbox applied the credentials, policy, and environment for new processes. If the result is pending, failed, withheld, or superseded, inspect its reason before launching the client. + +Launch the client after the attachment wait succeeds so it receives the updated environment: ```bash -openshell sandbox exec -- env +openshell sandbox exec -- ``` -Do not print or copy credential values into diagnostic output. Detaching a -provider revokes its policy and credential access: +After updating an ordinary static provider, wait for that change and launch a new client. An existing process keeps its revision-scoped reference; readiness does not make the old reference resolve the replacement value. Diagnose managed-refresh credentials according to their own lifecycle. + +Keep credentials and issued references out of diagnostic output. Acknowledged detach revokes future credential resolution and removes the reference from future process environments. Requests already forwarded may still finish: ```bash -openshell sandbox provider detach +openshell sandbox provider detach --wait --timeout 30 ``` ### 4. Verify Native Client Configuration diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index a6b54ec677..c0a30f14a7 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -150,18 +150,9 @@ journalctl -u openshell-gateway --no-pager --lines=200 The gateway calls each interceptor's `Describe` RPC and validates its manifest at startup. Check for unreachable endpoints, invalid RPC/phase bindings, strict `allowlist` or `exact` mismatches, and `post_commit` bindings that resolve to `fail_closed`. If gateway JWT signing is enabled, authenticated network interceptors require HTTPS and a valid bearer token; check the private CA path, endpoint hostname, expected audience, issuer, `kid`, and interceptor logs for token rejection. `allow_insecure_transport = true` explicitly preserves unauthenticated plaintext behavior. If `provider_profile_sources` names an interceptor, that interceptor must advertise provider-profile capability and return a valid, duplicate-free catalog. A selected interceptor-only source is authoritative; include `builtin` or `user` sources explicitly when composition is intended. -For operator-run supervisor middleware, inspect `[[openshell.supervisor.middleware]]`, service reachability, and both gateway and supervisor logs: - -```bash -rg -n 'supervisor|middleware|grpc_endpoint|tls_ca_cert_path|audience|allow_insecure_transport|max_payload_bytes|timeout|gateway_jwt' /etc/openshell/gateway.toml -journalctl -u --no-pager --lines=200 -journalctl -u openshell-gateway --no-pager --lines=200 -openshell logs --tail --source sandbox -``` - -The middleware service must start before the gateway and be reachable from both the gateway and sandbox supervisors. Gateway startup fails if `Describe` is unavailable, a manifest exposes duplicate operation/phase bindings, the registration claims the reserved `openshell/` namespace, or payload and timeout limits are invalid. Supported V1 bindings are `HTTP_REQUEST/PRE_CREDENTIALS` and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. When gateway JWT signing is disabled, supervisors preserve the legacy unauthenticated connector and do not request extension credentials. When signing is enabled, credential acquisition and verification failures are fail closed: check HTTPS trust and hostname validation, audience and issuer agreement, the token `kid`, gateway `RefreshSandboxToken` errors, and middleware logs. Changing a registration requires a gateway restart. A policy update can also fail before persistence if the selected implementation rejects its `network_middlewares` config. - -At request time, distinguish attachment, binding selection, coverage, denial, and failure. A host-matched HTTP-only attachment can inspect the upgrade GET but does not join the WebSocket chain; the connection proceeds under either `on_error` mode and emits `binding_not_selected` coverage. A selected WebSocket stage receives text messages only. Binary messages pass under both modes, emit `unsupported_message_type` coverage, and consume a session sequence without an RPC. An explicit `middleware_denied` result is always enforced. WebSocket preflight returns `INSPECT`, voluntary `SKIP`, or authoritative `DENY`; `DENY` rejects the upgrade before upstream contact under both `on_error` modes. A selected-stage failure follows the policy-local `on_error`: `fail_closed` blocks the HTTP request or closes the WebSocket, while `fail_open` bypasses only that stage and emits a detection finding. A fail-open per-message capacity failure bypasses that message without disabling the stage. A timeout, transport failure, stream closure, missing or invalid response, duplicate or regressed sequence, or other failure that makes an established WebSocket stream unreliable disables that stage for later messages on the connection and emits `openshell.middleware.websocket_stage_disabled`. Confirm preflight, session-start, and session-end in service logs. OpenShell best-effort sends at most one session-end to each still-writable opened stage, including a preflight that terminates before session start; distinguish `MIDDLEWARE_DENIAL` from `MIDDLEWARE_FAILURE`. WebSocket message sequences are allocated session-wide; each stage receives a strictly increasing subset, so gaps are valid when binary messages or other units are not delivered to that stage. Zero, duplicate, or regressed sequences are protocol errors. If a running supervisor cannot install a new registry, it preserves its last-known-good generation and emits a configuration failure event. +If the deployment uses supervisor middleware, follow the +[supervisor middleware troubleshooting reference](references/supervisor-middleware.md) +for startup, authentication, policy validation, and HTTP or WebSocket failures. For network policy validation failures, first distinguish a gateway mutation rejection from a supervisor runtime rejection. Direct policy updates, @@ -240,6 +231,7 @@ Common findings: - Sandbox fails before readiness with an OCI workspace validation error: inspect the image's `WorkingDir` using the immutable image ID reported by the gateway. Empty, `/`, and explicit `/sandbox` use the managed `/sandbox` compatibility workspace. Any other workdir must be an absolute normalized directory with no symlink components; the final policy UID, primary GID, and supplementary groups must pass the kernel's effective traverse/write checks, including POSIX ACL and LSM decisions. OpenShell does not create, chown, or chmod a non-default image workdir. - Docker also rejects an image `VOLUME` that covers the workdir or one of its parents because the runtime would mask the immutable path before validation. Move the `VOLUME` below the workspace or remove the declaration. - A workdir rejected as a special filesystem or OpenShell control-path collision cannot be made valid with permissions. Move the image workdir away from kernel-backed mounts and the concrete supervisor, TLS, token, runtime, and socket paths named in the error. +- Local Docker gateway setup cannot copy `openshell-sandbox` after exporting a supervisor image: the sandbox runtime and supervisor are separate artifacts. The runtime image must provide `/openshell-sandbox`; the supervisor image provides `/openshell-supervisor`. - Docker driver cannot initialize because it cannot find `openshell-sandbox`: verify the sibling binary next to `openshell-gateway`, or that the configured `sandbox_runtime_image` contains `/openshell-sandbox`. - Sandbox never registers: check gateway logs and supervisor callback endpoint. - Calls to an external tool server fail while the sandbox is Ready: inspect `Tool server connections` in `openshell sandbox get `. For configured MCP-over-HTTP endpoints, JSON output exposes each address together with `last_result` and `last_reported_at` in `endpoint_statuses`. Select the endpoint by host, path, and ports, then check the reported failure boundary. `last_reported_at` records gateway acceptance time and can advance when retained evidence is accepted after a reset. Results do not expire or prove current availability; `HttpResponseReceived` can still contain a tool error. If several paths share a host and port, a failure before the path is known remains in logs. Verify the actual operation when current tool availability matters. @@ -654,6 +646,23 @@ a required unprivileged seccomp, task-memory, or Landlock operation. Do not add capabilities, gateway egress, or credentials to the workload Pod as a workaround. +If a Sandbox remains in the `rolling-back` bootstrap phase, verify that the +gateway ServiceAccount can create, list, and delete Secrets in the sandbox +namespace. Recovery lists generation Secrets by sandbox and component labels +even when none remain, then deletes stale entries with UID preconditions before +clearing the rollback annotations: + +```bash +for verb in create list delete; do + kubectl auth can-i "$verb" secrets \ + --namespace \ + --as system:serviceaccount:openshell:openshell +done +``` + +Any `no` result can strand recovery before workload Pod creation. Upgrade the +OpenShell chart rather than treating missing workload Pods as Pod failures. + #### Corporate upstream proxy When the deployment routes sandbox egress through a corporate HTTP forward @@ -766,17 +775,10 @@ credential failures. | Edge or OIDC gateway returns `Unauthenticated` | Stored login expired, audience/scopes mismatch, or gateway auth configuration changed | `openshell gateway info`, `openshell gateway login `, gateway auth logs | | Gateway exits during OIDC initialization | Issuer is not HTTPS, discovery redirected, metadata used a non-JSON media type or exceeded its size limit, or `jwks_uri` uses an untrusted origin | Use an HTTPS issuer; mount a private CA with `server.oidc.caConfigMapName`; keep JWKS on the issuer origin or explicitly add its HTTPS origin to `server.oidc.jwksAllowedOrigins`. Numeric-loopback HTTP is development-only and also requires `server.oidc.dangerouslyAllowInsecureHttp=true` | | Gateway fails before serving health after enabling an interceptor | Interceptor endpoint unavailable or manifest/binding validation failed | Gateway and interceptor logs; interceptor socket; `binding_policy`, phases, and failure policy | -| Authenticated interceptor or middleware rejects gateway calls | Private CA or hostname mismatch, expected audience or issuer mismatch, stale/unknown `kid`, or malformed extension token | `tls_ca_cert_path`, registration `audience`, service verifier config and logs; fetch well-known metadata only through the already-trusted gateway TLS endpoint | +| Authenticated interceptor rejects gateway calls | Private CA or hostname mismatch, expected audience or issuer mismatch, stale/unknown `kid`, or malformed extension token | `tls_ca_cert_path`, registration `audience`, service verifier config and logs; fetch well-known metadata only through the already-trusted gateway TLS endpoint | | Provider profiles disappear after enabling an interceptor catalog | `provider_profile_sources` selected only an authoritative interceptor or returned invalid/duplicate IDs | Inspect source list and interceptor `Describe`/catalog logs; include `builtin` and `user` when intended | -| Gateway fails after registering supervisor middleware | Service unavailable, invalid manifest, duplicate binding, reserved name, or invalid payload/timeout limit | Middleware service and gateway logs; `[[openshell.supervisor.middleware]]`; `Describe` response | -| Policy update rejects `network_middlewares` | Unknown middleware name, implementation-owned config invalid, duplicate order, broad/invalid host selector, or fail-closed coverage of `tls: skip` | Policy error, gateway logs, middleware `ValidateConfig`, selector and order fields | | Policy mutation returns `FAILED_PRECONDITION` for endpoint ambiguity | Equally specific effective endpoint selectors disagree on connection or request-processing metadata | CLI error, base and provider-composed policy, affected profile attachments; confirm no new revision was stored | | Supervisor enters policy quarantine | A runtime candidate failed validation while `policy_validation_failure_mode = "fail_closed"` | Sandbox OCSF config/finding events, validation rationale, active generation, `previous_policy_active` | -| HTTP request returns `middleware_failed` or `middleware_denied`, or WebSocket closes with `1008` | Selected stage failed or explicitly denied admitted traffic | Sandbox OCSF logs; policy-local middleware config; service availability; binding operation; `on_error` | -| WebSocket upgrades but a host-matched middleware receives no preflight or message RPC | The implementation did not advertise `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` | `WEBSOCKET_MIDDLEWARE_COVERAGE state=binding_not_selected`; service `Describe`; the upgrade GET may still have used its HTTP binding | -| Binary WebSocket message passes without a middleware RPC | Binary is unsupported by the V1 text-message binding under both `on_error` modes | `WEBSOCKET_MIDDLEWARE_COVERAGE state=unsupported_message_type`; the next text RPC may have a valid sequence gap | -| WebSocket messages stop reaching middleware after one failure | A fail-open stage stream was disabled for the rest of the connection | `openshell.middleware.websocket_stage_disabled`; middleware timeout/stream/protocol logs. A per-message capacity bypass alone leaves the stage active. Reconnect to create a fresh stream after a genuine stream failure | -| Supervisor repeatedly fails to install middleware after enabling gateway JWT signing | Extension credential minting, distribution, or authenticated service connection failed; last-known-good registry remains active | Gateway `RefreshSandboxToken` logs, sandbox configuration events, service token-verification logs, registration TLS/audience settings | | Custom compute driver is unavailable | Driver process/socket missing, inaccessible, or selected name does not match its endpoint/config key | Socket ownership/mode, driver service logs, gateway `GetCapabilities` logs | | Sandbox remains `Stopping` or `Starting` | Driver stop/start failed, retained resource is missing, or a fresh supervisor has not connected | Gateway and driver logs; `docker inspect`, `podman inspect`, Agent Sandbox status/PVC, or VM state marker and launcher process | | Image pull failure | Gateway or sandbox image cannot be pulled | Runtime events and image pull credentials | diff --git a/skills/debug-openshell-cluster/references/supervisor-middleware.md b/skills/debug-openshell-cluster/references/supervisor-middleware.md new file mode 100644 index 0000000000..a1d7524662 --- /dev/null +++ b/skills/debug-openshell-cluster/references/supervisor-middleware.md @@ -0,0 +1,53 @@ +# Supervisor middleware troubleshooting + +Use this reference when the deployment registers supervisor middleware or a +sandbox policy attaches it through `network_middlewares`. Start with gateway +reachability and compute-platform checks in the [main skill](../SKILL.md). +Use installed CLI help for command syntax and the published +[gateway configuration reference](https://docs.nvidia.com/openshell/latest/reference/gateway-config.md) +for registration settings. + +## Collect diagnostics + +For operator-run supervisor middleware, inspect `[[openshell.supervisor.middleware]]`, service reachability, and both gateway and supervisor logs: + +```shell +rg -n 'supervisor|middleware|grpc_endpoint|tls_ca_cert_path|audience|allow_insecure_transport|max_payload_bytes|timeout|gateway_jwt' /etc/openshell/gateway.toml +journalctl -u --no-pager --lines=200 +journalctl -u openshell-gateway --no-pager --lines=200 +openshell logs --tail --source sandbox +``` + +## Startup and authentication + +The middleware service must start before the gateway and be reachable from both the gateway and sandbox supervisors. Gateway startup fails if `Describe` is unavailable, a manifest exposes duplicate operation/phase bindings, the registration claims the reserved `openshell/` namespace, or payload and timeout limits are invalid. Supported V1 bindings are `HTTP_REQUEST/PRE_CREDENTIALS`, `HTTP_RESPONSE/PRE_RETURN`, and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. + +When gateway JWT signing is disabled, supervisors preserve the legacy unauthenticated connector and do not request extension credentials. When signing is enabled, credential acquisition and verification failures are fail closed: check HTTPS trust and hostname validation, audience and issuer agreement, the token `kid`, gateway `RefreshSandboxToken` errors, and middleware logs. Changing a registration requires a gateway restart. A policy update can also fail before persistence if the selected implementation rejects its `network_middlewares` config. + +## HTTP response failures + +For response failures, distinguish a deliberate `middleware_denied` decision from `response_delivery_failed`. Before response commitment, they produce canonical 403 and 502 responses respectively. After commitment, OpenShell aborts without adding an error body, final chunk, or trailer. A whole-body accumulation timeout is one fixed, non-resetting 120-second wall-clock deadline shared across response reads and whole-body barriers; inspect the active stage's `on_error` and `whole_body_accumulation_timeout` diagnostics. Header-only stages preserve upstream body framing. Body-processing stages normalize framing and send a trailer exchange, including an empty trailer set, after the final body result. + +## Request and WebSocket failures + +At request time, distinguish attachment, binding selection, coverage, denial, and failure. A host-matched HTTP-only attachment can inspect the upgrade GET but does not join the WebSocket chain; the connection proceeds under either `on_error` mode and emits `binding_not_selected` coverage. A selected WebSocket stage receives text messages only. Binary messages pass under both modes, emit `unsupported_message_type` coverage, and consume a session sequence without an RPC. + +An explicit `middleware_denied` result is always enforced. WebSocket preflight returns `INSPECT`, voluntary `SKIP`, or authoritative `DENY`; `DENY` rejects the upgrade before upstream contact under both `on_error` modes. A selected-stage failure follows the policy-local `on_error`: `fail_closed` blocks the HTTP request or closes the WebSocket, while `fail_open` bypasses only that stage and emits a detection finding. A fail-open per-message capacity failure bypasses that message without disabling the stage. A timeout, transport failure, stream closure, missing or invalid response, duplicate or regressed sequence, or other failure that makes an established WebSocket stream unreliable disables that stage for later messages on the connection and emits `openshell.middleware.websocket_stage_disabled`. + +Confirm preflight, session-start, and session-end in service logs. OpenShell best-effort sends at most one session-end to each still-writable opened stage, including a preflight that terminates before session start; distinguish `MIDDLEWARE_DENIAL` from `MIDDLEWARE_FAILURE`. + +WebSocket message sequences are allocated session-wide; each stage receives a strictly increasing subset, so gaps are valid when binary messages or other units are not delivered to that stage. Zero, duplicate, or regressed sequences are protocol errors. If a running supervisor cannot install a new registry, it preserves its last-known-good generation and emits a configuration failure event. + +## Common failure patterns + +| Symptom | Likely cause | Check | +|---|---|---| +| Authenticated middleware rejects gateway calls | Private CA or hostname mismatch, expected audience or issuer mismatch, stale/unknown `kid`, or malformed extension token | `tls_ca_cert_path`, registration `audience`, service verifier config and logs; fetch well-known metadata only through the already-trusted gateway TLS endpoint | +| Gateway fails after registering supervisor middleware | Service unavailable, invalid manifest, duplicate binding, reserved name, or invalid payload/timeout limit | Middleware service and gateway logs; `[[openshell.supervisor.middleware]]`; `Describe` response | +| Policy update rejects `network_middlewares` | Unknown middleware name, implementation-owned config invalid, duplicate order, broad/invalid host selector, or fail-closed coverage of `tls: skip` | Policy error, gateway logs, middleware `ValidateConfig`, selector and order fields | +| HTTP request returns `middleware_failed` or `middleware_denied`, or WebSocket closes with `1008` | Selected stage failed or explicitly denied admitted traffic | Sandbox OCSF logs; policy-local middleware config; service availability; binding operation; `on_error` | +| HTTP response becomes canonical `403 middleware_denied`, `502 response_delivery_failed`, or closes mid-body | Response middleware blocked, failed before commitment, or stopped delivery after commitment | Sandbox OCSF response middleware events; `HTTP_RESPONSE/PRE_RETURN` binding; `on_error`; `whole_body_accumulation_timeout`; service stream lifecycle | +| WebSocket upgrades but a host-matched middleware receives no preflight or message RPC | The implementation did not advertise `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` | `WEBSOCKET_MIDDLEWARE_COVERAGE state=binding_not_selected`; service `Describe`; the upgrade GET may still have used its HTTP binding | +| Binary WebSocket message passes without a middleware RPC | Binary is unsupported by the V1 text-message binding under both `on_error` modes | `WEBSOCKET_MIDDLEWARE_COVERAGE state=unsupported_message_type`; the next text RPC may have a valid sequence gap | +| WebSocket messages stop reaching middleware after one failure | A fail-open stage stream was disabled for the rest of the connection | `openshell.middleware.websocket_stage_disabled`; middleware timeout/stream/protocol logs. A per-message capacity bypass alone leaves the stage active. Reconnect to create a fresh stream after a genuine stream failure | +| Supervisor repeatedly fails to install middleware after enabling gateway JWT signing | Extension credential minting, distribution, or authenticated service connection failed; last-known-good registry remains active | Gateway `RefreshSandboxToken` logs, sandbox configuration events, service token-verification logs, registration TLS/audience settings | diff --git a/skills/generate-sandbox-policy/SKILL.md b/skills/generate-sandbox-policy/SKILL.md index 73c0863df7..39ab4cadef 100644 --- a/skills/generate-sandbox-policy/SKILL.md +++ b/skills/generate-sandbox-policy/SKILL.md @@ -83,7 +83,7 @@ Regardless of tier, extract (or infer) these from the user's description: | **Paths** | Specific URL paths or patterns | Only for custom/fine-grained | | **Enforcement** | `enforce` or `audit`? Default to `enforce`. | No — has a default | | **Binary** | Which binary/process should have access | Yes — ask if not stated | -| **Middleware** | Whether admitted HTTP requests or client WebSocket text messages need an ordered built-in or operator-run processing stage | No | +| **Middleware** | Whether admitted HTTP requests, final HTTP responses, or client WebSocket text messages need an ordered built-in or operator-run processing stage | No | If the host and access level are clear but binaries are not specified, ask the user which binary or process will be making the requests. Suggest common defaults like `/usr/bin/curl`, `/usr/local/bin/claude`, etc. @@ -209,14 +209,13 @@ Is L7 inspection needed? ### Middleware Decision -Add `network_middlewares` only when the user asks to inspect, transform, redact, or independently authorize admitted HTTP requests or client WebSocket text messages. Middleware runs after network and L7 policy admission and before provider credential injection. +Add `network_middlewares` only when the user asks to inspect, transform, redact, or independently authorize admitted HTTP requests, final HTTP responses, or client WebSocket text messages. Request middleware runs after network and L7 policy admission and before provider credential injection. Response middleware runs on the matching final response before it returns to the sandbox. - Use `openshell/regex` without gateway registration for fixed-pattern redaction of UTF-8 HTTP request bodies or complete client-to-upstream WebSocket text messages. - Use an operator-owned middleware name only when it is already registered under `[[openshell.supervisor.middleware]]` and reachable from both the gateway and sandbox supervisors. -- Confirm that a requested WebSocket implementation exposes a `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` binding. `openshell/regex` exposes this binding. A host-matched HTTP-only implementation may inspect the upgrade GET but does not join the post-upgrade chain; messages pass and OpenShell emits `binding_not_selected` coverage regardless of `on_error`. -- WebSocket middleware runs for both `ws://` and `wss://` and receives complete client text messages only. Binary messages pass under both error modes and emit `unsupported_message_type` coverage for active stages. Upstream-to-client messages remain uninspected. Do not claim that V1 provides all-message WebSocket inspection. -- Treat `fail_open` on WebSocket as a session-scoped bypass: if the stage stream fails, OpenShell disables it for later messages on that connection and emits a state-change finding. Prefer `fail_closed` for required redaction or authorization. -- `on_error` governs failures after an advertised operation binding is selected. It does not apply to an unadvertised WebSocket binding or binary-message pass-through. An explicit HTTP, WebSocket preflight, or WebSocket message denial is authoritative under both `fail_open` and `fail_closed`. +- Confirm that the implementation advertises the requested binding: `HTTP_REQUEST/PRE_CREDENTIALS`, `HTTP_RESPONSE/PRE_RETURN`, or `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. A host match alone does not enable inspection. +- WebSocket middleware inspects client text messages only, over both `ws://` and `wss://`. Binary and upstream-to-client messages pass without inspection, even with `fail_closed`. +- `on_error` controls selected-stage failures. Explicit denials always block traffic. A failed WebSocket stage with `fail_open` can remain bypassed for the rest of the connection. - Default `on_error` to `fail_closed`. Use `fail_open` only when bypassing the stage preserves the user's stated security requirement. - Assign unique `order` values across the complete policy. Lower values run first, and at most 10 configs may be selected. - Match the narrowest destination hosts possible with `endpoints.include`; use `exclude` when a broad selector has trusted exceptions. @@ -380,6 +379,7 @@ Before presenting the policy to the user, verify correctness **and** flag breadt - [ ] Middleware `order` values are unique and no selected chain exceeds 10 stages - [ ] No fail-closed middleware selector can cover a `tls: skip` endpoint - [ ] Any required WebSocket control advertises `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`, and the user understands that V1 does not inspect binary messages +- [ ] Any required response control advertises `HTTP_RESPONSE/PRE_RETURN` - [ ] Endpoints contributed by a credentialed provider are not L4-only or `tls: skip` unless `allow_uninspected_credentials: true` explicitly records the exception ### Schema Warnings (log-only, but should be fixed) diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index 2e4c9c3bdf..f449903d2b 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -164,6 +164,10 @@ openshell provider profile import --file ./my-profile.yaml ### List, inspect, update, delete +Use `openshell sandbox provider status --help` and the attach, detach, and update help to find the installed version's wait options. Add `--wait` when the next step depends on a provider change taking effect. Without it, a successful command only confirms that the gateway saved the change. Save the returned `receipt_id` to check that same change later, and inspect the result for every selected sandbox. Credential refresh status confirms that OpenShell obtained credentials; provider status confirms that the sandbox applied them, activated the policy, and updated the environment for new processes. If the status is `superseded`, explain that a later change replaced the request and inspect that change separately. + +If attach, detach, or update reports `CONFIG_OPERATION_STORAGE_UNCERTAIN`, explain that the change may already be saved and its readiness receipt may be unavailable. Do not blindly retry the mutation. Inspect the provider and sandbox state and reconcile the saved change before deciding on another mutation; the error proves neither rollback nor readiness. + ```bash openshell provider list openshell provider list --output json @@ -378,8 +382,9 @@ provider instead of passing API keys, tokens, or other secrets to `sandbox exec` ```bash openshell sandbox provider list my-sandbox openshell sandbox provider list my-sandbox --output json -openshell sandbox provider attach my-sandbox my-github -openshell sandbox provider detach my-sandbox my-github +openshell sandbox provider attach my-sandbox my-github --wait --timeout 30 +openshell sandbox provider status my-sandbox my-github --output json +openshell sandbox provider detach my-sandbox my-github --wait --timeout 30 ``` Structured attachment output contains provider names, types, and sorted @@ -507,11 +512,15 @@ Edit `current-policy.yaml` to allow the blocked actions. **For policy content au - TLS termination configuration - Enforcement modes (`audit` vs `enforce`) - Binary matching patterns -- Ordered `network_middlewares`, host selection, HTTP and WebSocket bindings, and `fail_open` or `fail_closed` behavior +- Ordered `network_middlewares`, host selection, HTTP request/response and WebSocket bindings, and `fail_open` or `fail_closed` behavior `network_policies` and `network_middlewares` can be modified at runtime when the selected compute driver supports live policy updates. Use `--wait` to verify that the active runtime loaded the revision; do not infer enforcement from the gateway accepting the update. If `filesystem_policy`, `landlock`, or `process` need changes, the sandbox must be recreated. Built-in middleware such as `openshell/regex` needs no gateway registration. An operator-run middleware must already be registered under `[[openshell.supervisor.middleware]]`; changing that static registration requires a gateway restart. -Middleware can inspect parsed HTTP request bodies and complete client-to-upstream WebSocket text messages over both `ws://` and `wss://` when the implementation advertises the matching binding. The built-in `openshell/regex` advertises both bindings and applies its fixed patterns to UTF-8 text. A host-matched HTTP-only attachment can inspect the upgrade GET but does not join the WebSocket chain; look for `binding_not_selected` coverage. Binary messages pass under both `on_error` modes and active stages emit `unsupported_message_type` coverage; upstream-to-client messages remain uninspected. A broken fail-open WebSocket stage is disabled for the rest of that connection; inspect sandbox OCSF logs for `openshell.middleware.websocket_stage_disabled`. +Middleware can inspect HTTP requests, HTTP responses, or client WebSocket text +messages when the implementation advertises the matching binding. The built-in +`openshell/regex` supports request bodies and client WebSocket text messages. +Use the `generate-sandbox-policy` skill to choose attachments and failure policy, +and `debug-openshell-cluster` to investigate middleware failures. ### Step 5: Push the updated policy @@ -719,14 +728,14 @@ endpoint, create the provider, and attach it only to sandboxes that need it: ```bash openshell provider profile import -f ./inference-provider.yaml openshell provider create --name model-provider --type --credential -openshell sandbox provider attach work-session model-provider +openshell sandbox provider attach work-session model-provider --wait --timeout 30 openshell sandbox exec work-session -- ``` The application owns the native base URL, model, request shape, and timeout. -Launch a new process after attaching a provider so it inherits the provider -credential placeholder. Use the `debug-inference` skill for endpoint, policy, -credential-binding, or migration failures. +Launch a new process after attachment readiness so it inherits the installed provider environment. Use the `debug-inference` skill for endpoint, policy, credential-binding, or migration failures. + +For an ordinary static provider update, wait for the update and launch a new client process to obtain the new reference. Do not claim that readiness updates the environment of an existing process or retargets its old reference. Acknowledged detach revokes retained references and removes them from future process environments. ## Workflow 8: Gateway Management diff --git a/tasks/python.toml b/tasks/python.toml index d009d0232f..8d3a142147 100644 --- a/tasks/python.toml +++ b/tasks/python.toml @@ -27,7 +27,7 @@ VERIFY_ARGS=() if [ -n "${SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL:-}" ]; then VERIFY_ARGS+=(--expected-version "$SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL") fi -uv run --no-project python tasks/scripts/verify-python-wheel.py "$WHEEL_OUTPUT_DIR" "${VERIFY_ARGS[@]}" +uv run --no-project python tasks/scripts/verify-python-wheel.py "$WHEEL_OUTPUT_DIR" ${VERIFY_ARGS[@]+"${VERIFY_ARGS[@]}"} """ hide = true diff --git a/tasks/scripts/gateway-docker.sh b/tasks/scripts/gateway-docker.sh index 0b3edca729..112319cca5 100644 --- a/tasks/scripts/gateway-docker.sh +++ b/tasks/scripts/gateway-docker.sh @@ -194,7 +194,7 @@ if [[ "${HOST_OS}" == "Linux" && "${HOST_ARCH}" == "${DAEMON_ARCH}" ]]; then "${ROOT}/target/${SUPERVISOR_TARGET}/debug/openshell-sandbox" else # Cross-compile through the prebuilt-binary staging helper, then use the - # supervisor stage to extract just the openshell-sandbox binary. + # sandbox stage to extract just the openshell-sandbox binary. # # This task is gated on a working Docker daemon above, so pin the # container-engine helper to docker — otherwise it auto-detects podman @@ -204,7 +204,7 @@ else if ! CONTAINER_ENGINE=docker \ DOCKER_PLATFORM="linux/${DAEMON_ARCH}" \ DOCKER_OUTPUT="type=local,dest=${SUPERVISOR_BUILD_DIR}" \ - bash "${ROOT}/tasks/scripts/docker-build-image.sh" supervisor-output; then + bash "${ROOT}/tasks/scripts/docker-build-image.sh" sandbox; then rm -rf -- "${SUPERVISOR_BUILD_DIR}" exit 1 fi diff --git a/tasks/scripts/package-deb-install.sh b/tasks/scripts/package-deb-install.sh index e20d409bbd..bd95a13e49 100755 --- a/tasks/scripts/package-deb-install.sh +++ b/tasks/scripts/package-deb-install.sh @@ -7,7 +7,7 @@ # or on the gateway-as-a-service flow. # # Steps: -# 1. cargo build --release the three binaries that go into the deb. +# 1. cargo build --release the four 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. @@ -57,11 +57,13 @@ echo "==> Building release binaries" cargo build --release \ -p openshell-cli \ -p openshell-gateway \ + -p openshell-prover-cli \ -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_PROVER_BINARY="${repo_root}/target/release/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="${repo_root}/target/release/openshell-driver-vm" \ OPENSHELL_DEB_VERSION="$VERSION" \ OPENSHELL_DEB_ARCH="$ARCH" \ @@ -79,6 +81,7 @@ sudo dpkg -i "$deb_path" openshell --version openshell-gateway --version +openshell-prover --version echo "==> Starting user gateway service" systemctl --user daemon-reload diff --git a/tasks/scripts/package-deb.sh b/tasks/scripts/package-deb.sh index 3e20f6256e..c2492dd242 100755 --- a/tasks/scripts/package-deb.sh +++ b/tasks/scripts/package-deb.sh @@ -21,6 +21,7 @@ Build the openshell Debian package. Required environment: OPENSHELL_CLI_BINARY Path to openshell OPENSHELL_GATEWAY_BINARY Path to openshell-gateway + OPENSHELL_PROVER_BINARY Path to openshell-prover OPENSHELL_DRIVER_VM_BINARY Path to openshell-driver-vm OPENSHELL_DEB_VERSION Debian package version @@ -69,6 +70,7 @@ infer_deb_arch() { require_env OPENSHELL_CLI_BINARY require_env OPENSHELL_GATEWAY_BINARY +require_env OPENSHELL_PROVER_BINARY require_env OPENSHELL_DRIVER_VM_BINARY require_env OPENSHELL_DEB_VERSION @@ -110,6 +112,7 @@ mkdir -p "$pkgroot/DEBIAN" # Binaries. stage_binary "$OPENSHELL_CLI_BINARY" "$pkgroot/usr/bin/openshell" stage_binary "$OPENSHELL_GATEWAY_BINARY" "$pkgroot/usr/bin/openshell-gateway" +stage_binary "$OPENSHELL_PROVER_BINARY" "$pkgroot/usr/bin/openshell-prover" stage_binary "$OPENSHELL_DRIVER_VM_BINARY" "$pkgroot/usr/libexec/openshell/openshell-driver-vm" # Per-user systemd unit. Each user enables it via `systemctl --user`. diff --git a/tasks/scripts/release.py b/tasks/scripts/release.py index 3b0afe5ecd..78695824c2 100644 --- a/tasks/scripts/release.py +++ b/tasks/scripts/release.py @@ -37,6 +37,7 @@ class Versions: HOMEBREW_CLI_ASSET = f"openshell-{HOMEBREW_TARGET}.tar.gz" HOMEBREW_GATEWAY_ASSET = f"openshell-gateway-{HOMEBREW_TARGET}.tar.gz" HOMEBREW_DRIVER_VM_ASSET = f"openshell-driver-vm-{HOMEBREW_TARGET}.tar.gz" +HOMEBREW_PROVER_ASSET = f"openshell-prover-{HOMEBREW_TARGET}.tar.gz" GITHUB_RELEASE_DOWNLOADS = "https://github.com/NVIDIA/OpenShell/releases/download" LOCAL_GATEWAY_PORT = 17670 _SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$") @@ -310,6 +311,7 @@ def render_homebrew_formula( cli_sha256: str, gateway_sha256: str, driver_vm_sha256: str, + prover_sha256: str, ) -> str: if not _RELEASE_TAG_RE.fullmatch(release_tag): raise ValueError(f"release tag contains unsupported characters: {release_tag}") @@ -341,6 +343,11 @@ class Openshell < Formula sha256 "{driver_vm_sha256}" end + resource "openshell-prover" do + url "{_asset_url(release_tag, HOMEBREW_PROVER_ASSET)}" + sha256 "{prover_sha256}" + end + def install odie "OpenShell Homebrew formula currently supports macOS only" unless OS.mac? @@ -354,6 +361,10 @@ def install libexec.install "openshell-driver-vm" end + resource("openshell-prover").stage do + bin.install "openshell-prover" + end + (libexec/"openshell-gateway-homebrew-service").write <<~SH #!/bin/sh set -eu @@ -475,6 +486,7 @@ def caveats test do assert_match "openshell ", shell_output("#{{bin}}/openshell --version") + assert_match "openshell-prover ", shell_output("#{{bin}}/openshell-prover --version") end end """ @@ -488,8 +500,10 @@ def generate_homebrew_formula( ) -> None: checksums_path = release_dir / "openshell-checksums-sha256.txt" gateway_checksums_path = release_dir / "openshell-gateway-checksums-sha256.txt" + prover_checksums_path = release_dir / "openshell-prover-checksums-sha256.txt" checksums = _parse_sha256_file(checksums_path) gateway_checksums = _parse_sha256_file(gateway_checksums_path) + prover_checksums = _parse_sha256_file(prover_checksums_path) formula = render_homebrew_formula( release_tag=release_tag, @@ -504,6 +518,11 @@ def generate_homebrew_formula( HOMEBREW_DRIVER_VM_ASSET, checksums_path, ), + prover_sha256=_required_checksum( + prover_checksums, + HOMEBREW_PROVER_ASSET, + prover_checksums_path, + ), ) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(formula, encoding="utf-8") diff --git a/tasks/scripts/test-install-sh.sh b/tasks/scripts/test-install-sh.sh index 5a20399b6a..b9d5f980ff 100755 --- a/tasks/scripts/test-install-sh.sh +++ b/tasks/scripts/test-install-sh.sh @@ -110,4 +110,15 @@ if [ "$(PLATFORM=linux local_gateway_endpoint)" != "https://127.0.0.1:17670" ]; exit 1 fi +cat >"${tmpdir}/checksums" <<'EOF' +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa openshell-dev-x86_64.rpm +bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb openshell-gateway-dev-x86_64.rpm +cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc openshell-prover-dev-x86_64.rpm +EOF + +if [ "$(find_rpm_asset "${tmpdir}/checksums" x86_64 openshell-prover)" != "openshell-prover-dev-x86_64.rpm" ]; then + echo "FAIL: RPM prover package selection" >&2 + exit 1 +fi + echo "install.sh focused tests passed" diff --git a/tasks/scripts/test-packaging-assets.sh b/tasks/scripts/test-packaging-assets.sh index 9c9d3011fd..02ecdb007f 100755 --- a/tasks/scripts/test-packaging-assets.sh +++ b/tasks/scripts/test-packaging-assets.sh @@ -58,6 +58,9 @@ assert_contains \ "$spec" \ 'ExecStartPre=/usr/bin/openshell-gateway generate-certs --output-dir ${OPENSHELL_LOCAL_TLS_DIR} --server-san host.openshell.internal' assert_contains "$spec" 'ExecStartPre=/usr/bin/openshell-gateway config preflight' +assert_contains "$spec" '%package prover' +assert_contains "$spec" '%files prover' +assert_contains "$spec" '%{_bindir}/%{name}-prover' assert_not_contains "$spec" '%%S/openshell/tls' # Schema-v2 package startup wiring. @@ -95,12 +98,13 @@ if command -v dpkg-deb >/dev/null 2>&1; then package_work=$(mktemp -d "${TMPDIR:-/tmp}/openshell-package-assets.XXXXXX") trap 'rm -rf "$package_work"' EXIT mkdir -p "$package_work/bin" "$package_work/output" - for binary in openshell openshell-gateway openshell-driver-vm; do + for binary in openshell openshell-gateway openshell-prover openshell-driver-vm; do printf '#!/bin/sh\nexit 0\n' >"$package_work/bin/$binary" chmod +x "$package_work/bin/$binary" done OPENSHELL_CLI_BINARY="$package_work/bin/openshell" \ OPENSHELL_GATEWAY_BINARY="$package_work/bin/openshell-gateway" \ + OPENSHELL_PROVER_BINARY="$package_work/bin/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="$package_work/bin/openshell-driver-vm" \ OPENSHELL_DEB_VERSION=0.0.0 \ OPENSHELL_DEB_ARCH=amd64 \ @@ -113,6 +117,11 @@ if command -v dpkg-deb >/dev/null 2>&1; then echo "FAIL: package-deb did not stage the current Debian service" >&2 exit 1 fi + if ! dpkg-deb --fsys-tarfile "$package_work/output/openshell_0.0.0_amd64.deb" \ + | tar -tf - | grep -x './usr/bin/openshell-prover' >/dev/null; then + echo "FAIL: package-deb did not stage openshell-prover" >&2 + exit 1 + fi else echo "SKIP: dpkg-deb unavailable; Debian artifact staging requires its assigned lane" fi diff --git a/tasks/test.toml b/tasks/test.toml index f26950ce51..2b0feb2bba 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -85,6 +85,7 @@ run = [ # with test-only helpers enabled. "cargo test --workspace --exclude openshell-server", "cargo test -p openshell-server --features test-support", + "cargo nextest run --config-file .config/nextest.toml --manifest-path examples/supervisor-middleware-content-guard/Cargo.toml", ] run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 test-precommit native" hide = true diff --git a/tests/ansible/playbooks/smoke.yaml b/tests/ansible/playbooks/conformance/cli.yaml similarity index 63% rename from tests/ansible/playbooks/smoke.yaml rename to tests/ansible/playbooks/conformance/cli.yaml index ca04b6605b..4adf9aa954 100644 --- a/tests/ansible/playbooks/smoke.yaml +++ b/tests/ansible/playbooks/conformance/cli.yaml @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 --- -- name: Run OpenShell smoke tests +- name: Run OpenShell conformance tests hosts: all gather_facts: false tasks: @@ -18,7 +18,7 @@ group: tmachine mode: "0700" - - name: Install OpenShell conformance test bundle + - name: Extract OpenShell conformance test bundle become: true ansible.builtin.unarchive: src: "{{ openshell_conformance_test_bundle }}" @@ -26,24 +26,20 @@ owner: tmachine group: tmachine - - name: Wait for OpenShell gateway - ansible.builtin.wait_for: - host: 127.0.0.1 - port: 17670 - timeout: 60 + # Report a malformed outer bundle directly instead of failing later with + # an opaque cargo-nextest missing-archive error. + - name: Check OpenShell conformance nextest archive + ansible.builtin.stat: + path: /var/lib/openshell-conformance/tests/tests.tar.zst + register: conformance_archive - - name: Register OpenShell gateway - ansible.builtin.command: - argv: - - /usr/local/bin/openshell - - gateway - - add - - http://127.0.0.1:17670 - - --local - - --name - - tmachine + - name: Require OpenShell conformance nextest archive + ansible.builtin.assert: + that: + - conformance_archive.stat.isreg | default(false) + fail_msg: OpenShell conformance test bundle did not contain tests.tar.zst - - name: Run OpenShell smoke conformance archive + - name: Run OpenShell conformance archive ansible.builtin.command: argv: - cargo-nextest @@ -60,13 +56,12 @@ changed_when: false failed_when: false - - name: Show OpenShell smoke conformance diagnostics + # Preserve both streams for failures without adding passing-test output to + # every tmachine run. + - name: Show OpenShell conformance diagnostics ansible.builtin.debug: - var: conformance_result.stderr_lines - - - name: Show OpenShell smoke conformance result - ansible.builtin.debug: - var: conformance_result.stdout_lines + var: conformance_result + when: conformance_result.rc != 0 - name: Read OpenShell gateway logs become: true @@ -88,8 +83,8 @@ var: openshell_gateway_logs.stdout_lines when: conformance_result.rc != 0 - - name: Require OpenShell smoke conformance success + - name: Require OpenShell conformance success ansible.builtin.assert: that: - conformance_result.rc == 0 - fail_msg: OpenShell smoke conformance test failed + fail_msg: OpenShell conformance test failed diff --git a/tests/ansible/playbooks/gateway.yaml b/tests/ansible/playbooks/gateway.yaml index 51d47e73cf..11fd7be882 100644 --- a/tests/ansible/playbooks/gateway.yaml +++ b/tests/ansible/playbooks/gateway.yaml @@ -7,3 +7,4 @@ gather_facts: false roles: - openshell_gateway + - openshell_client diff --git a/tests/ansible/roles/openshell_client/tasks/main.yaml b/tests/ansible/roles/openshell_client/tasks/main.yaml new file mode 100644 index 0000000000..25f41fb861 --- /dev/null +++ b/tests/ansible/roles/openshell_client/tasks/main.yaml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +--- +- name: Register OpenShell gateway for tmachine test client + ansible.builtin.command: + argv: + - /usr/local/bin/openshell + - gateway + - add + - http://127.0.0.1:17670 + - --local + - --name + - tmachine diff --git a/tests/artifacts.nix b/tests/artifacts.nix index 80bb1bf984..fe1d165c41 100644 --- a/tests/artifacts.nix +++ b/tests/artifacts.nix @@ -16,14 +16,15 @@ let builtins.attrValues toolchains ); - mkTestArchive = { - name, - workspacePath, - manifestPath, - package, - target, - output, - }: + mkTestArchive = + { + name, + workspacePath, + manifestPath, + package, + target, + output, + }: pkgs.writeShellApplication { name = "build-${name}-test-archive"; runtimeInputs = [ @@ -90,6 +91,7 @@ rec { binaries = pkgs.writeShellApplication { name = "build-artifacts-binaries"; runtimeInputs = [ + pkgs.coreutils pkgs.git rustToolchain ]; @@ -105,6 +107,22 @@ rec { cargo build --target ${gnuToolchain.target} \ -p openshell-gateway \ -p openshell-supervisor + + install -D -m 0755 \ + target/${muslToolchain.target}/debug/openshell \ + artifacts/binaries/${muslToolchain.target}/openshell + + install -D -m 0755 \ + target/${muslToolchain.target}/debug/openshell-sandbox \ + artifacts/binaries/${muslToolchain.target}/openshell-sandbox + + install -D -m 0755 \ + target/${gnuToolchain.target}/debug/openshell-gateway \ + artifacts/binaries/${gnuToolchain.target}/openshell-gateway + + install -D -m 0755 \ + target/${gnuToolchain.target}/debug/openshell-supervisor \ + artifacts/binaries/${gnuToolchain.target}/openshell-supervisor ''; }; @@ -119,15 +137,15 @@ rec { cd "$root" install -D -m 0755 \ - target/${gnuToolchain.target}/debug/openshell-gateway \ + artifacts/binaries/${gnuToolchain.target}/openshell-gateway \ deploy/docker/.build/prebuilt-binaries/${dockerArch}/openshell-gateway install -D -m 0755 \ - target/${gnuToolchain.target}/debug/openshell-supervisor \ + artifacts/binaries/${gnuToolchain.target}/openshell-supervisor \ deploy/docker/.build/prebuilt-binaries/${dockerArch}/openshell-supervisor install -D -m 0755 \ - target/${muslToolchain.target}/debug/openshell-sandbox \ + artifacts/binaries/${muslToolchain.target}/openshell-sandbox \ deploy/docker/.build/prebuilt-binaries/${dockerArch}/openshell-sandbox docker build \ diff --git a/tests/config.nix b/tests/config.nix index 23870587cd..b22c79f6c1 100644 --- a/tests/config.nix +++ b/tests/config.nix @@ -49,8 +49,8 @@ let "ansible/playbooks/gateway.yaml" ]; inputs = { - openshell_cli_binary = "../target/${muslTarget}/debug/openshell"; - openshell_gateway_binary = "../target/${gnuTarget}/debug/openshell-gateway"; + openshell_cli_binary = "../artifacts/binaries/${muslTarget}/openshell"; + openshell_gateway_binary = "../artifacts/binaries/${gnuTarget}/openshell-gateway"; openshell_supervisor_image = "../artifacts/images/openshell-supervisor-tmachine.tar"; openshell_sandbox_image = "../artifacts/images/openshell-sandbox-tmachine.tar"; }; @@ -73,8 +73,8 @@ let "ansible/playbooks/gateway.yaml" ]; inputs = { - openshell_cli_binary = "../target/${muslTarget}/debug/openshell"; - openshell_gateway_binary = "../target/${gnuTarget}/debug/openshell-gateway"; + openshell_cli_binary = "../artifacts/binaries/${muslTarget}/openshell"; + openshell_gateway_binary = "../artifacts/binaries/${gnuTarget}/openshell-gateway"; openshell_supervisor_image = "../artifacts/images/openshell-supervisor-tmachine.tar"; openshell_sandbox_image = "../artifacts/images/openshell-sandbox-tmachine.tar"; }; @@ -97,8 +97,8 @@ let "ansible/playbooks/gateway.yaml" ]; inputs = { - openshell_cli_binary = "../target/${muslTarget}/debug/openshell"; - openshell_gateway_binary = "../target/${gnuTarget}/debug/openshell-gateway"; + openshell_cli_binary = "../artifacts/binaries/${muslTarget}/openshell"; + openshell_gateway_binary = "../artifacts/binaries/${gnuTarget}/openshell-gateway"; openshell_supervisor_image = "../artifacts/images/openshell-supervisor-tmachine.tar"; openshell_sandbox_image = "../artifacts/images/openshell-sandbox-tmachine.tar"; }; @@ -108,8 +108,8 @@ let testsuites = [ { - name = "smoke"; - playbooks = [ "ansible/playbooks/smoke.yaml" ]; + name = "conformance"; + playbooks = [ "ansible/playbooks/conformance/cli.yaml" ]; inputs = { openshell_conformance_test_bundle = "../artifacts/test-archives/${muslTarget}/openshell-conformance-tests.tar"; }; diff --git a/tests/suites/conformance/cli/tests/lifecycle.rs b/tests/suites/conformance/cli/tests/lifecycle.rs new file mode 100644 index 0000000000..1a18adef86 --- /dev/null +++ b/tests/suites/conformance/cli/tests/lifecycle.rs @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Driver-agnostic sandbox lifecycle conformance tests. + +use openshell_conformance::{OpenShellRunner, SANDBOX_LIFECYCLE_SCENARIO}; + +/// Exercise stop, start, and stopped-deletion behavior through the candidate CLI. +#[tokio::test] +async fn sandbox_lifecycle() { + let mut runner = OpenShellRunner::from_env(SANDBOX_LIFECYCLE_SCENARIO.name) + .expect("candidate openshell CLI is available"); + + let result = async { + runner.check_gateway_status().await?; + SANDBOX_LIFECYCLE_SCENARIO.run(&mut runner).await + } + .await; + if let Err(error) = runner.finish(result).await { + panic!("sandbox lifecycle conformance scenario failed:\n{error}"); + } +}