diff --git a/.agents/skills/openshell-cli/SKILL.md b/.agents/skills/openshell-cli/SKILL.md index 69a889a8e2..313e239883 100644 --- a/.agents/skills/openshell-cli/SKILL.md +++ b/.agents/skills/openshell-cli/SKILL.md @@ -207,6 +207,18 @@ output. Use `provider refresh rotate`, reconfigure refresh, or delete refresh before returning those keys to manual management. Unrelated provider fields remain updateable. +When OAuth refresh fails, inspect the `RECOVERY` and `FAILURE_CODE` columns from +`provider refresh status`; do not infer the remedy from HTTP status or parse +`LAST_ERROR`. `retry` means the worker will try again, `reauthorize` means the +user must obtain a new OAuth grant and run `provider refresh configure`, +`fix_configuration` means an operator must repair the OAuth client, scopes, or +administrator policy, and `investigate` means the issuer returned an +unrecognized response. The gateway parks `reauthorize` records until a manual +rotate or reconfiguration. It retries +`fix_configuration` records hourly so externally repaired configuration can +recover without rapid token-endpoint traffic. The existing access credential +remains usable only until its recorded expiry. + --- ## Workflow 3: Sandbox Lifecycle diff --git a/.agents/skills/sbom/SKILL.md b/.agents/skills/sbom/SKILL.md index 5d62dde0ba..852259293d 100644 --- a/.agents/skills/sbom/SKILL.md +++ b/.agents/skills/sbom/SKILL.md @@ -9,15 +9,37 @@ Generate CycloneDX SBOMs, resolve missing licenses, and export to CSV for compli ## Overview -The OpenShell SBOM tooling produces CycloneDX JSON SBOMs using Syft, resolves missing or hash-based licenses by querying public registries (crates.io, npm, PyPI), and exports the results to CSV for stakeholder review. +The OpenShell SBOM tooling produces source-tree CycloneDX JSON SBOMs using Syft, resolves missing or hash-based licenses by querying public registries (crates.io, npm, PyPI), and exports the results to CSV for stakeholder review. SBOMs are **release artifacts only** -- they are generated on demand and not committed to the repository. Output lands in `deploy/sbom/output/` (gitignored). +Release Dev and Release Tag image builds separately embed cargo-auditable metadata in the staged gateway and supervisor binaries. This metadata describes the binary's Rust dependency graph and lets Syft discover Cargo packages from the binary itself. It is not a complete image SBOM and is not an OCI SBOM attestation; publishing such an attestation remains separate work. + ## Prerequisites - `mise install` has been run (installs Syft and other tools) - The repository is checked out at the root +## Inspecting an Auditable Image Binary + +Opt into auditable metadata when staging a local image binary: + +```bash +OPENSHELL_AUDITABLE=1 PREBUILT_ARCH=amd64 \ + tasks/scripts/stage-prebuilt-binaries.sh gateway +``` + +Scan the staged binary rather than the source tree: + +```bash +mise x -- syft \ + "file:deploy/docker/.build/prebuilt-binaries/amd64/openshell-gateway" \ + -o cyclonedx-json +``` + +This output is limited to packages Syft discovers from that binary. Use +`mise run sbom` for the broader source-tree license-compliance inventory. + ## Workflow 1: Full SBOM Generation (One Command) ```bash diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index d0d600e58b..2e7abe2008 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -32,6 +32,11 @@ on: required: false type: string default: "" + auditable: + description: "Embed cargo-auditable dependency metadata in image binaries" + required: false + type: boolean + default: false image-tag: description: "Image tag base to build/push (defaults to the GitHub SHA)" required: false @@ -177,6 +182,7 @@ jobs: image-tag: ${{ needs.resolve.outputs.image_tag_base }} checkout-ref: ${{ inputs['checkout-ref'] }} features: ${{ needs.resolve.outputs.features }} + auditable: ${{ inputs.auditable }} artifact-name: ${{ needs.resolve.outputs.artifact_prefix }}-linux-${{ matrix.arch }} secrets: inherit diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index 006f5cf440..f176953048 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -157,6 +157,12 @@ jobs: podman_package_version: "5.7.0+ds2-3build1" conmon_package_version: "2.1.13+ds1-2" cmd: "env -u OPENSHELL_GATEWAY_BIN mise run --no-deps --skip-deps e2e:podman:external-driver" + - suite: provider-refresh-keycloak + runner: ubuntu-26.04 + podman_major: "5" + podman_package_version: "5.7.0+ds2-3build1" + conmon_package_version: "2.1.13+ds1-2" + cmd: "mise run --no-deps --skip-deps e2e:provider-refresh-keycloak" env: IMAGE_TAG: ${{ inputs.image-tag }} MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -197,6 +203,7 @@ jobs: run: | sudo apt-get update sudo apt-get install -y --no-install-recommends \ + apparmor \ build-essential \ clang \ fuse-overlayfs \ @@ -219,6 +226,20 @@ jobs: echo "/usr/bin" >> "${GITHUB_PATH}" echo "CONTAINERS_CONF_OVERRIDE=${podman_config}" >> "${GITHUB_ENV}" + - name: Allow pasta to receive Podman stop signals + # Ubuntu's packaged pasta profile currently blocks this signal, forcing + # Podman to wait for its SIGKILL fallback. Keep this narrow allowance + # until the distribution package includes the upstream profile fix. + run: | + set -euo pipefail + profile=/etc/apparmor.d/usr.bin.pasta + rule=' signal (receive) peer=podman,' + if ! sudo grep -Fqx "${rule}" "${profile}"; then + sudo sed -i '\|^ include $|a\ signal (receive) peer=podman,' "${profile}" + fi + sudo grep -Fqx "${rule}" "${profile}" + sudo apparmor_parser --replace "${profile}" + - name: Configure rootless Podman run: | set -euo pipefail @@ -279,6 +300,17 @@ jobs: if: always() run: sudo dmesg | grep -E 'apparmor=.*DENIED|profile="unprivileged_userns"' | tail -100 || true + - name: Fail on pasta SIGTERM AppArmor denial + if: always() + run: | + set -euo pipefail + denials="$(sudo dmesg | grep -E 'profile="pasta".*requested_mask="receive".*signal=term.*peer="podman"' || true)" + if [ -n "${denials}" ]; then + echo "::error::pasta denied Podman's SIGTERM; Podman will use its SIGKILL fallback" + printf '%s\n' "${denials}" + exit 1 + fi + e2e-vm: name: E2E (rust-vm-${{ matrix.suite }}) # libkrun needs KVM, so this job must run directly on a GitHub-hosted diff --git a/.github/workflows/release-dev.yml b/.github/workflows/release-dev.yml index 768f5bd5a6..500fcb4be6 100644 --- a/.github/workflows/release-dev.yml +++ b/.github/workflows/release-dev.yml @@ -59,6 +59,7 @@ jobs: with: component: gateway cargo-version: ${{ needs.compute-versions.outputs.cargo_version }} + auditable: true build-supervisor: needs: [compute-versions] @@ -66,6 +67,7 @@ jobs: with: component: supervisor cargo-version: ${{ needs.compute-versions.outputs.cargo_version }} + auditable: true e2e: needs: [build-gateway, build-supervisor] @@ -99,91 +101,24 @@ jobs: "${REGISTRY}/${component}:${{ github.sha }}" done - build-python-wheels-linux: - name: Build Python Wheels (Linux ${{ matrix.arch }}) - needs: [compute-versions] - strategy: - matrix: - include: - - arch: amd64 - runner: linux-amd64-cpu8 - artifact: linux-amd64 - task: python:build:linux:amd64 - output_path: target/wheels/linux-amd64/*.whl - - arch: arm64 - runner: linux-arm64-cpu8 - artifact: linux-arm64 - task: python:build:linux:arm64 - output_path: target/wheels/linux-arm64/*.whl - runs-on: ${{ matrix.runner }} - timeout-minutes: 120 - container: - image: ghcr.io/nvidia/openshell/ci:latest - credentials: - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - options: --privileged - env: - MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - OPENSHELL_IMAGE_TAG: dev - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - - - name: Mark workspace safe for git - run: git config --global --add safe.directory "$GITHUB_WORKSPACE" - - - name: Sync Python dependencies - run: uv sync - - - name: Cache Rust target and registry - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - shared-key: python-wheel-linux-${{ matrix.arch }} - cache-directories: .cache/sccache - cache-targets: "true" - - - name: Build Python wheels - run: | - set -euo pipefail - OPENSHELL_CARGO_VERSION="${{ needs.compute-versions.outputs.cargo_version }}" mise run ${{ matrix.task }} - ls -la ${{ matrix.output_path }} - - - name: Upload wheel artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: python-wheels-${{ matrix.artifact }} - path: ${{ matrix.output_path }} - retention-days: 5 - - build-python-wheel-macos: - name: Build Python Wheel (macOS) + build-python-wheel: + name: Build Python Wheel needs: [compute-versions] runs-on: linux-amd64-cpu8 - timeout-minutes: 120 + timeout-minutes: 20 container: image: ghcr.io/nvidia/openshell/ci:latest credentials: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - options: --privileged - volumes: - - /var/run/docker.sock:/var/run/docker.sock env: MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - OPENSHELL_IMAGE_TAG: dev + SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL: ${{ needs.compute-versions.outputs.python_version }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - name: Log in to GHCR - run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin - - - name: Set up Docker Buildx - uses: ./.github/actions/setup-buildx - - name: Mark workspace safe for git run: git config --global --add safe.directory "$GITHUB_WORKSPACE" @@ -193,13 +128,13 @@ jobs: - name: Build Python wheel run: | set -euo pipefail - OPENSHELL_CARGO_VERSION="${{ needs.compute-versions.outputs.cargo_version }}" mise run python:build:macos + mise run python:build ls -la target/wheels/*.whl - - name: Upload wheel artifacts + - name: Upload wheel artifact uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: - name: python-wheels-macos + name: python-wheel path: target/wheels/*.whl retention-days: 5 @@ -683,7 +618,7 @@ jobs: smoke-linux-dev-artifacts: name: Smoke Linux Dev Artifacts (${{ matrix.name }}) - needs: [build-gateway-binary-linux, build-driver-vm-linux, build-deb, build-rpm, build-python-wheels-linux] + needs: [build-gateway-binary-linux, build-driver-vm-linux, build-deb, build-rpm, build-python-wheel] timeout-minutes: 20 strategy: fail-fast: false @@ -713,18 +648,10 @@ jobs: kind: rpm artifact_arch: arm64 rpm_arch: aarch64 - - name: python-wheel-amd64 + - name: python-wheel runner: linux-amd64-cpu8 image: python:3.12-slim kind: wheel - artifact_arch: amd64 - rpm_arch: x86_64 - - name: python-wheel-arm64 - runner: linux-arm64-cpu8 - image: python:3.12-slim - kind: wheel - artifact_arch: arm64 - rpm_arch: aarch64 runs-on: ${{ matrix.runner }} container: image: ${{ matrix.image }} @@ -763,27 +690,29 @@ jobs: if: matrix.kind == 'wheel' uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: python-wheels-linux-${{ matrix.artifact_arch }} + name: python-wheel path: wheel-input/ - name: Smoke Python wheel if: matrix.kind == 'wheel' run: | set -euo pipefail - pip install --no-cache-dir wheel-input/*.whl - python - <<'PY' + python -m venv /tmp/openshell-wheel-smoke + /tmp/openshell-wheel-smoke/bin/pip install --no-cache-dir wheel-input/*.whl + /tmp/openshell-wheel-smoke/bin/python - <<'PY' import importlib for name in ("openshell", "openshell._proto", "openshell.sandbox"): importlib.import_module(name) print(name, "OK") PY + test ! -e /tmp/openshell-wheel-smoke/bin/openshell # --------------------------------------------------------------------------- # Create / update the dev GitHub Release with CLI, gateway, driver, and wheels # --------------------------------------------------------------------------- release-dev: name: Release Dev - needs: [compute-versions, build-cli-linux, build-cli-macos, build-gateway-binary-linux, build-gateway-binary-macos, build-supervisor-binary-linux, build-python-wheels-linux, build-python-wheel-macos, e2e, build-driver-vm-linux, build-driver-vm-macos, build-deb, build-rpm, build-snap, smoke-linux-dev-artifacts] + needs: [compute-versions, build-cli-linux, build-cli-macos, build-gateway-binary-linux, build-gateway-binary-macos, build-supervisor-binary-linux, build-python-wheel, e2e, build-driver-vm-linux, build-driver-vm-macos, build-deb, build-rpm, build-snap, smoke-linux-dev-artifacts] runs-on: linux-amd64-cpu8 timeout-minutes: 10 permissions: @@ -824,12 +753,11 @@ jobs: path: release/ merge-multiple: true - - name: Download wheel artifacts + - name: Download wheel artifact uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - pattern: python-wheels-* + name: python-wheel path: release/ - merge-multiple: true - name: Download Debian package artifacts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 @@ -881,9 +809,14 @@ jobs: id: wheel_filenames run: | set -euo pipefail - ls -la release/*.whl - WHEEL_FILENAMES=$(ls release/*.whl | xargs -n1 basename | sort | paste -sd, -) - echo "wheel_filenames=${WHEEL_FILENAMES}" >> "$GITHUB_OUTPUT" + shopt -s nullglob + wheels=(release/*.whl) + if [ "${#wheels[@]}" -ne 1 ]; then + echo "expected exactly one Python wheel, found ${#wheels[@]}" >&2 + exit 1 + fi + wheel_filename=$(basename "${wheels[0]}") + echo "wheel_filenames=${wheel_filename}" >> "$GITHUB_OUTPUT" - name: Generate checksums run: | diff --git a/.github/workflows/release-tag.yml b/.github/workflows/release-tag.yml index 35792bcb63..74be300b0c 100644 --- a/.github/workflows/release-tag.yml +++ b/.github/workflows/release-tag.yml @@ -81,6 +81,7 @@ jobs: cargo-version: ${{ needs.compute-versions.outputs.cargo_version }} image-tag: ${{ needs.compute-versions.outputs.source_sha }} checkout-ref: ${{ inputs.tag || github.ref }} + auditable: true build-supervisor: needs: [compute-versions] @@ -90,6 +91,7 @@ jobs: cargo-version: ${{ needs.compute-versions.outputs.cargo_version }} image-tag: ${{ needs.compute-versions.outputs.source_sha }} checkout-ref: ${{ inputs.tag || github.ref }} + auditable: true e2e: needs: [compute-versions, build-gateway, build-supervisor] @@ -130,93 +132,25 @@ jobs: "${REGISTRY}/${component}:${SOURCE_TAG}" done - build-python-wheels-linux: - name: Build Python Wheels (Linux ${{ matrix.arch }}) - needs: [compute-versions] - strategy: - matrix: - include: - - arch: amd64 - runner: linux-amd64-cpu8 - artifact: linux-amd64 - task: python:build:linux:amd64 - output_path: target/wheels/linux-amd64/*.whl - - arch: arm64 - runner: linux-arm64-cpu8 - artifact: linux-arm64 - task: python:build:linux:arm64 - output_path: target/wheels/linux-arm64/*.whl - runs-on: ${{ matrix.runner }} - timeout-minutes: 120 - container: - image: ghcr.io/nvidia/openshell/ci:latest - credentials: - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - options: --privileged - env: - MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - OPENSHELL_IMAGE_TAG: ${{ needs.compute-versions.outputs.semver }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ inputs.tag || github.ref }} - fetch-depth: 0 - - - name: Mark workspace safe for git - run: git config --global --add safe.directory "$GITHUB_WORKSPACE" - - - name: Sync Python dependencies - run: uv sync - - - name: Cache Rust target and registry - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 - with: - shared-key: python-wheel-linux-${{ matrix.arch }} - cache-directories: .cache/sccache - cache-targets: "true" - - - name: Build Python wheels - run: | - set -euo pipefail - OPENSHELL_CARGO_VERSION="${{ needs.compute-versions.outputs.cargo_version }}" mise run ${{ matrix.task }} - ls -la ${{ matrix.output_path }} - - - name: Upload wheel artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: python-wheels-${{ matrix.artifact }} - path: ${{ matrix.output_path }} - retention-days: 5 - - build-python-wheel-macos: - name: Build Python Wheel (macOS) + build-python-wheel: + name: Build Python Wheel needs: [compute-versions] runs-on: linux-amd64-cpu8 - timeout-minutes: 120 + timeout-minutes: 20 container: image: ghcr.io/nvidia/openshell/ci:latest credentials: username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - options: --privileged - volumes: - - /var/run/docker.sock:/var/run/docker.sock env: MISE_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - OPENSHELL_IMAGE_TAG: ${{ needs.compute-versions.outputs.semver }} + SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL: ${{ needs.compute-versions.outputs.python_version }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.tag || github.ref }} fetch-depth: 0 - - name: Log in to GHCR - run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin - - - name: Set up Docker Buildx - uses: ./.github/actions/setup-buildx - - name: Mark workspace safe for git run: git config --global --add safe.directory "$GITHUB_WORKSPACE" @@ -226,13 +160,13 @@ jobs: - name: Build Python wheel run: | set -euo pipefail - OPENSHELL_CARGO_VERSION="${{ needs.compute-versions.outputs.cargo_version }}" mise run python:build:macos + mise run python:build ls -la target/wheels/*.whl - - name: Upload wheel artifacts + - name: Upload wheel artifact uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: - name: python-wheels-macos + name: python-wheel path: target/wheels/*.whl retention-days: 5 @@ -721,7 +655,7 @@ jobs: smoke-linux-release-artifacts: name: Smoke Linux Release Artifacts (${{ matrix.name }}) - needs: [build-gateway-binary-linux, build-driver-vm-linux, build-deb, build-rpm, build-python-wheels-linux] + needs: [build-gateway-binary-linux, build-driver-vm-linux, build-deb, build-rpm, build-python-wheel] timeout-minutes: 20 strategy: fail-fast: false @@ -773,16 +707,6 @@ jobs: runner: linux-amd64-cpu8 image: python:3.12-slim kind: wheel - artifact_arch: amd64 - rpm_arch: x86_64 - target: x86_64-unknown-linux-gnu - - name: python-wheel-arm64 - runner: linux-arm64-cpu8 - image: python:3.12-slim - kind: wheel - artifact_arch: arm64 - rpm_arch: aarch64 - target: aarch64-unknown-linux-gnu runs-on: ${{ matrix.runner }} container: image: ${{ matrix.image }} @@ -846,27 +770,29 @@ jobs: if: matrix.kind == 'wheel' uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - name: python-wheels-linux-${{ matrix.artifact_arch }} + name: python-wheel path: wheel-input/ - name: Smoke Python wheel if: matrix.kind == 'wheel' run: | set -euo pipefail - pip install --no-cache-dir wheel-input/*.whl - python - <<'PY' + python -m venv /tmp/openshell-wheel-smoke + /tmp/openshell-wheel-smoke/bin/pip install --no-cache-dir wheel-input/*.whl + /tmp/openshell-wheel-smoke/bin/python - <<'PY' import importlib for name in ("openshell", "openshell._proto", "openshell.sandbox"): importlib.import_module(name) print(name, "OK") PY + test ! -e /tmp/openshell-wheel-smoke/bin/openshell # --------------------------------------------------------------------------- # Create a tagged GitHub Release with CLI, gateway, driver, and wheels # --------------------------------------------------------------------------- release: name: Release - needs: [compute-versions, build-cli-linux, build-cli-macos, build-gateway-binary-linux, build-gateway-binary-macos, build-supervisor-binary-linux, build-python-wheels-linux, build-python-wheel-macos, e2e, build-driver-vm-linux, build-driver-vm-macos, build-deb, build-rpm, build-snap, smoke-linux-release-artifacts] + needs: [compute-versions, build-cli-linux, build-cli-macos, build-gateway-binary-linux, build-gateway-binary-macos, build-supervisor-binary-linux, build-python-wheel, e2e, build-driver-vm-linux, build-driver-vm-macos, build-deb, build-rpm, build-snap, smoke-linux-release-artifacts] runs-on: linux-amd64-cpu8 timeout-minutes: 10 permissions: @@ -909,12 +835,11 @@ jobs: path: release/ merge-multiple: true - - name: Download wheel artifacts + - name: Download wheel artifact uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - pattern: python-wheels-* + name: python-wheel path: release/ - merge-multiple: true - name: Download Debian package artifacts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 @@ -941,9 +866,14 @@ jobs: id: wheel_filenames run: | set -euo pipefail - ls -la release/*.whl - WHEEL_FILENAMES=$(ls release/*.whl | xargs -n1 basename | sort | paste -sd, -) - echo "wheel_filenames=${WHEEL_FILENAMES}" >> "$GITHUB_OUTPUT" + shopt -s nullglob + wheels=(release/*.whl) + if [ "${#wheels[@]}" -ne 1 ]; then + echo "expected exactly one Python wheel, found ${#wheels[@]}" >&2 + exit 1 + fi + wheel_filename=$(basename "${wheels[0]}") + echo "wheel_filenames=${wheel_filename}" >> "$GITHUB_OUTPUT" - name: Generate checksums run: | diff --git a/.github/workflows/rust-native-build.yml b/.github/workflows/rust-native-build.yml index f024cacc50..3496f4779f 100644 --- a/.github/workflows/rust-native-build.yml +++ b/.github/workflows/rust-native-build.yml @@ -40,6 +40,11 @@ on: required: false type: string default: "" + auditable: + description: "Embed cargo-auditable dependency metadata in the binary" + required: false + type: boolean + default: false retention-days: description: "Artifact retention period" required: false @@ -265,6 +270,7 @@ jobs: mise x -- rustup target add "${{ steps.target.outputs.target }}" cargo_cmd=(cargo build) + cargo_env=() build_target="${{ steps.target.outputs.target }}" args=() @@ -278,6 +284,13 @@ jobs: # accepts -static for *-linux-gnu and links dynamically anyway. export RUSTFLAGS="${RUSTFLAGS:-} -C target-feature=+crt-static" fi + if [[ "${{ inputs.auditable }}" == "true" ]]; then + cargo_cmd=("${cargo_cmd[0]}" auditable "${cargo_cmd[@]:1}") + # mise.toml injects RUSTC_WRAPPER=sccache. Unset it after mise has + # constructed the environment so it cannot wrap cargo-auditable's + # RUSTC_WORKSPACE_WRAPPER and misidentify that wrapper as rustc. + cargo_env=(env -u RUSTC_WRAPPER) + fi args+=( --release --target "$build_target" @@ -290,7 +303,7 @@ jobs: if [[ -n "${{ steps.version.outputs.cargo_version }}" ]]; then export GIT_DIR=/nonexistent fi - mise x -- "${cargo_cmd[@]}" "${args[@]}" + mise x -- "${cargo_env[@]}" "${cargo_cmd[@]}" "${args[@]}" - name: Verify packaged binary run: | @@ -307,6 +320,22 @@ jobs: exit 1 fi + - name: Verify auditable dependency metadata + if: inputs.auditable + run: | + set -euo pipefail + BIN="target/${{ steps.target.outputs.target }}/release/${{ steps.target.outputs.binary }}" + cargo_packages="$( + SYFT_CHECK_FOR_APP_UPDATE=false \ + mise x -- syft "file:$BIN" -o cyclonedx-json | + jq '[.components[]? | select((.purl // "") | startswith("pkg:cargo/"))] | length' + )" + if [[ "$cargo_packages" -eq 0 ]]; then + echo "Syft did not decode any Cargo packages from $BIN" >&2 + exit 1 + fi + echo "auditable dependency metadata: $cargo_packages Cargo packages" + - name: Verify glibc symbol floor if: inputs.component == 'gateway' run: | diff --git a/README.md b/README.md index b8ce17a6d2..ba1ccf9859 100644 --- a/README.md +++ b/README.md @@ -33,14 +33,14 @@ OpenShell is built agent-first. The project ships with agent skills for everythi curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh | sh ``` -**From PyPI (requires [uv](https://docs.astral.sh/uv/)):** +The installer installs the latest stable release by default. To install a specific version, set `OPENSHELL_VERSION`. A [`dev` release](https://github.com/NVIDIA/OpenShell/releases/tag/dev) is also available that tracks the latest commit on `main`. + +The `openshell` package on PyPI provides the Python SDK only. It does not install the `openshell` CLI. Add the SDK to a Python project with [uv](https://docs.astral.sh/uv/): ```bash -uv tool install -U openshell +uv add openshell ``` -Both methods install the latest stable release by default. To install a specific version, set `OPENSHELL_VERSION` (binary) or pin the version with `uv tool install openshell==`. A [`dev` release](https://github.com/NVIDIA/OpenShell/releases/tag/dev) is also available that tracks the latest commit on `main`. - **Helm chart:** > **Experimental** — the Kubernetes deployment path is under active development. Expect rough edges and breaking changes. diff --git a/THIRD-PARTY-NOTICES b/THIRD-PARTY-NOTICES index 41eda0e0a8..8125e5692f 100644 --- a/THIRD-PARTY-NOTICES +++ b/THIRD-PARTY-NOTICES @@ -14813,13 +14813,6 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -================================================================================ -maturin 1.11.5 -License: MIT OR Apache-2.0 --------------------------------------------------------------------------------- - -UNKNOWN - ================================================================================ packaging 26.0 License: Apache-2.0 OR BSD-2-Clause diff --git a/architecture/build.md b/architecture/build.md index 5c5751772a..7daf4a7c66 100644 --- a/architecture/build.md +++ b/architecture/build.md @@ -11,7 +11,8 @@ OpenShell builds these main artifacts: | Artifact | Source | |---|---| | Gateway binary | `crates/openshell-server` | -| CLI package and Python SDK | `python/openshell` plus Rust binaries where packaged | +| CLI binaries and system packages | `crates/openshell-cli` plus release packaging | +| Python SDK wheel | `python/openshell` | | TypeScript SDK package | `sdk/typescript` | | Gateway container image | `deploy/docker/Dockerfile.gateway` | | Supervisor container image | `deploy/docker/Dockerfile.supervisor` | @@ -130,6 +131,27 @@ step via the `rust-native-build.yml` workflow (per-architecture, per-component) and uploads the result as an artifact that the image build job downloads back into the staging directory before running Buildx. +Gateway and supervisor binaries staged into Release Dev and Release Tag images +are compiled through `cargo auditable` (pinned in `mise.toml`), which embeds a +`.dep-v0` section describing the Rust dependencies actually compiled into the +binary. That section holds data rather than symbols, so it survives the +workspace's `strip = true` release profile, and Syft can catalog the crates +present in image binaries instead of inferring them from the source tree. This +is a different artifact from the source SBOM produced by `syft dir:.` in +`tasks/sbom.toml`, which describes the checkout, and from an OCI SBOM +attestation, which remains out of scope. + +Only release image builds are auditable. `docker-build.yml` and +`rust-native-build.yml` take an `auditable` input that defaults to false, so PR +and E2E image builds and standalone release artifacts remain non-auditable. The +CI image gains the pinned `cargo-auditable` tool through `mise install --locked` +but ships no auditable OpenShell binary of its own. Local staging opts in with +`OPENSHELL_AUDITABLE=1`. sccache's `RUSTC_WRAPPER` is unset only around auditable +builds, because it would otherwise wrap `cargo-auditable`'s workspace wrapper and +be misidentified as `rustc`. Auditable builds are verified by scanning the built +binary with Syft and requiring at least one decoded Cargo package; the check runs +only for those builds. + Runtime layout: - **Gateway**: `gcr.io/distroless/cc-debian13:nonroot` base, GNU-linked binary at @@ -205,14 +227,18 @@ for explicit publication. ## Python Wheel Packaging The generated protobuf/gRPC stubs under `python/openshell/_proto/` are gitignored -build outputs of `mise run python:proto`. The task uses `uv run --frozen` to -synchronize the current worktree's `.venv` from `uv.lock` before generation. -maturin honors `.gitignore` when collecting `python-source` files, so native -builds (Linux CI, local `pip install .`) would drop them and ship an unimportable -wheel. `pyproject.toml` -pins them back in with `[tool.maturin].include` globs. The release workflows -install each Linux wheel in a clean image and import `openshell.sandbox` as a -smoke check. +build outputs of `mise run python:proto`. Setuptools includes them through the +package-data configuration in `pyproject.toml`. Release workflows build the +wheel directly and do not produce a source distribution. Setuptools SCM derives +local versions from Git and accepts the release workflow's computed version +through its distribution-specific override. + +The build produces one platform-independent `py3-none-any` wheel. A verifier +checks its tag, metadata, version, required package files, and the absence of +native files or an `openshell` executable entry point. Release workflows build +the wheel once, install it in a clean virtual environment, import the public +package modules, and confirm that installation did not create an `openshell` +command. ## TypeScript SDK Packaging diff --git a/architecture/gateway.md b/architecture/gateway.md index f7c80d1ed8..f86f855845 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -189,6 +189,14 @@ reuses them when refreshing an access token. This preserves the intended API resource selection for identity providers that bind access-token audiences to OAuth scopes. +Python and Go SDK client-credentials providers can use the same registered +issuer, client ID, audience, and scope metadata; the TypeScript provider accepts +those fields explicitly. All three own a separate in-memory lifecycle, repeat +the grant before expiry, and never persist the client secret or acquired access +token into the CLI token cache. They require TLS when sending renewable bearer +credentials to non-loopback gateways. This keeps non-interactive SDK +authentication independent from refresh-token rotation and shared disk state. + Gateway health and user authentication are separate probes. `OpenShell.Health` remains unauthenticated so deployment and load-balancer health checks do not depend on user credentials. The CLI uses the existing, side-effect-free @@ -343,6 +351,15 @@ Multi-replica deployments can use that default with a shared database and shared key-encryption key, or opt into an external backend such as Vault or Kubernetes Secrets. +OAuth refresh failures retain a gateway-owned recovery classification alongside +the refresh state. The gateway reads only a bounded error response and maps +recognized OAuth codes to retry, reauthorization, configuration repair, or +investigation without persisting issuer-controlled descriptions. Terminal +reauthorization failures remain parked until a manual retry or explicit refresh +reconfiguration. Configuration failures retry hourly so an externally repaired +clock, policy, or stored credential can recover without rapid endpoint traffic; +short-lived credentials still fail closed at their recorded expiry. + Credential handles remain bound to the driver that created them. Before the 0.1.0 compatibility boundary, gateways do not migrate inline refresh material or move handles between credential drivers; operators reconfigure affected diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index af8b7d5fd2..0a0b21a7f4 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -46,7 +46,8 @@ use openshell_core::proto::{ GetSandboxRequest, GetServiceRequest, GpuResourceRequirements, ImportProviderProfilesRequest, LintProviderProfilesRequest, ListProviderProfilesRequest, ListProvidersRequest, ListSandboxPoliciesRequest, ListSandboxProvidersRequest, ListSandboxesRequest, - ListServicesRequest, PolicySource, PolicyStatus, Provider, ProviderCredentialRefreshStatus, + ListServicesRequest, PolicySource, PolicyStatus, Provider, + ProviderCredentialRefreshRecoveryAction, ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrantType, ProviderProfile, ProviderProfileDiagnostic, ProviderProfileImportItem, RejectDraftChunkRequest, ResourceRequirements, RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox, @@ -4338,14 +4339,16 @@ pub async fn provider_refresh_status( fn refresh_status_header() -> String { format!( - "{:<24} {:<28} {:<28} {:<18} {:<20} {:<20} {:<20} {}", + "{:<24} {:<28} {:<28} {:<24} {:<18} {:<20} {:<20} {:<20} {:<44} {}", "PROVIDER".bold(), "CREDENTIAL_KEY".bold(), "STRATEGY".bold(), "STATUS".bold(), + "RECOVERY".bold(), "EXPIRES_AT".bold(), "NEXT_REFRESH".bold(), "LAST_REFRESH".bold(), + "FAILURE_CODE".bold(), "LAST_ERROR".bold(), ) } @@ -4497,19 +4500,43 @@ fn print_refresh_status_row(status: &ProviderCredentialRefreshStatus) { fn refresh_status_row(status: &ProviderCredentialRefreshStatus) -> String { let strategy = ProviderCredentialRefreshStrategy::try_from(status.strategy) .unwrap_or(ProviderCredentialRefreshStrategy::Unspecified); + let recovery_action = ProviderCredentialRefreshRecoveryAction::try_from(status.recovery_action) + .unwrap_or(ProviderCredentialRefreshRecoveryAction::Unspecified); format!( - "{:<24} {:<28} {:<28} {:<18} {:<20} {:<20} {:<20} {}", + "{:<24} {:<28} {:<28} {:<24} {:<18} {:<20} {:<20} {:<20} {:<44} {}", status.provider_name, status.credential_key, provider_refresh_strategy_name(strategy), status.status, + provider_refresh_recovery_action_name(recovery_action), format_optional_epoch_ms(status.expires_at_ms), - format_optional_epoch_ms(status.next_refresh_at_ms), + format_refresh_next_at_ms(status.next_refresh_at_ms), format_optional_epoch_ms(status.last_refresh_at_ms), + status.failure_code, truncate_status_field(&status.last_error, 72), ) } +fn format_refresh_next_at_ms(next_refresh_at_ms: i64) -> String { + if next_refresh_at_ms == i64::MAX { + "-".to_string() + } else { + format_optional_epoch_ms(next_refresh_at_ms) + } +} + +fn provider_refresh_recovery_action_name( + action: ProviderCredentialRefreshRecoveryAction, +) -> &'static str { + match action { + ProviderCredentialRefreshRecoveryAction::Retry => "retry", + ProviderCredentialRefreshRecoveryAction::Reauthorize => "reauthorize", + ProviderCredentialRefreshRecoveryAction::FixConfiguration => "fix_configuration", + ProviderCredentialRefreshRecoveryAction::Investigate => "investigate", + ProviderCredentialRefreshRecoveryAction::Unspecified => "-", + } +} + fn provider_refresh_strategy_name(strategy: ProviderCredentialRefreshStrategy) -> &'static str { match strategy { ProviderCredentialRefreshStrategy::Static => "static", @@ -7403,10 +7430,11 @@ mod tests { }; use openshell_core::proto::{ GetSandboxConfigResponse, GpuResourceRequirements, PolicySource, PolicyStatus, Provider, - ProviderCredentialRefresh, ProviderCredentialRefreshStatus, - ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrant, ProviderProfile, - ProviderProfileCredential, ResourceRequirements, Sandbox, SandboxCondition, SandboxPhase, - SandboxPolicyRevision, SandboxStatus, datamodel::v1::ObjectMeta, + ProviderCredentialRefresh, ProviderCredentialRefreshRecoveryAction, + ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, + ProviderCredentialTokenGrant, ProviderProfile, ProviderProfileCredential, + ResourceRequirements, Sandbox, SandboxCondition, SandboxPhase, SandboxPolicyRevision, + SandboxStatus, datamodel::v1::ObjectMeta, }; #[test] @@ -7645,6 +7673,8 @@ mod tests { let header = refresh_status_header(); assert!(header.contains("NEXT_REFRESH")); assert!(header.contains("LAST_REFRESH")); + assert!(header.contains("RECOVERY")); + assert!(header.contains("FAILURE_CODE")); assert!(header.contains("LAST_ERROR")); let row = refresh_status_row(&ProviderCredentialRefreshStatus { @@ -7654,17 +7684,24 @@ mod tests { strategy: ProviderCredentialRefreshStrategy::Oauth2ClientCredentials as i32, status: "error".to_string(), expires_at_ms: 1_767_225_600_000, - next_refresh_at_ms: 1_767_225_660_000, + next_refresh_at_ms: i64::MAX, last_refresh_at_ms: 1_767_225_000_000, last_error: "token endpoint returned a very long error message that should be truncated for table readability" .to_string(), + recovery_action: ProviderCredentialRefreshRecoveryAction::Reauthorize as i32, + failure_code: "oauth_rotated_refresh_token_handle_missing".to_string(), + provider_error_subtype: "invalid_rapt".to_string(), + last_error_at_ms: 1_767_225_000_000, }); assert!(row.contains("my-graph")); assert!(row.contains("MS_GRAPH_ACCESS_TOKEN")); assert!(row.contains("oauth2_client_credentials")); assert!(row.contains("error")); + assert!(row.contains("reauthorize")); + assert!(row.contains("oauth_rotated_refresh_token_handle_missing")); assert!(row.contains("2026-01-01 00:00:00")); + assert!(!row.contains("292278994")); assert!(row.contains("...")); } diff --git a/crates/openshell-cli/tests/provider_commands_integration.rs b/crates/openshell-cli/tests/provider_commands_integration.rs index c349bbdbb4..2c71e0b39f 100644 --- a/crates/openshell-cli/tests/provider_commands_integration.rs +++ b/crates/openshell-cli/tests/provider_commands_integration.rs @@ -750,6 +750,10 @@ impl OpenShell for TestOpenShell { next_refresh_at_ms: 0, last_refresh_at_ms: 0, last_error: String::new(), + recovery_action: 0, + failure_code: String::new(), + provider_error_subtype: String::new(), + last_error_at_ms: 0, }; drop(providers); self.state diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 62411e20b5..ed5736eff7 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -13,8 +13,9 @@ use std::net::SocketAddr; #[cfg(unix)] use std::os::unix::fs::FileTypeExt; use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; use std::str::FromStr; -use std::time::Duration; +use std::time::{Duration, Instant}; // ── Public default constants ──────────────────────────────────────────── // @@ -214,9 +215,16 @@ pub fn is_podman_available() -> bool { detect_podman_socket().is_some() } -/// Return the first responsive Podman API socket, or `None` if none respond. +/// Return the Podman API socket, or `None` if Podman is not available. +/// +/// Probes the well-known socket candidates first, then falls back to asking +/// the Podman CLI where its socket lives. The symlink at a well-known path is +/// not always present — it varies by Podman version, machine provider, and +/// platform — so the CLI fallback is what makes detection work on hosts where +/// Podman is functional but the socket is somewhere else. pub fn detect_podman_socket() -> Option { detect_podman_socket_from_candidates(&podman_socket_candidates()) + .or_else(discover_podman_socket) } fn detect_podman_socket_from_candidates(candidates: &[PathBuf]) -> Option { @@ -226,6 +234,339 @@ fn detect_podman_socket_from_candidates(candidates: &[PathBuf]) -> Option` with a bounded deadline, returning captured stdout on a +/// successful exit. Returns `None` on spawn failure, non-zero exit, or timeout. +fn run_podman_capture(args: &[&str]) -> Option> { + run_bounded_command("podman", args, PODMAN_DISCOVERY_TIMEOUT) +} + +/// Run `program ` with a deadline, capturing stdout. +/// +/// Unlike `Command::output()`, which blocks until the child exits, the deadline +/// is absolute: the call returns within `timeout` no matter what the probe or +/// its descendants do. A Podman probe can leave a daemonized descendant (an SSH +/// multiplexer, `gvproxy`, etc.) that inherited the stdout pipe, so +/// `read_to_end` would otherwise wait for EOF forever even after the direct +/// child exits — and such a descendant may even have escaped the probe's +/// process group. To stay bounded, the deadline covers both waiting for the +/// child and draining its stdout; on expiry the call best-effort kills the +/// process group (cleaning up in-group descendants) and gives up immediately, +/// abandoning the reader thread rather than waiting on it again. The abandoned +/// reader exits on its own once the pipe finally closes. Returns the captured +/// stdout only on a successful exit whose output was fully drained within the +/// deadline; otherwise `None`. +fn run_bounded_command(program: &str, args: &[&str], timeout: Duration) -> Option> { + use std::io::Read as _; + use std::sync::mpsc; + + let mut command = Command::new(program); + command + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + // Run the probe as its own process-group leader so in-group descendants that + // inherited the stdout pipe can be terminated as a group on timeout. + set_new_process_group(&mut command); + let mut child = command.spawn().ok()?; + + // Drain stdout on a separate thread so a child that fills the pipe buffer + // cannot deadlock against the polling loop below. The reader reports through + // a channel so the drain can be bounded by the deadline and abandoned if it + // outlives it. + let mut stdout = child.stdout.take()?; + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = stdout.read_to_end(&mut buf); + let _ = tx.send(buf); + }); + + let deadline = Instant::now() + timeout; + + // Wait for the direct child to exit, bounded by the deadline. + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) => { + if Instant::now() >= deadline { + break None; + } + std::thread::sleep(PODMAN_DISCOVERY_POLL_INTERVAL); + } + Err(_) => break None, + } + }; + + // The child never exited within the deadline: kill the group, reap the + // (now-killed) direct child, and give up. `wait()` is bounded because the + // direct child is dead. + let Some(status) = status else { + terminate_process_group(&mut child); + let _ = child.wait(); + return None; + }; + + // The direct child exited (already reaped by `try_wait`). Collect its stdout + // without ever blocking past the deadline. A surviving descendant — possibly + // one that escaped the process group — can hold the pipe open indefinitely, + // so on expiry best-effort kill the group for cleanup and return None rather + // than waiting on the reader again. + let remaining = deadline.saturating_duration_since(Instant::now()); + match rx.recv_timeout(remaining) { + Ok(stdout) if status.success() => Some(stdout), + Ok(_) => None, + Err(_) => { + terminate_process_group(&mut child); + None + } + } +} + +/// Configure `command` to start its child as a new process-group leader so the +/// group can be signaled as a unit. No-op on non-Unix platforms. +#[cfg(unix)] +fn set_new_process_group(command: &mut Command) { + use std::os::unix::process::CommandExt as _; + command.process_group(0); +} + +#[cfg(not(unix))] +fn set_new_process_group(_command: &mut Command) {} + +/// Kill the child's whole process group so daemonized descendants that inherited +/// the stdout pipe are terminated too. Falls back to killing just the child. +#[cfg(unix)] +fn terminate_process_group(child: &mut std::process::Child) { + // `set_new_process_group` made the child a group leader, so its PID doubles + // as the group ID; signaling the negated PID targets the entire group. The + // group stays valid while a descendant is alive, so this reaches survivors + // even after the leader has been reaped. + let raw_pid = i32::try_from(child.id()).unwrap_or(i32::MAX); + let pgid = nix::unistd::Pid::from_raw(-raw_pid); + let _ = nix::sys::signal::kill(pgid, nix::sys::signal::Signal::SIGKILL); + let _ = child.kill(); +} + +#[cfg(not(unix))] +fn terminate_process_group(child: &mut std::process::Child) { + let _ = child.kill(); +} + +/// Query the Podman CLI to discover the host-side API socket path. +/// +/// Strategy: +/// 1. Run `podman info --format json` to check connectivity and whether +/// the service is remote (macOS/Windows VM) or local (native Linux). +/// 2. If `CONTAINER_HOST` explicitly points at a Unix socket, `podman info` +/// just connected through it — use that path directly (a raw unix:// URL +/// has no machine to inspect and reports the VM-internal socket). +/// 3. If `serviceIsRemote` is true, run `podman machine inspect` to get +/// the host-side forwarded socket (the `remoteSocket` from `podman info` +/// is the VM-internal path, which is not reachable from the host). +/// 4. If `serviceIsRemote` is false, use `remoteSocket.path` directly +/// (on native Linux this IS the real local socket). +fn discover_podman_socket() -> Option { + let stdout = run_podman_capture(&["info", "--format", "json"])?; + + // podman info succeeded, so an explicit unix:// CONTAINER_HOST is the exact + // working host-side socket. This must be checked before the machine path, + // which cannot map a raw unix:// endpoint to a machine. + if let Some(path) = explicit_unix_container_host() { + return Some(path); + } + + let info: serde_json::Value = serde_json::from_slice(&stdout).ok()?; + let is_remote = info["host"]["serviceIsRemote"].as_bool().unwrap_or(false); + + if is_remote { + discover_podman_machine_socket() + } else { + parse_podman_info_socket(&info) + } +} + +/// Return the socket path when `CONTAINER_HOST` is an explicit `unix://` URL. +/// +/// Honors Podman's precedence: `CONTAINER_CONNECTION` outranks `CONTAINER_HOST`, +/// so a set `CONTAINER_CONNECTION` means `podman info` did not use +/// `CONTAINER_HOST` and this returns `None`. +fn explicit_unix_container_host() -> Option { + if env_var_nonempty("CONTAINER_CONNECTION").is_some() { + return None; + } + let host = env_var_nonempty("CONTAINER_HOST")?; + unix_url_socket_path(&host) +} + +/// Parse the socket path from a `unix://` URL, or `None` for other schemes. +fn unix_url_socket_path(url: &str) -> Option { + let path = url.trim().strip_prefix("unix://")?; + (!path.is_empty()).then(|| PathBuf::from(path)) +} + +/// Extract the socket path from `podman info` JSON output. +/// Used on native Linux where `remoteSocket.path` is the real local socket. +fn parse_podman_info_socket(info: &serde_json::Value) -> Option { + let path_str = info["host"]["remoteSocket"]["path"].as_str()?; + let path = path_str.strip_prefix("unix://").unwrap_or(path_str); + if path.is_empty() { + return None; + } + Some(PathBuf::from(path)) +} + +/// Which Podman machine `podman info` connected through. +/// +/// Podman resolves its endpoint (highest precedence first) from +/// `CONTAINER_CONNECTION` (a named connection), then `CONTAINER_HOST` (a URL), +/// then the default connection in `containers.conf`. +#[derive(Debug, PartialEq, Eq)] +enum ActiveMachine { + /// An explicit selector (`CONTAINER_CONNECTION`, or `CONTAINER_HOST` mapped + /// to a connection by URL) named this connection. It must match a machine + /// exactly; guessing another machine would connect to the wrong socket. + Explicit(String), + /// An explicit `CONTAINER_HOST` is set but maps to no known connection + /// (e.g. a plain remote server, not a local machine). The active machine + /// cannot be determined and must not be guessed. + UnresolvedExplicit, + /// No explicit selector; the `containers.conf` default connection name, if + /// any. When absent, Podman's built-in default machine is inspected by name. + Default(Option), +} + +/// Run `podman machine inspect ` to discover the host-side forwarded +/// socket. Used on macOS/Windows where the Podman service runs inside a VM. +/// +/// The active machine is resolved first and inspected *by name*: a no-argument +/// `podman machine inspect` inspects only `podman-machine-default`, so a host +/// whose default connection is a different machine would otherwise be pointed +/// at the wrong machine's socket. When the active machine cannot be mapped to a +/// name, this returns `None` rather than substituting an unrelated machine. +fn discover_podman_machine_socket() -> Option { + let targets = podman_machine_inspect_targets(&active_podman_machine())?; + targets.iter().find_map(|name| { + let stdout = run_podman_capture(&["machine", "inspect", name])?; + let machines: serde_json::Value = serde_json::from_slice(&stdout).ok()?; + parse_podman_machine_inspect_socket(&machines) + }) +} + +/// Machine names to try with `podman machine inspect`, most specific first. +/// +/// `None` means the active machine cannot be determined; inspection must not +/// guess, since picking an unrelated machine would return the wrong socket. A +/// rootful connection is named `-root` while the machine itself is +/// ``, so the `-root`-stripped name is offered as a fallback. +fn podman_machine_inspect_targets(active: &ActiveMachine) -> Option> { + fn names_for(connection: &str) -> Vec { + let mut names = vec![connection.to_string()]; + if let Some(stripped) = connection.strip_suffix("-root") + && !stripped.is_empty() + { + names.push(stripped.to_string()); + } + names + } + + match active { + ActiveMachine::Explicit(name) | ActiveMachine::Default(Some(name)) => Some(names_for(name)), + ActiveMachine::UnresolvedExplicit => None, + // No explicit selector and no default connection: `podman info` used + // Podman's built-in default machine, so inspect it by name rather than + // guessing an arbitrary entry. + ActiveMachine::Default(None) => Some(vec!["podman-machine-default".to_string()]), + } +} + +/// Determine which machine `podman info` connected through. +fn active_podman_machine() -> ActiveMachine { + if let Some(name) = env_var_nonempty("CONTAINER_CONNECTION") { + return ActiveMachine::Explicit(name); + } + let container_host = env_var_nonempty("CONTAINER_HOST"); + resolve_active_podman_machine(container_host.as_deref(), podman_connection_list().as_ref()) +} + +/// Resolve the active machine from `CONTAINER_HOST` and the connection list. +/// +/// `CONTAINER_CONNECTION` is handled by the caller (it needs no connection +/// list). This is split out as a pure function for testing. +fn resolve_active_podman_machine( + container_host: Option<&str>, + connections: Option<&serde_json::Value>, +) -> ActiveMachine { + if let Some(host) = container_host { + return connections + .and_then(|c| podman_connection_name_for_uri(c, host)) + .map_or(ActiveMachine::UnresolvedExplicit, ActiveMachine::Explicit); + } + ActiveMachine::Default(connections.and_then(parse_default_podman_connection)) +} + +fn env_var_nonempty(key: &str) -> Option { + std::env::var(key) + .ok() + .filter(|value| !value.trim().is_empty()) +} + +/// Run `podman system connection list --format json`. +fn podman_connection_list() -> Option { + let stdout = run_podman_capture(&["system", "connection", "list", "--format", "json"])?; + serde_json::from_slice(&stdout).ok() +} + +/// Extract the default machine connection name from +/// `podman system connection list --format json`. +fn parse_default_podman_connection(connections: &serde_json::Value) -> Option { + connections + .as_array()? + .iter() + .find(|c| { + c["Default"].as_bool().unwrap_or(false) && c["IsMachine"].as_bool().unwrap_or(false) + }) + .and_then(|c| c["Name"].as_str()) + .map(str::to_string) +} + +/// Find the machine connection whose URI matches `CONTAINER_HOST`. +/// +/// Only machine connections (`IsMachine: true`) map to a local socket, so a +/// `CONTAINER_HOST` pointing at a plain remote server yields `None`. +fn podman_connection_name_for_uri(connections: &serde_json::Value, uri: &str) -> Option { + connections + .as_array()? + .iter() + .find(|c| c["IsMachine"].as_bool().unwrap_or(false) && c["URI"].as_str() == Some(uri)) + .and_then(|c| c["Name"].as_str()) + .map(str::to_string) +} + +/// Extract the host-side socket path from a `podman machine inspect ` +/// JSON array (which contains only the inspected machine). +fn parse_podman_machine_inspect_socket(machines: &serde_json::Value) -> Option { + let machine = machines.as_array()?.first()?; + let path_str = machine["ConnectionInfo"]["PodmanSocket"]["Path"].as_str()?; + if path_str.is_empty() { + return None; + } + Some(PathBuf::from(path_str)) +} + fn podman_socket_candidates() -> Vec { let socket = std::env::var("OPENSHELL_PODMAN_SOCKET") .ok() @@ -1088,12 +1429,15 @@ const fn default_ssh_session_ttl_secs() -> u64 { #[cfg(test)] mod tests { use super::{ - ComputeDriverKind, Config, DEFAULT_SERVICE_ROUTING_DOMAIN, GatewayInterceptorBindingPolicy, - GatewayInterceptorConfig, GatewayInterceptorFailurePolicy, GatewayJwtConfig, - GatewayProviderProfileSourceConfig, PolicyValidationFailureMode, + ActiveMachine, ComputeDriverKind, Config, DEFAULT_SERVICE_ROUTING_DOMAIN, + GatewayInterceptorBindingPolicy, GatewayInterceptorConfig, GatewayInterceptorFailurePolicy, + GatewayJwtConfig, GatewayProviderProfileSourceConfig, PolicyValidationFailureMode, detect_docker_socket_from_candidates, detect_driver, detect_podman_socket_from_candidates, - docker_host_unix_socket_path, docker_socket_responds, normalize_compute_driver_name, - podman_socket_candidates_from_env, podman_socket_responds, + docker_host_unix_socket_path, docker_socket_responds, explicit_unix_container_host, + normalize_compute_driver_name, parse_default_podman_connection, parse_podman_info_socket, + parse_podman_machine_inspect_socket, podman_connection_name_for_uri, + podman_machine_inspect_targets, podman_socket_candidates_from_env, podman_socket_responds, + resolve_active_podman_machine, run_bounded_command, unix_url_socket_path, }; #[cfg(unix)] use super::{is_reachable_unix_socket, is_unix_socket}; @@ -1104,6 +1448,8 @@ mod tests { use std::os::unix::net::UnixListener; use std::path::PathBuf; use std::time::Duration; + #[cfg(unix)] + use std::time::Instant; #[test] fn compute_driver_kind_parses_supported_values() { @@ -1595,6 +1941,23 @@ mod tests { ); } + #[test] + fn parse_podman_info_socket_extracts_linux_local_socket() { + let info: serde_json::Value = serde_json::json!({ + "host": { + "serviceIsRemote": false, + "remoteSocket": { + "path": "unix:///run/user/1000/podman/podman.sock", + "exists": true + } + } + }); + assert_eq!( + parse_podman_info_socket(&info), + Some(PathBuf::from("/run/user/1000/podman/podman.sock")) + ); + } + #[test] fn supervisor_image_tag_sanitizes_build_metadata_for_oci() { use super::resolve_supervisor_image_tag; @@ -1608,6 +1971,22 @@ mod tests { ); } + #[test] + fn parse_podman_info_socket_handles_path_without_unix_prefix() { + let info: serde_json::Value = serde_json::json!({ + "host": { + "remoteSocket": { + "path": "/run/user/1000/podman/podman.sock", + "exists": true + } + } + }); + assert_eq!( + parse_podman_info_socket(&info), + Some(PathBuf::from("/run/user/1000/podman/podman.sock")) + ); + } + #[test] fn default_supervisor_image_is_version_pinned() { use super::default_supervisor_image; @@ -1616,4 +1995,348 @@ mod tests { let tag = image.rsplit_once(':').unwrap().1; assert!(!tag.is_empty()); } + + #[test] + fn parse_podman_info_socket_returns_none_for_missing_path() { + let info: serde_json::Value = serde_json::json!({ + "host": { + "remoteSocket": {} + } + }); + assert_eq!(parse_podman_info_socket(&info), None); + } + + #[test] + fn parse_podman_info_socket_returns_none_for_empty_path() { + let info: serde_json::Value = serde_json::json!({ + "host": { + "remoteSocket": { + "path": "", + "exists": false + } + } + }); + assert_eq!(parse_podman_info_socket(&info), None); + } + + #[test] + fn parse_podman_machine_inspect_socket_extracts_macos_socket() { + // `podman machine inspect ` returns only the inspected machine. + let machines: serde_json::Value = serde_json::json!([ + { + "ConnectionInfo": { + "PodmanSocket": { + "Path": "/var/folders/1q/jx7s14b928n8zvstgfk98lj00000gn/T/podman/podman-machine-default-api.sock" + }, + "PodmanPipe": null + }, + "Name": "podman-machine-default" + } + ]); + assert_eq!( + parse_podman_machine_inspect_socket(&machines), + Some(PathBuf::from( + "/var/folders/1q/jx7s14b928n8zvstgfk98lj00000gn/T/podman/podman-machine-default-api.sock" + )) + ); + } + + #[test] + fn parse_podman_machine_inspect_socket_returns_none_for_empty_array() { + let machines: serde_json::Value = serde_json::json!([]); + assert_eq!(parse_podman_machine_inspect_socket(&machines), None); + } + + #[test] + fn parse_podman_machine_inspect_socket_returns_none_for_missing_socket() { + let machines: serde_json::Value = serde_json::json!([ + { + "ConnectionInfo": {}, + "Name": "podman-machine-default" + } + ]); + assert_eq!(parse_podman_machine_inspect_socket(&machines), None); + } + + #[test] + fn podman_machine_inspect_targets_uses_explicit_machine_by_name() { + // The active connection points at `work`; discovery must inspect `work` + // explicitly rather than the no-argument default machine, which would + // return a different machine's socket. + assert_eq!( + podman_machine_inspect_targets(&ActiveMachine::Explicit("work".to_string())), + Some(vec!["work".to_string()]) + ); + } + + #[test] + fn podman_machine_inspect_targets_strips_rootful_suffix() { + // Rootful connections are named `-root`; the machine itself is + // ``, offered as a fallback after the connection name. + assert_eq!( + podman_machine_inspect_targets(&ActiveMachine::Explicit("work-root".to_string())), + Some(vec!["work-root".to_string(), "work".to_string()]) + ); + } + + #[test] + fn podman_machine_inspect_targets_uses_default_connection_name() { + assert_eq!( + podman_machine_inspect_targets(&ActiveMachine::Default(Some("work".to_string()))), + Some(vec!["work".to_string()]) + ); + } + + #[test] + fn podman_machine_inspect_targets_falls_back_to_builtin_default() { + // No explicit selector and no default connection: inspect Podman's own + // built-in default machine by name. + assert_eq!( + podman_machine_inspect_targets(&ActiveMachine::Default(None)), + Some(vec!["podman-machine-default".to_string()]) + ); + } + + #[test] + fn podman_machine_inspect_targets_does_not_guess_for_unresolved_explicit() { + // CONTAINER_HOST pointing at a non-machine endpoint cannot be mapped to + // a machine; discovery must not guess an unrelated one. + assert_eq!( + podman_machine_inspect_targets(&ActiveMachine::UnresolvedExplicit), + None + ); + } + + #[cfg(unix)] + #[test] + fn run_bounded_command_captures_stdout_on_success() { + assert_eq!( + run_bounded_command("printf", &["hello"], Duration::from_secs(5)), + Some(b"hello".to_vec()) + ); + } + + #[cfg(unix)] + #[test] + fn run_bounded_command_returns_none_on_nonzero_exit() { + assert_eq!( + run_bounded_command("false", &[], Duration::from_secs(5)), + None + ); + } + + #[cfg(unix)] + #[test] + fn run_bounded_command_kills_child_that_exceeds_deadline() { + // A process that would otherwise block startup indefinitely must be + // bounded: `run_bounded_command` returns within the deadline instead of + // hanging until the child exits. + let start = Instant::now(); + let result = run_bounded_command("sleep", &["30"], Duration::from_millis(200)); + let elapsed = start.elapsed(); + assert_eq!(result, None); + assert!( + elapsed < Duration::from_secs(5), + "bounded command did not return promptly: {elapsed:?}" + ); + } + + #[cfg(unix)] + #[test] + fn run_bounded_command_bounds_drain_when_in_group_descendant_holds_stdout() { + // The shell exits immediately after `echo`, but the backgrounded child + // (in the same process group) inherits and holds the stdout pipe open. + // Without a bounded drain, `read_to_end` would wait ~30s for EOF even + // though the direct child already exited. + let start = Instant::now(); + let result = run_bounded_command( + "sh", + &["-c", "sleep 30 & echo done"], + Duration::from_millis(300), + ); + let elapsed = start.elapsed(); + assert!( + elapsed < Duration::from_secs(2), + "drain blocked on a descendant holding stdout: {elapsed:?}" + ); + // Draining hit the deadline, so the probe is treated as "not found". + assert_eq!(result, None); + } + + #[cfg(unix)] + #[test] + fn run_bounded_command_bounds_drain_when_descendant_escapes_process_group() { + // `set -m` runs the background job in its OWN process group, so it + // survives the group kill while still holding the stdout pipe. The + // deadline must remain absolute: the call must not fall back to an + // untimed receive that waits for the escaped descendant's EOF. + let start = Instant::now(); + let result = run_bounded_command( + "bash", + &["-c", "set -m; sleep 5 & echo done"], + Duration::from_millis(300), + ); + let elapsed = start.elapsed(); + // A regression (blocking receive after the timeout) would wait ~5s for + // the escaped `sleep`; the bounded implementation returns promptly. + assert!( + elapsed < Duration::from_secs(2), + "drain blocked on a descendant that escaped the process group: {elapsed:?}" + ); + assert_eq!(result, None); + } + + #[cfg(unix)] + #[test] + fn run_bounded_command_returns_none_for_missing_program() { + assert_eq!( + run_bounded_command( + "openshell-nonexistent-binary-xyz", + &[], + Duration::from_secs(5) + ), + None + ); + } + + #[test] + fn resolve_active_podman_machine_maps_container_host_to_connection() { + let connections: serde_json::Value = serde_json::json!([ + { "Name": "work", "IsMachine": true, "Default": false, + "URI": "ssh://core@127.0.0.1:5555/run/user/1000/podman/podman.sock" }, + { "Name": "podman-machine-default", "IsMachine": true, "Default": true, + "URI": "ssh://core@127.0.0.1:4444/run/user/1000/podman/podman.sock" } + ]); + // CONTAINER_HOST pointing at the non-default machine's URI resolves to + // that machine, not the default. + assert_eq!( + resolve_active_podman_machine( + Some("ssh://core@127.0.0.1:5555/run/user/1000/podman/podman.sock"), + Some(&connections) + ), + ActiveMachine::Explicit("work".to_string()) + ); + } + + #[test] + fn resolve_active_podman_machine_unmatched_host_is_unresolved() { + let connections: serde_json::Value = serde_json::json!([ + { "Name": "podman-machine-default", "IsMachine": true, "Default": true, + "URI": "ssh://core@127.0.0.1:4444/run/user/1000/podman/podman.sock" } + ]); + // A CONTAINER_HOST that matches no machine connection is unresolved, + // never silently mapped to the default machine. + assert_eq!( + resolve_active_podman_machine(Some("tcp://192.0.2.10:2375"), Some(&connections)), + ActiveMachine::UnresolvedExplicit + ); + } + + #[test] + fn resolve_active_podman_machine_defaults_without_host() { + let connections: serde_json::Value = serde_json::json!([ + { "Name": "podman-machine-default", "IsMachine": true, "Default": true, + "URI": "ssh://core@127.0.0.1:4444/run/user/1000/podman/podman.sock" } + ]); + assert_eq!( + resolve_active_podman_machine(None, Some(&connections)), + ActiveMachine::Default(Some("podman-machine-default".to_string())) + ); + } + + #[test] + fn podman_connection_name_for_uri_ignores_non_machine_matches() { + let connections: serde_json::Value = serde_json::json!([ + { "Name": "remote", "IsMachine": false, "Default": false, + "URI": "tcp://192.0.2.10:2375" } + ]); + // A URI match against a non-machine connection does not map to a local + // machine socket. + assert_eq!( + podman_connection_name_for_uri(&connections, "tcp://192.0.2.10:2375"), + None + ); + } + + #[test] + fn unix_url_socket_path_parses_unix_urls() { + assert_eq!( + unix_url_socket_path("unix:///run/user/1000/podman/podman.sock"), + Some(PathBuf::from("/run/user/1000/podman/podman.sock")) + ); + // Non-unix schemes and empty paths are not sockets. + assert_eq!(unix_url_socket_path("ssh://core@127.0.0.1:22/x"), None); + assert_eq!(unix_url_socket_path("tcp://127.0.0.1:2375"), None); + assert_eq!(unix_url_socket_path("unix://"), None); + } + + #[test] + #[allow(unsafe_code)] // std::env::set_var/remove_var require unsafe in Rust 2024 + fn explicit_unix_container_host_honors_scheme_and_precedence() { + fn set(key: &str, value: Option<&str>) { + unsafe { + match value { + Some(v) => std::env::set_var(key, v), + None => std::env::remove_var(key), + } + } + } + + let original_host = std::env::var("CONTAINER_HOST").ok(); + let original_connection = std::env::var("CONTAINER_CONNECTION").ok(); + + // A unix:// CONTAINER_HOST with no CONTAINER_CONNECTION is used directly. + set("CONTAINER_CONNECTION", None); + set("CONTAINER_HOST", Some("unix:///tmp/podman/custom.sock")); + assert_eq!( + explicit_unix_container_host(), + Some(PathBuf::from("/tmp/podman/custom.sock")) + ); + + // CONTAINER_CONNECTION outranks CONTAINER_HOST. + set("CONTAINER_CONNECTION", Some("work")); + assert_eq!(explicit_unix_container_host(), None); + + // A non-unix CONTAINER_HOST is not a direct socket. + set("CONTAINER_CONNECTION", None); + set( + "CONTAINER_HOST", + Some("ssh://core@127.0.0.1:5555/run/podman.sock"), + ); + assert_eq!(explicit_unix_container_host(), None); + + // Nothing set. + set("CONTAINER_HOST", None); + assert_eq!(explicit_unix_container_host(), None); + + set("CONTAINER_HOST", original_host.as_deref()); + set("CONTAINER_CONNECTION", original_connection.as_deref()); + } + + #[test] + fn parse_default_podman_connection_picks_default_machine() { + let connections: serde_json::Value = serde_json::json!([ + { "Name": "podman-machine-default", "IsMachine": true, "Default": true }, + { "Name": "podman-machine-default-root", "IsMachine": true, "Default": false } + ]); + assert_eq!( + parse_default_podman_connection(&connections), + Some("podman-machine-default".to_string()) + ); + } + + #[test] + fn parse_default_podman_connection_ignores_non_machine_and_missing_default() { + // Default connection that is not a machine is ignored. + let non_machine: serde_json::Value = serde_json::json!([ + { "Name": "remote-host", "IsMachine": false, "Default": true } + ]); + assert_eq!(parse_default_podman_connection(&non_machine), None); + + // No default at all. + let no_default: serde_json::Value = serde_json::json!([ + { "Name": "work", "IsMachine": true, "Default": false } + ]); + assert_eq!(parse_default_podman_connection(&no_default), None); + } } diff --git a/crates/openshell-driver-podman/README.md b/crates/openshell-driver-podman/README.md index f8890b00d1..b0436634ee 100644 --- a/crates/openshell-driver-podman/README.md +++ b/crates/openshell-driver-podman/README.md @@ -374,7 +374,7 @@ Podman resources after out-of-band container removal or label drift. | Environment Variable | CLI Flag | Default | Description | |---|---|---|---| -| `OPENSHELL_PODMAN_SOCKET` | `--podman-socket` | Probes known local Podman API sockets and uses the first responsive socket. Fails to start if none respond. | Podman API Unix socket path. | +| `OPENSHELL_PODMAN_SOCKET` | `--podman-socket` | Probes known local Podman API sockets and uses the first responsive socket, then falls back to asking the `podman` CLI for the host-side socket. Fails to start if neither finds one. | Podman API Unix socket path. | | `OPENSHELL_SANDBOX_IMAGE` | `--sandbox-image` | From gateway config | Default OCI image for sandboxes. | | `OPENSHELL_SANDBOX_IMAGE_PULL_POLICY` | `--sandbox-image-pull-policy` | `missing` | Pull policy: `always`, `missing`, `never`, or `newer`. | | `OPENSHELL_GRPC_ENDPOINT` | `--grpc-endpoint` | Auto-detected via `host.containers.internal` | Gateway gRPC endpoint for sandbox callbacks. | diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index d96f141cc8..b4c2cfd9dd 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -16,6 +16,7 @@ mod sidecar_control; use miette::{IntoDiagnostic, Result, WrapErr}; use std::future::Future; +use std::pin::Pin; use std::sync::Arc; #[cfg(target_os = "linux")] use std::sync::atomic::Ordering; @@ -62,6 +63,7 @@ use openshell_core::policy::{NetworkMode, NetworkPolicy, ProxyPolicy, SandboxPol use openshell_core::proposals::AgentProposals; use openshell_core::provider_credentials::ProviderCredentialState; use openshell_supervisor_network::opa::OpaEngine; +use openshell_supervisor_network::proxy::ProxyHandle; use openshell_supervisor_process::process::ProcessEnforcementMode; pub use openshell_supervisor_process::process::{ProcessHandle, ProcessStatus}; use openshell_supervisor_process::skills; @@ -514,7 +516,7 @@ pub async fn run_sandbox( // API read the current value so proposals target the correct workspace. let (workspace_tx, workspace_rx) = tokio::sync::watch::channel(String::new()); - let networking = if network_enabled { + let mut networking = if network_enabled { #[cfg(target_os = "linux")] let proxy_bind_ip = netns .as_ref() @@ -823,6 +825,19 @@ pub async fn run_sandbox( .zip(bootstrap.proxy_ca_bundle_path.clone()) }); + let proxy_exited: Pin + Send>> = if let Some(rx) = networking + .as_mut() + .and_then(|n| n.proxy.as_mut()) + .and_then(ProxyHandle::take_exit_receiver) + { + Box::pin(async { + let _ = rx.await; + }) + } else { + Box::pin(std::future::pending()) + }; + tokio::pin!(proxy_exited); + let exit_code = if process_enabled { let ca_file_paths = networking .as_ref() @@ -935,9 +950,41 @@ pub async fn run_sandbox( "authoritative network-sidecar control channel closed" )); } + () = &mut proxy_exited => { + ocsf_emit!( + AppLifecycleBuilder::new(ocsf_ctx()) + .activity(ActivityId::Fail) + .severity(SeverityId::High) + .status(StatusId::Failure) + .message( + "Proxy accept loop exited unexpectedly; terminating sandbox" + ) + .build() + ); + return Err(miette::miette!( + "proxy accept loop exited unexpectedly" + )); + } } } else { - process.await? + tokio::select! { + result = process => result?, + () = &mut proxy_exited => { + ocsf_emit!( + AppLifecycleBuilder::new(ocsf_ctx()) + .activity(ActivityId::Fail) + .severity(SeverityId::High) + .status(StatusId::Failure) + .message( + "Proxy accept loop exited unexpectedly; terminating sandbox" + ) + .build() + ); + return Err(miette::miette!( + "proxy accept loop exited unexpectedly" + )); + } + } } } else { // Network-only sidecar mode: keep the proxy and its background @@ -953,15 +1000,62 @@ pub async fn run_sandbox( warn!(?result, "Authoritative sidecar control channel exited; restarting sidecar"); 1 } + () = &mut proxy_exited => { + ocsf_emit!( + AppLifecycleBuilder::new(ocsf_ctx()) + .activity(ActivityId::Fail) + .severity(SeverityId::High) + .status(StatusId::Failure) + .message( + "Proxy accept loop exited unexpectedly; terminating sandbox" + ) + .build() + ); + return Err(miette::miette!( + "proxy accept loop exited unexpectedly" + )); + } } } else { - wait_for_shutdown_signal().await; - 0 + tokio::select! { + () = wait_for_shutdown_signal() => 0, + () = &mut proxy_exited => { + ocsf_emit!( + AppLifecycleBuilder::new(ocsf_ctx()) + .activity(ActivityId::Fail) + .severity(SeverityId::High) + .status(StatusId::Failure) + .message( + "Proxy accept loop exited unexpectedly; terminating sandbox" + ) + .build() + ); + return Err(miette::miette!( + "proxy accept loop exited unexpectedly" + )); + } + } } #[cfg(not(target_os = "linux"))] { - wait_for_shutdown_signal().await; - 0 + tokio::select! { + () = wait_for_shutdown_signal() => 0, + () = &mut proxy_exited => { + ocsf_emit!( + AppLifecycleBuilder::new(ocsf_ctx()) + .activity(ActivityId::Fail) + .severity(SeverityId::High) + .status(StatusId::Failure) + .message( + "Proxy accept loop exited unexpectedly; terminating sandbox" + ) + .build() + ); + return Err(miette::miette!( + "proxy accept loop exited unexpectedly" + )); + } + } } }; @@ -3157,7 +3251,7 @@ type MiddlewareConnector = Arc< dyn Fn( Vec, MiddlewareAuthentication, - ) -> std::pin::Pin< + ) -> Pin< Box< dyn std::future::Future< Output = Result, diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 7ca5f339d5..51f05a395c 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -3980,10 +3980,24 @@ fn derive_phase(status: Option<&DriverSandboxStatus>) -> SandboxPhase { return SandboxPhase::Deleting; } - if status.conditions.iter().any(|condition| { - condition.r#type.eq_ignore_ascii_case("Suspended") + // `Ready=True` means the sandbox is usable through this gateway and must + // win over a `Suspended=True` condition. Agent Sandbox v1beta1 sets + // `Suspended=True (PodTerminated)` on stop and does not clear it on resume, + // so a resumed CR carries both `Ready=True` and a stale `Suspended=True`. + // Treating any `Suspended=True` as Stopped would pin the resumed sandbox at + // Starting forever (issue #2932). A genuine stop leaves `Ready` unset or + // False, so `Suspended` still resolves to Stopped in that case. + let ready = status.conditions.iter().any(|condition| { + condition.r#type.eq_ignore_ascii_case("Ready") && condition.status.eq_ignore_ascii_case("true") - }) { + }); + + if !ready + && status.conditions.iter().any(|condition| { + condition.r#type.eq_ignore_ascii_case("Suspended") + && condition.status.eq_ignore_ascii_case("true") + }) + { return SandboxPhase::Stopped; } @@ -6458,6 +6472,56 @@ mod tests { assert_eq!(current.phase(), SandboxPhase::Stopped as i32); } + #[tokio::test] + async fn resumed_v1beta1_snapshot_with_stale_suspended_reaches_ready() { + // Reproduces issue #2932: on Agent Sandbox v1beta1 a resumed CR reports + // Ready=True (DependenciesReady) alongside a stale Suspended=True + // (PodTerminated). Starting from the Starting phase that `start` sets, the + // reconciled sandbox must advance to Ready rather than being pinned at + // Starting by the stale Suspended condition. + let runtime = test_runtime(Arc::new(TestDriver::default())).await; + let sandbox = sandbox_record("sb-resumed", "sandbox-resumed", SandboxPhase::Starting); + runtime.store.put_message(&sandbox).await.unwrap(); + register_test_supervisor_session(&runtime, sandbox.object_id()); + + let mut resumed = ready_driver_sandbox(sandbox.object_id(), sandbox.object_name()); + resumed.status = Some(DriverSandboxStatus { + sandbox_name: sandbox.object_name().to_string(), + instance_id: format!("{}-pod", sandbox.object_name()), + conditions: vec![ + DriverCondition { + r#type: "Ready".to_string(), + status: "True".to_string(), + reason: "DependenciesReady".to_string(), + message: "Sandbox is ready".to_string(), + last_transition_time: String::new(), + }, + DriverCondition { + r#type: "Suspended".to_string(), + status: "True".to_string(), + reason: "PodTerminated".to_string(), + message: "Pod terminated".to_string(), + last_transition_time: String::new(), + }, + ], + ..Default::default() + }); + + runtime.apply_sandbox_update(resumed).await.unwrap(); + + let current = runtime + .store + .get_message::(sandbox.object_id()) + .await + .unwrap() + .unwrap(); + assert_eq!( + current.phase(), + SandboxPhase::Ready as i32, + "a resumed, Ready sandbox must not stay Starting because of a stale Suspended condition" + ); + } + #[tokio::test] async fn stopped_container_snapshot_cannot_error_stopped_sandbox() { let runtime = test_runtime(Arc::new(TestDriver::default())).await; diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index e20edc055f..c8c8149a82 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -4755,10 +4755,11 @@ mod tests { ImportProviderProfilesRequest, L7Allow, L7Rule, LintProviderProfilesRequest, ListProviderProfilesRequest, ListProvidersRequest, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProviderCredentialRefresh, ProviderCredentialRefreshMaterial, - ProviderCredentialTokenGrant, ProviderCredentialTokenGrantAudienceOverride, - ProviderProfile, ProviderProfileCategory, ProviderProfileCredential, - ProviderProfileImportItem, RotateProviderCredentialRequest, Sandbox, SandboxPolicy, - SandboxSpec, StoredProviderProfile, UpdateProviderProfilesRequest, UpdateProviderRequest, + ProviderCredentialRefreshRecoveryAction, ProviderCredentialTokenGrant, + ProviderCredentialTokenGrantAudienceOverride, ProviderProfile, ProviderProfileCategory, + ProviderProfileCredential, ProviderProfileImportItem, RotateProviderCredentialRequest, + Sandbox, SandboxPolicy, SandboxSpec, StoredProviderProfile, UpdateProviderProfilesRequest, + UpdateProviderRequest, }; use openshell_core::{ObjectId, ObjectName}; use tonic::{Code, Request}; @@ -11988,7 +11989,16 @@ mod tests { .await .unwrap() .expect("refresh state should exist"); - assert_eq!(refresh_state.status, "error"); + assert_eq!(refresh_state.status, "configuration_required"); + assert_eq!( + refresh_state.recovery_action, + ProviderCredentialRefreshRecoveryAction::FixConfiguration as i32 + ); + assert_eq!(refresh_state.failure_code, "refresh_configuration_invalid"); + assert_eq!( + refresh_state.next_refresh_at_ms - refresh_state.last_error_at_ms, + 60 * 60 * 1000 + ); } #[tokio::test] diff --git a/crates/openshell-server/src/provider_refresh.rs b/crates/openshell-server/src/provider_refresh.rs index f562e1d18e..176f86ae22 100644 --- a/crates/openshell-server/src/provider_refresh.rs +++ b/crates/openshell-server/src/provider_refresh.rs @@ -9,7 +9,8 @@ use crate::credentials::RefreshMaterialScope; use crate::persistence::{ObjectType, PersistenceError, Store, WriteCondition, current_time_ms}; use openshell_core::ObjectWorkspace; use openshell_core::proto::{ - CredentialHandle, Provider, ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, + CredentialHandle, Provider, ProviderCredentialRefreshRecoveryAction, + ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, StoredProviderCredentialRefreshState, StoredRefreshMaterialDeletion, }; use openshell_core::{ObjectId, ObjectName, SetResourceVersion}; @@ -17,13 +18,15 @@ use prost::Message; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::time::Duration; -use tonic::Status; +use tonic::{Code, Status}; use tracing::{info, warn}; const DEFAULT_REFRESH_BEFORE_SECONDS: i64 = 300; const DEFAULT_MAX_LIFETIME_SECONDS: i64 = 3600; const REFRESH_ERROR_RETRY_SECONDS: i64 = 60; +const REFRESH_CONFIGURATION_RETRY_SECONDS: i64 = 60 * 60; const REFRESH_WORKER_PAGE_SIZE: u32 = 1000; +const MAX_OAUTH_ERROR_RESPONSE_BYTES: usize = 8 * 1024; pub fn refresh_material_scope( state: &StoredProviderCredentialRefreshState, @@ -321,6 +324,10 @@ pub fn refresh_status_from_state( next_refresh_at_ms: state.next_refresh_at_ms, last_refresh_at_ms: state.last_refresh_at_ms, last_error: state.last_error.clone(), + recovery_action: state.recovery_action, + failure_code: state.failure_code.clone(), + provider_error_subtype: state.provider_error_subtype.clone(), + last_error_at_ms: state.last_error_at_ms, } } @@ -385,6 +392,10 @@ pub fn new_refresh_state( authorization_epoch: uuid::Uuid::new_v4().to_string(), secret_material_handles: HashMap::new(), pending_secret_deletions: Vec::new(), + recovery_action: ProviderCredentialRefreshRecoveryAction::Unspecified as i32, + failure_code: String::new(), + provider_error_subtype: String::new(), + last_error_at_ms: 0, }) } @@ -403,6 +414,130 @@ struct TokenResponse { refresh_token: Option, } +#[derive(Debug, Deserialize)] +struct OAuthErrorResponse { + error: String, + #[serde(default, deserialize_with = "deserialize_optional_oauth_string")] + error_subtype: Option, +} + +fn deserialize_optional_oauth_string<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + let value = serde_json::Value::deserialize(deserializer)?; + Ok(value.as_str().map(str::to_owned)) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum OAuthGrantKind { + UserRefreshToken, + NonInteractive, +} + +#[derive(Debug)] +struct RefreshFailure { + status: Status, + recovery_action: ProviderCredentialRefreshRecoveryAction, + failure_code: &'static str, + provider_error_subtype: Option<&'static str>, + retry_schedule: RefreshRetrySchedule, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RefreshRetrySchedule { + Short, + Configuration, + Parked, +} + +impl RefreshFailure { + fn retryable(status: Status, failure_code: &'static str) -> Self { + Self { + status, + recovery_action: ProviderCredentialRefreshRecoveryAction::Retry, + failure_code, + provider_error_subtype: None, + retry_schedule: RefreshRetrySchedule::Short, + } + } + + fn investigate(status: Status, failure_code: &'static str) -> Self { + Self { + status, + recovery_action: ProviderCredentialRefreshRecoveryAction::Investigate, + failure_code, + provider_error_subtype: None, + retry_schedule: RefreshRetrySchedule::Short, + } + } + + fn reauthorize( + status: Status, + failure_code: &'static str, + provider_error_subtype: Option<&'static str>, + ) -> Self { + Self { + status, + recovery_action: ProviderCredentialRefreshRecoveryAction::Reauthorize, + failure_code, + provider_error_subtype, + retry_schedule: RefreshRetrySchedule::Parked, + } + } + + fn fix_configuration(status: Status, failure_code: &'static str) -> Self { + Self { + status, + recovery_action: ProviderCredentialRefreshRecoveryAction::FixConfiguration, + failure_code, + provider_error_subtype: None, + retry_schedule: RefreshRetrySchedule::Configuration, + } + } + + fn fix_configuration_with_subtype( + status: Status, + failure_code: &'static str, + provider_error_subtype: &'static str, + ) -> Self { + Self { + status, + recovery_action: ProviderCredentialRefreshRecoveryAction::FixConfiguration, + failure_code, + provider_error_subtype: Some(provider_error_subtype), + retry_schedule: RefreshRetrySchedule::Configuration, + } + } + + fn into_status(self) -> Status { + self.status + } + + fn from_status(status: &Status) -> Self { + Self::from(Status::new(status.code(), status.message().to_string())) + } +} + +impl From for RefreshFailure { + fn from(status: Status) -> Self { + match status.code() { + Code::InvalidArgument + | Code::FailedPrecondition + | Code::PermissionDenied + | Code::Unauthenticated => { + Self::fix_configuration(status, "refresh_configuration_invalid") + } + Code::Unavailable + | Code::DeadlineExceeded + | Code::ResourceExhausted + | Code::Aborted + | Code::Internal => Self::retryable(status, "refresh_failed"), + _ => Self::investigate(status, "refresh_failed"), + } + } +} + #[derive(Debug, Serialize)] struct GoogleServiceAccountClaims<'a> { iss: &'a str, @@ -554,17 +689,51 @@ async fn cleanup_pending_secret_deletions( Ok(new_version) } -async fn persist_refresh_error_state( +async fn persist_retryable_refresh_error_state( store: &Store, state: &mut StoredProviderCredentialRefreshState, expected_version: u64, error: &Status, +) -> Result { + let failure = RefreshFailure::retryable( + Status::new(error.code(), error.message().to_string()), + "refresh_failed", + ); + persist_refresh_failure_state(store, state, expected_version, &failure).await +} + +async fn persist_refresh_failure_state( + store: &Store, + state: &mut StoredProviderCredentialRefreshState, + expected_version: u64, + failure: &RefreshFailure, ) -> Result { let now_ms = current_time_ms(); - state.status = "error".to_string(); - state.last_error = error.message().to_string(); - state.next_refresh_at_ms = - now_ms.saturating_add(REFRESH_ERROR_RETRY_SECONDS.saturating_mul(1000)); + state.status = match failure.recovery_action { + ProviderCredentialRefreshRecoveryAction::Retry + | ProviderCredentialRefreshRecoveryAction::Unspecified => "error", + ProviderCredentialRefreshRecoveryAction::Reauthorize => "reauthorization_required", + ProviderCredentialRefreshRecoveryAction::FixConfiguration => "configuration_required", + ProviderCredentialRefreshRecoveryAction::Investigate => "investigation_required", + } + .to_string(); + state.last_error = failure.status.message().to_string(); + state.recovery_action = failure.recovery_action as i32; + state.failure_code = failure.failure_code.to_string(); + state.provider_error_subtype = failure + .provider_error_subtype + .unwrap_or_default() + .to_string(); + state.last_error_at_ms = now_ms; + state.next_refresh_at_ms = match failure.retry_schedule { + RefreshRetrySchedule::Short => { + now_ms.saturating_add(REFRESH_ERROR_RETRY_SECONDS.saturating_mul(1000)) + } + RefreshRetrySchedule::Configuration => { + now_ms.saturating_add(REFRESH_CONFIGURATION_RETRY_SECONDS.saturating_mul(1000)) + } + RefreshRetrySchedule::Parked => i64::MAX, + }; let new_version = persist_refresh_state_if_current(store, state, expected_version) .await? .ok_or_else(|| { @@ -670,7 +839,8 @@ pub async fn refresh_provider_credential( // Otherwise disabling providers_v2_enabled leaves already-configured refresh // states that the worker and manual rotation keep minting from. if let Err(err) = ensure_refresh_providers_v2_gate(store, &state).await { - persist_refresh_error_state(store, &mut state, expected_version, &err).await?; + let failure = RefreshFailure::from_status(&err); + persist_refresh_failure_state(store, &mut state, expected_version, &failure).await?; warn!( provider = %state.provider_name, credential_key = %state.credential_key, @@ -684,7 +854,7 @@ pub async fn refresh_provider_credential( let mint_result = match resolve_refresh_material(Some(credentials), &state).await { Ok(transient_state) => mint_credential(&transient_state).await, - Err(err) => Err(err), + Err(err) => Err(err.into()), }; match mint_result { Ok(minted) => { @@ -716,19 +886,32 @@ pub async fn refresh_provider_credential( { Ok(handles) => handles, Err(store_err) => { - let err = Status::failed_precondition(format!( - "the OAuth provider rotated the refresh token, but the replacement could not be stored; the grant must be re-authorized: {}", - store_err.message() - )); - persist_refresh_error_state(store, &mut state, expected_version, &err) - .await?; - return Err(err); + let failure = RefreshFailure::reauthorize( + Status::failed_precondition(format!( + "the OAuth provider rotated the refresh token, but the replacement could not be stored; the grant must be re-authorized: {}", + store_err.message() + )), + "oauth_rotated_refresh_token_store_failed", + None, + ); + persist_refresh_failure_state( + store, + &mut state, + expected_version, + &failure, + ) + .await?; + return Err(failure.into_status()); } }; let Some(handle) = staged_refresh_token_handles.get("refresh_token").cloned() else { - let err = Status::failed_precondition( - "the OAuth provider rotated the refresh token, but the credential driver returned no replacement handle; the grant must be re-authorized", + let failure = RefreshFailure::reauthorize( + Status::failed_precondition( + "the OAuth provider rotated the refresh token, but the credential driver returned no replacement handle; the grant must be re-authorized", + ), + "oauth_rotated_refresh_token_handle_missing", + None, ); cleanup_staged_refresh_material_handles( credentials, @@ -736,8 +919,9 @@ pub async fn refresh_provider_credential( &staged_refresh_token_handles, ) .await; - persist_refresh_error_state(store, &mut state, expected_version, &err).await?; - return Err(err); + persist_refresh_failure_state(store, &mut state, expected_version, &failure) + .await?; + return Err(failure.into_status()); }; if let Some(previous) = state .secret_material_handles @@ -757,6 +941,10 @@ pub async fn refresh_provider_credential( state.last_refresh_at_ms = now_ms; state.status = "refreshed".to_string(); state.last_error.clear(); + state.recovery_action = ProviderCredentialRefreshRecoveryAction::Unspecified as i32; + state.failure_code.clear(); + state.provider_error_subtype.clear(); + state.last_error_at_ms = 0; // Claim the refresh generation with a version-matched write BEFORE // touching the provider. It succeeds only if the refresh still holds @@ -800,7 +988,13 @@ pub async fn refresh_provider_credential( // upstream-valid grant. If that also fails, leave the // staged object intact for operator recovery rather than // deleting an irreplaceable rotated token. - persist_refresh_error_state(store, &mut state, expected_version, &err).await?; + persist_retryable_refresh_error_state( + store, + &mut state, + expected_version, + &err, + ) + .await?; return Err(err); } }; @@ -819,7 +1013,8 @@ pub async fn refresh_provider_credential( { // Reflect the failure on the state we just wrote; skip silently // if it was deleted concurrently (it is not recreated). - persist_refresh_error_state(store, &mut state, new_version, &err).await?; + let failure = RefreshFailure::from_status(&err); + persist_refresh_failure_state(store, &mut state, new_version, &failure).await?; warn!( provider = %state.provider_name, credential_key = %state.credential_key, @@ -860,9 +1055,9 @@ pub async fn refresh_provider_credential( } Ok(state) } - Err(err) => { + Err(failure) => { let now_ms = current_time_ms(); - persist_refresh_error_state(store, &mut state, expected_version, &err).await?; + persist_refresh_failure_state(store, &mut state, expected_version, &failure).await?; warn!( provider = %state.provider_name, credential_key = %state.credential_key, @@ -870,10 +1065,12 @@ pub async fn refresh_provider_credential( status = %state.status, next_refresh_at_ms = state.next_refresh_at_ms, seconds_until_refresh = seconds_until_ms(now_ms, state.next_refresh_at_ms), - error = %err, + recovery_action = ?failure.recovery_action, + failure_code = failure.failure_code, + error = %failure.status, "provider credential refresh errored" ); - Err(err) + Err(failure.into_status()) } } } @@ -1106,7 +1303,7 @@ async fn ensure_refresh_providers_v2_gate( async fn mint_credential( state: &StoredProviderCredentialRefreshState, -) -> Result { +) -> Result { let strategy = ProviderCredentialRefreshStrategy::try_from(state.strategy) .unwrap_or(ProviderCredentialRefreshStrategy::Unspecified); match strategy { @@ -1126,13 +1323,14 @@ async fn mint_credential( | ProviderCredentialRefreshStrategy::Static | ProviderCredentialRefreshStrategy::Unspecified => Err(Status::failed_precondition( format!("refresh strategy '{strategy:?}' cannot be minted by the gateway"), - )), + ) + .into()), } } async fn mint_oauth2_refresh_token( state: &StoredProviderCredentialRefreshState, -) -> Result { +) -> Result { let token_url = oauth2_token_url(state)?; let client_id = required_material(&state.material, "client_id")?; let refresh_token = required_material(&state.material, "refresh_token")?; @@ -1149,12 +1347,18 @@ async fn mint_oauth2_refresh_token( form.push(("scope".to_string(), scope)); } - request_token(&token_url, &form, state.max_lifetime_seconds).await + request_token( + &token_url, + &form, + state.max_lifetime_seconds, + OAuthGrantKind::UserRefreshToken, + ) + .await } async fn mint_oauth2_client_credentials( state: &StoredProviderCredentialRefreshState, -) -> Result { +) -> Result { let token_url = oauth2_token_url(state)?; let client_id = required_material(&state.material, "client_id")?; let client_secret = required_material(&state.material, "client_secret")?; @@ -1168,14 +1372,19 @@ async fn mint_oauth2_client_credentials( form.push(("scope".to_string(), scope)); } - request_token(&token_url, &form, state.max_lifetime_seconds).await + request_token( + &token_url, + &form, + state.max_lifetime_seconds, + OAuthGrantKind::NonInteractive, + ) + .await } async fn mint_google_service_account_jwt( state: &StoredProviderCredentialRefreshState, -) -> Result { +) -> Result { crate::install_jsonwebtoken_crypto_provider(); - let token_url = google_token_url(state); let client_email = required_material(&state.material, "client_email")?; let private_key = required_material(&state.material, "private_key")?; @@ -1183,7 +1392,8 @@ async fn mint_google_service_account_jwt( if scopes.is_empty() { return Err(Status::invalid_argument( "google_service_account_jwt requires at least one scope", - )); + ) + .into()); } let now_ms = current_time_ms(); let now_secs = now_ms / 1000; @@ -1216,12 +1426,18 @@ async fn mint_google_service_account_jwt( ), ("assertion".to_string(), assertion), ]; - request_token(&token_url, &form, lifetime_secs).await + request_token( + &token_url, + &form, + lifetime_secs, + OAuthGrantKind::NonInteractive, + ) + .await } async fn mint_aws_sts_assume_role( state: &StoredProviderCredentialRefreshState, -) -> Result { +) -> Result { let role_arn = required_material(&state.material, "role_arn")?; let session_name = material_value(&state.material, &["session_name"]) .unwrap_or_else(|| "openshell-sandbox".to_string()); @@ -1256,13 +1472,15 @@ async fn mint_aws_sts_assume_role( (None, None) if session_token.is_some() => { return Err(Status::invalid_argument( "aws_session_token requires aws_access_key_id and aws_secret_access_key", - )); + ) + .into()); } (None, None) => {} _ => { return Err(Status::invalid_argument( "aws_access_key_id and aws_secret_access_key must both be set or both omitted", - )); + ) + .into()); } } @@ -1346,7 +1564,8 @@ async fn request_token( token_url: &str, form: &[(String, String)], max_lifetime_seconds: i64, -) -> Result { + grant_kind: OAuthGrantKind, +) -> Result { let parsed = reqwest::Url::parse(token_url) .map_err(|_| Status::invalid_argument("token_url must be an absolute URL"))?; match parsed.scheme() { @@ -1355,7 +1574,8 @@ async fn request_token( _ => { return Err(Status::invalid_argument( "token_url must use https, except loopback http for local tests", - )); + ) + .into()); } } @@ -1368,20 +1588,41 @@ async fn request_token( .form(form) .send() .await - .map_err(|e| Status::unavailable(format!("token endpoint request failed: {e}")))?; + .map_err(|error| { + let error_kind = if error.is_timeout() { + "timeout" + } else if error.is_connect() { + "connect" + } else if error.is_request() { + "request" + } else { + "other" + }; + warn!( + error = %error.without_url(), + error_kind, + "OAuth token endpoint request failed" + ); + RefreshFailure::retryable( + Status::unavailable("token endpoint request failed"), + "oauth_token_endpoint_unavailable", + ) + })?; let status = response.status(); if !status.is_success() { - return Err(Status::failed_precondition(format!( - "token endpoint returned HTTP {status}" - ))); + let body = read_bounded_oauth_error_body(response).await; + return Err(classify_oauth_token_error(status, &body, grant_kind)); } - let token = response - .json::() - .await - .map_err(|_| Status::failed_precondition("token endpoint returned invalid JSON"))?; + let token = response.json::().await.map_err(|_| { + RefreshFailure::investigate( + Status::failed_precondition("token endpoint returned invalid JSON"), + "oauth_invalid_success_response", + ) + })?; if token.access_token.trim().is_empty() { - return Err(Status::failed_precondition( - "token endpoint returned empty access_token", + return Err(RefreshFailure::investigate( + Status::failed_precondition("token endpoint returned empty access_token"), + "oauth_empty_access_token", )); } let now_ms = current_time_ms(); @@ -1405,6 +1646,135 @@ async fn request_token( }) } +async fn read_bounded_oauth_error_body(mut response: reqwest::Response) -> Vec { + let mut body = Vec::new(); + while body.len() < MAX_OAUTH_ERROR_RESPONSE_BYTES { + let Ok(Some(chunk)) = response.chunk().await else { + break; + }; + let remaining = MAX_OAUTH_ERROR_RESPONSE_BYTES.saturating_sub(body.len()); + body.extend_from_slice(&chunk[..chunk.len().min(remaining)]); + if chunk.len() >= remaining { + break; + } + } + body +} + +fn classify_oauth_token_error( + status: reqwest::StatusCode, + body: &[u8], + grant_kind: OAuthGrantKind, +) -> RefreshFailure { + if status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error() { + return RefreshFailure::retryable( + Status::unavailable(format!("token endpoint returned HTTP {status}")), + "oauth_token_endpoint_retryable", + ); + } + + let Ok(error_response) = serde_json::from_slice::(body) else { + return RefreshFailure::investigate( + Status::failed_precondition(format!( + "token endpoint returned HTTP {status} without a recognized OAuth error" + )), + "oauth_unrecognized_error_response", + ); + }; + + match error_response.error.as_str() { + "invalid_grant" if grant_kind == OAuthGrantKind::UserRefreshToken => { + let subtype = error_response + .error_subtype + .as_deref() + .filter(|subtype| *subtype == "invalid_rapt") + .map(|_| "invalid_rapt"); + let message = if subtype.is_some() { + "OAuth refresh grant requires interactive reauthorization (invalid_grant/invalid_rapt)" + } else { + "OAuth refresh grant is no longer usable (invalid_grant); user reauthorization is required" + }; + RefreshFailure::reauthorize( + Status::failed_precondition(message), + "oauth_invalid_grant", + subtype, + ) + } + "invalid_client" => RefreshFailure::fix_configuration( + Status::failed_precondition( + "OAuth token endpoint rejected the client configuration (invalid_client)", + ), + "oauth_invalid_client", + ), + "unauthorized_client" => RefreshFailure::fix_configuration( + Status::failed_precondition( + "OAuth token endpoint rejected the client grant (unauthorized_client)", + ), + "oauth_unauthorized_client", + ), + "invalid_scope" => RefreshFailure::fix_configuration( + Status::failed_precondition( + "OAuth token endpoint rejected the configured scopes (invalid_scope)", + ), + "oauth_invalid_scope", + ), + "unsupported_grant_type" => RefreshFailure::fix_configuration( + Status::failed_precondition( + "OAuth token endpoint rejected the configured grant type (unsupported_grant_type)", + ), + "oauth_unsupported_grant_type", + ), + "admin_policy_enforced" => RefreshFailure::fix_configuration( + Status::failed_precondition( + "OAuth access is blocked by an administrator policy (admin_policy_enforced)", + ), + "oauth_admin_policy_enforced", + ), + "access_denied" + if error_response.error_subtype.as_deref() == Some("admin_policy_enforced") => + { + RefreshFailure::fix_configuration_with_subtype( + Status::failed_precondition( + "OAuth access is blocked by an administrator policy (access_denied/admin_policy_enforced)", + ), + "oauth_admin_policy_enforced", + "admin_policy_enforced", + ) + } + "access_denied" if grant_kind == OAuthGrantKind::UserRefreshToken => { + RefreshFailure::reauthorize( + Status::failed_precondition( + "OAuth access was denied; user reauthorization is required (access_denied)", + ), + "oauth_access_denied", + None, + ) + } + "access_denied" => RefreshFailure::fix_configuration( + Status::failed_precondition( + "OAuth access was denied for the non-interactive grant (access_denied)", + ), + "oauth_access_denied", + ), + "invalid_grant" => RefreshFailure::fix_configuration( + Status::failed_precondition( + "OAuth token endpoint rejected the non-interactive grant (invalid_grant)", + ), + "oauth_invalid_grant", + ), + "server_error" | "temporarily_unavailable" => RefreshFailure::retryable( + Status::unavailable("OAuth token endpoint reported a temporary failure"), + "oauth_token_endpoint_retryable", + ), + _ => RefreshFailure::investigate( + Status::failed_precondition(format!( + "token endpoint returned HTTP {status} with an unrecognized OAuth error" + )), + "oauth_unrecognized_error", + ), + } +} + pub fn refresh_scopes(state: &StoredProviderCredentialRefreshState) -> Vec { if !state.scopes.is_empty() { return state.scopes.clone(); @@ -1677,11 +2047,13 @@ async fn run_refresh_worker_tick( #[cfg(test)] mod tests { use super::{ - NewRefreshStateConfig, delete_refresh_state_with_credentials, - effective_authorization_epoch, enqueue_pending_secret_deletion, get_refresh_state, - list_all_refresh_states, list_refresh_states_for_provider, new_refresh_state, - put_refresh_state, refresh_material_scope, refresh_provider_credential, refresh_state_name, - refresh_strategy_name, run_refresh_worker_tick, seconds_until_ms, + MAX_OAUTH_ERROR_RESPONSE_BYTES, NewRefreshStateConfig, OAuthGrantKind, RefreshFailure, + RefreshRetrySchedule, Status, classify_oauth_token_error, + delete_refresh_state_with_credentials, effective_authorization_epoch, + enqueue_pending_secret_deletion, get_refresh_state, list_all_refresh_states, + list_refresh_states_for_provider, new_refresh_state, put_refresh_state, + read_bounded_oauth_error_body, refresh_material_scope, refresh_provider_credential, + refresh_state_name, refresh_strategy_name, run_refresh_worker_tick, seconds_until_ms, validate_secret_material_references, }; use crate::credentials::CredentialRuntime; @@ -1689,7 +2061,8 @@ mod tests { use openshell_core::Config; use openshell_core::proto::datamodel::v1::ObjectMeta; use openshell_core::proto::{ - CredentialHandle, Provider, ProviderCredentialRefreshStrategy, Sandbox, SandboxSpec, + CredentialHandle, Provider, ProviderCredentialRefreshRecoveryAction, + ProviderCredentialRefreshStrategy, Sandbox, SandboxSpec, StoredProviderCredentialRefreshState, }; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; @@ -1806,6 +2179,37 @@ mod tests { assert_eq!(refresh_strategy_name(i32::MAX), "unspecified"); } + #[test] + fn local_refresh_statuses_default_to_safe_recovery_actions() { + for status in [ + Status::invalid_argument("missing material"), + Status::failed_precondition("strategy cannot be minted"), + Status::permission_denied("client is not allowed"), + ] { + let failure = RefreshFailure::from(status); + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::FixConfiguration + ); + assert_eq!(failure.failure_code, "refresh_configuration_invalid"); + assert_eq!(failure.retry_schedule, RefreshRetrySchedule::Configuration); + } + + let retry = RefreshFailure::from(Status::unavailable("temporary backend outage")); + assert_eq!( + retry.recovery_action, + ProviderCredentialRefreshRecoveryAction::Retry + ); + assert_eq!(retry.retry_schedule, RefreshRetrySchedule::Short); + + let investigate = RefreshFailure::from(Status::unknown("unclassified failure")); + assert_eq!( + investigate.recovery_action, + ProviderCredentialRefreshRecoveryAction::Investigate + ); + assert_eq!(investigate.retry_schedule, RefreshRetrySchedule::Short); + } + #[test] fn pending_secret_deletions_preserve_multiple_generations_for_one_key() { let mut state = StoredProviderCredentialRefreshState::default(); @@ -1862,6 +2266,388 @@ mod tests { validate_secret_material_references(&state).unwrap(); } + #[test] + fn oauth_invalid_grant_requires_user_reauthorization_without_exposing_description() { + let failure = classify_oauth_token_error( + reqwest::StatusCode::BAD_REQUEST, + br#"{"error":"invalid_grant","error_subtype":"invalid_rapt","error_description":"sensitive provider detail"}"#, + OAuthGrantKind::UserRefreshToken, + ); + + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::Reauthorize + ); + assert_eq!(failure.failure_code, "oauth_invalid_grant"); + assert_eq!(failure.provider_error_subtype, Some("invalid_rapt")); + assert_eq!(failure.retry_schedule, RefreshRetrySchedule::Parked); + assert!( + failure + .status + .message() + .contains("interactive reauthorization") + ); + assert!( + !failure + .status + .message() + .contains("sensitive provider detail") + ); + } + + #[test] + fn oauth_invalid_grant_ignores_non_string_optional_subtype() { + let failure = classify_oauth_token_error( + reqwest::StatusCode::BAD_REQUEST, + br#"{"error":"invalid_grant","error_subtype":{"vendor":"value"}}"#, + OAuthGrantKind::UserRefreshToken, + ); + + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::Reauthorize + ); + assert_eq!(failure.failure_code, "oauth_invalid_grant"); + assert_eq!(failure.provider_error_subtype, None); + assert_eq!(failure.retry_schedule, RefreshRetrySchedule::Parked); + } + + #[test] + fn oauth_noninteractive_invalid_grant_requires_configuration_fix() { + let failure = classify_oauth_token_error( + reqwest::StatusCode::BAD_REQUEST, + br#"{"error":"invalid_grant"}"#, + OAuthGrantKind::NonInteractive, + ); + + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::FixConfiguration + ); + assert_eq!(failure.failure_code, "oauth_invalid_grant"); + assert_eq!(failure.retry_schedule, RefreshRetrySchedule::Configuration); + } + + #[test] + fn oauth_admin_policy_subtype_requires_configuration_fix() { + let failure = classify_oauth_token_error( + reqwest::StatusCode::BAD_REQUEST, + br#"{"error":"access_denied","error_subtype":"admin_policy_enforced"}"#, + OAuthGrantKind::UserRefreshToken, + ); + + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::FixConfiguration + ); + assert_eq!(failure.failure_code, "oauth_admin_policy_enforced"); + assert_eq!( + failure.provider_error_subtype, + Some("admin_policy_enforced") + ); + assert_eq!(failure.retry_schedule, RefreshRetrySchedule::Configuration); + } + + #[test] + fn oauth_access_denied_recovery_depends_on_grant_kind() { + let user_failure = classify_oauth_token_error( + reqwest::StatusCode::FORBIDDEN, + br#"{"error":"access_denied"}"#, + OAuthGrantKind::UserRefreshToken, + ); + assert_eq!( + user_failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::Reauthorize + ); + assert_eq!(user_failure.failure_code, "oauth_access_denied"); + assert_eq!(user_failure.retry_schedule, RefreshRetrySchedule::Parked); + + let service_failure = classify_oauth_token_error( + reqwest::StatusCode::FORBIDDEN, + br#"{"error":"access_denied"}"#, + OAuthGrantKind::NonInteractive, + ); + assert_eq!( + service_failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::FixConfiguration + ); + assert_eq!(service_failure.failure_code, "oauth_access_denied"); + assert_eq!( + service_failure.retry_schedule, + RefreshRetrySchedule::Configuration + ); + } + + #[test] + fn oauth_server_failure_remains_retryable() { + let failure = classify_oauth_token_error( + reqwest::StatusCode::SERVICE_UNAVAILABLE, + br#"{"error":"invalid_grant"}"#, + OAuthGrantKind::UserRefreshToken, + ); + + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::Retry + ); + assert_eq!(failure.failure_code, "oauth_token_endpoint_retryable"); + assert_eq!(failure.retry_schedule, RefreshRetrySchedule::Short); + } + + #[test] + fn unrecognized_oauth_error_requests_investigation_without_echoing_body() { + let failure = classify_oauth_token_error( + reqwest::StatusCode::BAD_REQUEST, + br#"{"error":"vendor_secret_error","error_description":"do not expose me"}"#, + OAuthGrantKind::UserRefreshToken, + ); + + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::Investigate + ); + assert_eq!(failure.failure_code, "oauth_unrecognized_error"); + assert_eq!(failure.retry_schedule, RefreshRetrySchedule::Short); + assert!(!failure.status.message().contains("vendor_secret_error")); + assert!(!failure.status.message().contains("do not expose me")); + } + + #[test] + fn html_and_malformed_oauth_errors_are_investigated_without_echoing_body() { + for body in [b"issuer failure".as_slice(), b"{".as_slice()] { + let failure = classify_oauth_token_error( + reqwest::StatusCode::BAD_REQUEST, + body, + OAuthGrantKind::UserRefreshToken, + ); + + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::Investigate + ); + assert_eq!(failure.failure_code, "oauth_unrecognized_error_response"); + assert!(!failure.status.message().contains("issuer failure")); + } + } + + #[tokio::test] + async fn oversized_oauth_error_body_is_bounded_and_investigated() { + let mock_server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/oversized")) + .respond_with(ResponseTemplate::new(400).set_body_bytes(vec![ + b'x'; + MAX_OAUTH_ERROR_RESPONSE_BYTES + + 512 + ])) + .mount(&mock_server) + .await; + + let response = reqwest::get(format!("{}/oversized", mock_server.uri())) + .await + .unwrap(); + let status = response.status(); + let body = read_bounded_oauth_error_body(response).await; + assert_eq!(body.len(), MAX_OAUTH_ERROR_RESPONSE_BYTES); + + let failure = classify_oauth_token_error(status, &body, OAuthGrantKind::UserRefreshToken); + assert_eq!( + failure.recovery_action, + ProviderCredentialRefreshRecoveryAction::Investigate + ); + assert_eq!(failure.failure_code, "oauth_unrecognized_error_response"); + } + + #[tokio::test] + async fn invalid_local_oauth_configuration_retries_hourly() { + let store = test_store().await; + let provider = provider("invalid-local-config", "outlook"); + store.put_message(&provider).await.unwrap(); + let state = new_refresh_state( + &provider, + "default", + "MS_GRAPH_ACCESS_TOKEN", + NewRefreshStateConfig { + strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken, + material: HashMap::from([ + ("client_id".to_string(), "client-id".to_string()), + ("refresh_token".to_string(), "refresh-token".to_string()), + ]), + secret_material_keys: vec!["refresh_token".to_string()], + expires_at_ms: 0, + token_url: "not-an-absolute-url".to_string(), + scopes: Vec::new(), + refresh_before_seconds: 30, + max_lifetime_seconds: 60, + additional_output_keys: HashMap::new(), + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let err = refresh_provider_credential( + &store, + "default", + &test_credentials(), + None, + "invalid-local-config", + "MS_GRAPH_ACCESS_TOKEN", + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), tonic::Code::InvalidArgument); + let stored = get_refresh_state( + &store, + "default", + provider.object_id(), + "MS_GRAPH_ACCESS_TOKEN", + ) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.status, "configuration_required"); + assert_eq!( + stored.recovery_action, + ProviderCredentialRefreshRecoveryAction::FixConfiguration as i32 + ); + assert_eq!(stored.failure_code, "refresh_configuration_invalid"); + assert_eq!( + stored.next_refresh_at_ms - stored.last_error_at_ms, + 60 * 60 * 1000 + ); + } + + #[tokio::test] + async fn disabled_provider_gate_requires_configuration_and_retries_hourly() { + let store = test_store().await; + let provider = provider("disabled-provider-gate", "aws-s3"); + store.put_message(&provider).await.unwrap(); + let state = new_refresh_state( + &provider, + "default", + "AWS_ACCESS_KEY_ID", + NewRefreshStateConfig { + strategy: ProviderCredentialRefreshStrategy::AwsStsAssumeRole, + material: HashMap::from([( + "role_arn".to_string(), + "arn:aws:iam::123456789012:role/test".to_string(), + )]), + secret_material_keys: Vec::new(), + expires_at_ms: 0, + token_url: String::new(), + scopes: Vec::new(), + refresh_before_seconds: 30, + max_lifetime_seconds: 60, + additional_output_keys: HashMap::new(), + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let err = refresh_provider_credential( + &store, + "default", + &test_credentials(), + None, + "disabled-provider-gate", + "AWS_ACCESS_KEY_ID", + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + let stored = + get_refresh_state(&store, "default", provider.object_id(), "AWS_ACCESS_KEY_ID") + .await + .unwrap() + .unwrap(); + assert_eq!(stored.status, "configuration_required"); + assert_eq!( + stored.recovery_action, + ProviderCredentialRefreshRecoveryAction::FixConfiguration as i32 + ); + assert_eq!(stored.failure_code, "refresh_configuration_invalid"); + assert_eq!( + stored.next_refresh_at_ms - stored.last_error_at_ms, + 60 * 60 * 1000 + ); + } + + #[tokio::test] + async fn oauth_invalid_grant_persists_terminal_reauthorization_status() { + let mock_server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/token")) + .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({ + "error": "invalid_grant", + "error_subtype": "invalid_rapt", + "error_description": "provider-controlled detail" + }))) + .mount(&mock_server) + .await; + + let store = test_store().await; + let provider = provider("expired-grant", "outlook"); + store.put_message(&provider).await.unwrap(); + let state = new_refresh_state( + &provider, + "default", + "MS_GRAPH_ACCESS_TOKEN", + NewRefreshStateConfig { + strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken, + material: HashMap::from([ + ("client_id".to_string(), "client-id".to_string()), + ( + "refresh_token".to_string(), + "expired-refresh-token".to_string(), + ), + ]), + secret_material_keys: vec!["refresh_token".to_string()], + expires_at_ms: 0, + token_url: format!("{}/token", mock_server.uri()), + scopes: Vec::new(), + refresh_before_seconds: 30, + max_lifetime_seconds: 60, + additional_output_keys: HashMap::new(), + }, + ) + .unwrap(); + put_refresh_state(&store, &state).await.unwrap(); + + let err = refresh_provider_credential( + &store, + "default", + &test_credentials(), + None, + "expired-grant", + "MS_GRAPH_ACCESS_TOKEN", + ) + .await + .unwrap_err(); + + assert_eq!(err.code(), tonic::Code::FailedPrecondition); + let stored = get_refresh_state( + &store, + "default", + provider.object_id(), + "MS_GRAPH_ACCESS_TOKEN", + ) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.status, "reauthorization_required"); + assert_eq!(stored.next_refresh_at_ms, i64::MAX); + assert_eq!( + stored.recovery_action, + ProviderCredentialRefreshRecoveryAction::Reauthorize as i32 + ); + assert_eq!(stored.failure_code, "oauth_invalid_grant"); + assert_eq!(stored.provider_error_subtype, "invalid_rapt"); + assert!(stored.last_error_at_ms > 0); + assert!(!stored.last_error.contains("provider-controlled detail")); + } + #[tokio::test] async fn oauth2_client_credentials_refresh_mints_and_persists_access_token() { let mock_server = MockServer::start().await; @@ -1884,7 +2670,7 @@ mod tests { let provider = provider("my-graph", "outlook"); store.put_message(&provider).await.unwrap(); let before_refresh_ms = current_time_ms(); - let state = new_refresh_state( + let mut state = new_refresh_state( &provider, "default", "MS_GRAPH_ACCESS_TOKEN", @@ -1904,6 +2690,12 @@ mod tests { }, ) .unwrap(); + state.status = "investigation_required".to_string(); + state.last_error = "safe prior error".to_string(); + state.recovery_action = ProviderCredentialRefreshRecoveryAction::Investigate as i32; + state.failure_code = "oauth_unrecognized_error".to_string(); + state.provider_error_subtype = "prior_subtype".to_string(); + state.last_error_at_ms = current_time_ms(); put_refresh_state(&store, &state).await.unwrap(); let authorization_epoch = state.authorization_epoch.clone(); let credentials = test_credentials(); @@ -1924,6 +2716,13 @@ mod tests { assert!(refreshed.next_refresh_at_ms > 0); assert!(refreshed.expires_at_ms <= before_refresh_ms + 120_000); assert!(refreshed.last_error.is_empty()); + assert_eq!( + refreshed.recovery_action, + ProviderCredentialRefreshRecoveryAction::Unspecified as i32 + ); + assert!(refreshed.failure_code.is_empty()); + assert!(refreshed.provider_error_subtype.is_empty()); + assert_eq!(refreshed.last_error_at_ms, 0); let stored = store .get_message_by_name::("default", "my-graph") @@ -2135,7 +2934,16 @@ mod tests { .await .unwrap() .unwrap(); - assert_eq!(stored_state.status, "error"); + assert_eq!(stored_state.status, "configuration_required"); + assert_eq!( + stored_state.recovery_action, + ProviderCredentialRefreshRecoveryAction::FixConfiguration as i32 + ); + assert_eq!(stored_state.failure_code, "refresh_configuration_invalid"); + assert_eq!( + stored_state.next_refresh_at_ms - stored_state.last_error_at_ms, + 60 * 60 * 1000 + ); assert!(stored_state.last_error.contains("MS_GRAPH_ACCESS_TOKEN")); let stored_provider = store .get_message_by_name::("default", "refreshing-graph") @@ -2366,7 +3174,7 @@ mod tests { } #[tokio::test] - async fn rotated_refresh_token_store_failure_persists_error_and_backoff() { + async fn rotated_refresh_token_store_failure_requires_reauthorization() { let mock_server = MockServer::start().await; Mock::given(method("POST")) .and(path("/token")) @@ -2415,7 +3223,6 @@ mod tests { state.material.remove("refresh_token"); put_refresh_state(&store, &state).await.unwrap(); credentials.fail_next_store(); - let before = current_time_ms(); let err = refresh_provider_credential( &store, @@ -2439,9 +3246,17 @@ mod tests { .await .unwrap() .unwrap(); - assert_eq!(stored.status, "error"); + assert_eq!(stored.status, "reauthorization_required"); assert!(stored.last_error.contains("must be re-authorized")); - assert!(stored.next_refresh_at_ms > before); + assert_eq!(stored.next_refresh_at_ms, i64::MAX); + assert_eq!( + stored.recovery_action, + ProviderCredentialRefreshRecoveryAction::Reauthorize as i32 + ); + assert_eq!( + stored.failure_code, + "oauth_rotated_refresh_token_store_failed" + ); assert_eq!(credentials.stored_credential_count(), Some(1)); assert_eq!( credentials @@ -2586,6 +3401,58 @@ mod tests { ); } + #[tokio::test] + async fn refresh_worker_skips_parked_reauthorization_state() { + let store = test_store().await; + let provider = provider("parked-refresh", "outlook"); + store.put_message(&provider).await.unwrap(); + let mut state = new_refresh_state( + &provider, + "default", + "MS_GRAPH_ACCESS_TOKEN", + NewRefreshStateConfig { + strategy: ProviderCredentialRefreshStrategy::Oauth2RefreshToken, + material: HashMap::new(), + secret_material_keys: Vec::new(), + expires_at_ms: 0, + token_url: "https://issuer.example/token".to_string(), + scopes: Vec::new(), + refresh_before_seconds: 30, + max_lifetime_seconds: 60, + additional_output_keys: HashMap::new(), + }, + ) + .unwrap(); + state.status = "reauthorization_required".to_string(); + state.last_error = "OAuth refresh grant is no longer usable".to_string(); + state.recovery_action = ProviderCredentialRefreshRecoveryAction::Reauthorize as i32; + state.failure_code = "oauth_invalid_grant".to_string(); + state.last_error_at_ms = current_time_ms(); + state.next_refresh_at_ms = i64::MAX; + put_refresh_state(&store, &state).await.unwrap(); + + run_refresh_worker_tick(&store, Some(&test_credentials()), None) + .await + .unwrap(); + + let stored = get_refresh_state( + &store, + "default", + provider.object_id(), + "MS_GRAPH_ACCESS_TOKEN", + ) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.status, "reauthorization_required"); + assert_eq!(stored.next_refresh_at_ms, i64::MAX); + assert_eq!(stored.failure_code, "oauth_invalid_grant"); + assert_eq!( + stored.recovery_action, + ProviderCredentialRefreshRecoveryAction::Reauthorize as i32 + ); + } + #[tokio::test] async fn refresh_worker_finalizes_tombstoned_refresh_material() { let store = test_store().await; diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index bc3ad8b3db..dc2736a4ea 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -228,11 +228,11 @@ impl InferenceContext { } } -#[derive(Debug)] pub struct ProxyHandle { #[allow(dead_code)] http_addr: Option, join: JoinHandle<()>, + exited_rx: Option>, } impl ProxyHandle { @@ -337,7 +337,13 @@ impl ProxyHandle { ocsf_emit!(event); } + let (exited_tx, exited_rx) = tokio::sync::oneshot::channel::<()>(); let join = tokio::spawn(async move { + // Hold the sender for the lifetime of this task — when the task + // exits (panic, abort, or loop break), the sender drops and the + // receiver fires, notifying the sandbox that the proxy is gone. + let _proxy_exit_guard = exited_tx; + // Wait for the OPA engine's symlink resolution reload to complete // before accepting connections. This prevents requests from // observing a generation transition mid-flight, which would cause @@ -422,23 +428,36 @@ impl ProxyHandle { }); } Err(err) => { - let outcome = handle_accept_error( + match classify_accept_error( &err, &mut consecutive_resource_errors, &mut consecutive_unknown_errors, - ); - - let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Fail) - .severity(outcome.severity) - .status(StatusId::Failure) - .message(outcome.message) - .build(); - ocsf_emit!(event); - - match outcome.backoff { - Some(backoff) => tokio::time::sleep(backoff).await, - None => break, + ) { + AcceptAction::Terminal => { + let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Fail) + .severity(SeverityId::High) + .status(StatusId::Failure) + .message(format!( + "Proxy accept loop exiting on terminal error: {err}", + )) + .build(); + ocsf_emit!(event); + break; + } + AcceptAction::Retry { backoff, severity } => { + let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Fail) + .severity(severity) + .status(StatusId::Failure) + .message(format!( + "Proxy accept error (retrying in {}ms): {err}", + backoff.as_millis(), + )) + .build(); + ocsf_emit!(event); + tokio::time::sleep(backoff).await; + } } } } @@ -448,6 +467,7 @@ impl ProxyHandle { Ok(Self { http_addr: Some(local_addr), join, + exited_rx: Some(exited_rx), }) } @@ -455,6 +475,10 @@ impl ProxyHandle { pub const fn http_addr(&self) -> Option { self.http_addr } + + pub fn take_exit_receiver(&mut self) -> Option> { + self.exited_rx.take() + } } impl Drop for ProxyHandle { @@ -972,142 +996,106 @@ fn emit_transparent_policy_denial( ); } -fn emit_activity(tx: &Option, denied: bool, deny_group: &'static str) { - if let Some(tx) = tx { - let _ = try_record_activity(tx, denied, deny_group); - } -} +const MAX_CONSECUTIVE_UNKNOWN_ACCEPT_ERRORS: u32 = 10; -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum AcceptErrorClass { - Transient, +#[derive(Debug, PartialEq)] +enum AcceptAction { Terminal, - Unknown, + Retry { + backoff: std::time::Duration, + severity: SeverityId, + }, } -#[cfg(unix)] -fn classify_accept_error(err: &std::io::Error) -> AcceptErrorClass { - match err.raw_os_error() { - Some( - libc::EMFILE - | libc::ENFILE - | libc::ENOBUFS - | libc::ENOMEM - | libc::ECONNABORTED - | libc::ECONNRESET - | libc::EINTR - | libc::ENETDOWN - | libc::EPROTO - | libc::ENOPROTOOPT - | libc::EHOSTDOWN - | libc::EHOSTUNREACH - | libc::EOPNOTSUPP - | libc::ENETUNREACH - | libc::ENOSR - | libc::ESOCKTNOSUPPORT - | libc::EPROTONOSUPPORT - | libc::ETIMEDOUT, - ) => AcceptErrorClass::Transient, - #[cfg(target_os = "linux")] - Some(libc::ENONET) => AcceptErrorClass::Transient, - Some(libc::EBADF | libc::EINVAL | libc::ENOTSOCK) => AcceptErrorClass::Terminal, - _ => AcceptErrorClass::Unknown, - } -} - -#[cfg(not(unix))] -fn classify_accept_error(_err: &std::io::Error) -> AcceptErrorClass { - AcceptErrorClass::Unknown -} - -#[cfg(unix)] -fn is_resource_pressure_error(err: &std::io::Error) -> bool { - matches!( +fn classify_accept_error( + err: &std::io::Error, + consecutive_resource_errors: &mut u32, + consecutive_unknown_errors: &mut u32, +) -> AcceptAction { + #[cfg(unix)] + if matches!( err.raw_os_error(), - Some(libc::EMFILE | libc::ENFILE | libc::ENOBUFS | libc::ENOMEM | libc::ENOSR) - ) -} + Some(libc::EBADF | libc::EINVAL | libc::ENOTSOCK) + ) { + return AcceptAction::Terminal; + } -#[cfg(not(unix))] -fn is_resource_pressure_error(_err: &std::io::Error) -> bool { - false -} + #[cfg(unix)] + if matches!( + err.raw_os_error(), + Some( + libc::EMFILE + | libc::ENFILE + | libc::ENOBUFS + | libc::ENOMEM + | libc::ECONNABORTED + | libc::ECONNRESET + | libc::EINTR + | libc::ENETDOWN + | libc::EPROTO + | libc::ENOPROTOOPT + | libc::EHOSTDOWN + | libc::EHOSTUNREACH + | libc::EOPNOTSUPP + | libc::ENETUNREACH + | libc::ENOSR + | libc::ESOCKTNOSUPPORT + | libc::EPROTONOSUPPORT + | libc::ETIMEDOUT + ) + ) { + *consecutive_unknown_errors = 0; + + #[cfg(unix)] + let is_resource_pressure = matches!( + err.raw_os_error(), + Some(libc::EMFILE | libc::ENFILE | libc::ENOBUFS | libc::ENOMEM | libc::ENOSR) + ); + #[cfg(not(unix))] + let is_resource_pressure = false; + + if is_resource_pressure { + *consecutive_resource_errors = consecutive_resource_errors.saturating_add(1); + let backoff_ms = 100u64 + .saturating_mul(1u64 << (*consecutive_resource_errors).min(7).saturating_sub(1)) + .min(5_000); + return AcceptAction::Retry { + backoff: std::time::Duration::from_millis(backoff_ms), + severity: SeverityId::Medium, + }; + } -const ACCEPT_BACKOFF_BASE_MS: u64 = 100; -const ACCEPT_BACKOFF_MAX_MS: u64 = 5_000; -const MAX_CONSECUTIVE_UNKNOWN_ERRORS: u32 = 5; + *consecutive_resource_errors = 0; + return AcceptAction::Retry { + backoff: std::time::Duration::from_millis(100), + severity: SeverityId::Low, + }; + } -fn accept_backoff(consecutive_errors: u32) -> std::time::Duration { - let exponent = consecutive_errors.saturating_sub(1).min(7); - let ms = ACCEPT_BACKOFF_BASE_MS - .saturating_mul(1u64 << exponent) - .min(ACCEPT_BACKOFF_MAX_MS); - std::time::Duration::from_millis(ms) -} + #[cfg(unix)] + #[cfg(target_os = "linux")] + if matches!(err.raw_os_error(), Some(libc::ENONET)) { + *consecutive_unknown_errors = 0; + *consecutive_resource_errors = 0; + return AcceptAction::Retry { + backoff: std::time::Duration::from_millis(100), + severity: SeverityId::Low, + }; + } -struct AcceptErrorOutcome { - severity: SeverityId, - message: String, - backoff: Option, + *consecutive_unknown_errors = consecutive_unknown_errors.saturating_add(1); + if *consecutive_unknown_errors >= MAX_CONSECUTIVE_UNKNOWN_ACCEPT_ERRORS { + return AcceptAction::Terminal; + } + AcceptAction::Retry { + backoff: std::time::Duration::from_millis(100), + severity: SeverityId::Low, + } } -fn handle_accept_error( - err: &std::io::Error, - consecutive_resource_errors: &mut u32, - consecutive_unknown_errors: &mut u32, -) -> AcceptErrorOutcome { - let class = classify_accept_error(err); - - match class { - AcceptErrorClass::Terminal => AcceptErrorOutcome { - severity: SeverityId::High, - message: format!("Proxy accept error (terminal, exiting): {err}"), - backoff: None, - }, - AcceptErrorClass::Unknown => { - *consecutive_unknown_errors = consecutive_unknown_errors.saturating_add(1); - if *consecutive_unknown_errors > MAX_CONSECUTIVE_UNKNOWN_ERRORS { - AcceptErrorOutcome { - severity: SeverityId::High, - message: format!( - "Proxy accept error (exceeded {MAX_CONSECUTIVE_UNKNOWN_ERRORS} retries, exiting): {err}" - ), - backoff: None, - } - } else { - let backoff = accept_backoff(*consecutive_unknown_errors); - AcceptErrorOutcome { - severity: SeverityId::Medium, - message: format!( - "Proxy accept error (retry {}/{MAX_CONSECUTIVE_UNKNOWN_ERRORS} in {}ms): {err}", - *consecutive_unknown_errors, - backoff.as_millis(), - ), - backoff: Some(backoff), - } - } - } - AcceptErrorClass::Transient => { - *consecutive_unknown_errors = 0; - if is_resource_pressure_error(err) { - *consecutive_resource_errors = consecutive_resource_errors.saturating_add(1); - let backoff = accept_backoff(*consecutive_resource_errors); - AcceptErrorOutcome { - severity: SeverityId::Medium, - message: format!( - "Proxy accept error (retrying in {}ms): {err}", - backoff.as_millis(), - ), - backoff: Some(backoff), - } - } else { - AcceptErrorOutcome { - severity: SeverityId::Low, - message: format!("Proxy accept error (retrying in 100ms): {err}"), - backoff: Some(std::time::Duration::from_millis(100)), - } - } - } +fn emit_activity(tx: &Option, denied: bool, deny_group: &'static str) { + if let Some(tx) = tx { + let _ = try_record_activity(tx, denied, deny_group); } } @@ -12711,335 +12699,318 @@ network_policies: } } - #[test] - fn accept_backoff_exponential_progression() { - let ms = |n| accept_backoff(n).as_millis(); - assert_eq!(ms(1), 100); - assert_eq!(ms(2), 200); - assert_eq!(ms(3), 400); - assert_eq!(ms(4), 800); - assert_eq!(ms(5), 1_600); - assert_eq!(ms(6), 3_200); - assert_eq!(ms(7), 5_000); // 6400 capped to 5000 - assert_eq!(ms(8), 5_000); // stays at cap - } - - #[test] - fn accept_backoff_zero_consecutive_errors() { - assert_eq!(accept_backoff(0).as_millis(), 100); + #[tokio::test] + async fn test_exit_receiver_fires_when_task_exits() { + let (exited_tx, exited_rx) = tokio::sync::oneshot::channel::<()>(); + let handle = tokio::spawn(async move { + let _guard = exited_tx; + }); + handle.await.unwrap(); + // The sender was dropped when the task completed, so the receiver + // should resolve immediately with an Err (sender dropped). + assert!(exited_rx.await.is_err()); } - #[test] - fn accept_backoff_saturates_at_cap() { - assert_eq!(accept_backoff(100).as_millis(), 5_000); - assert_eq!(accept_backoff(u32::MAX).as_millis(), 5_000); + #[tokio::test] + async fn test_exit_receiver_fires_when_task_is_aborted() { + let (exited_tx, exited_rx) = tokio::sync::oneshot::channel::<()>(); + let handle = tokio::spawn(async move { + let _guard = exited_tx; + std::future::pending::<()>().await; + }); + handle.abort(); + // Abort drops the task's locals, including the sender guard. + assert!(exited_rx.await.is_err()); } - #[cfg(unix)] - #[test] - fn is_resource_pressure_detects_emfile() { - let err = std::io::Error::from_raw_os_error(libc::EMFILE); - assert!(is_resource_pressure_error(&err)); + #[tokio::test] + async fn test_take_exit_receiver_returns_real_receiver() { + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + let join = tokio::spawn(std::future::pending::<()>()); + let mut handle = ProxyHandle { + http_addr: None, + join, + exited_rx: Some(rx), + }; + let mut taken = handle + .take_exit_receiver() + .expect("first take should return Some"); + assert!(taken.try_recv().is_err()); + drop(tx); + assert!(taken.await.is_err()); } - #[cfg(unix)] - #[test] - fn is_resource_pressure_detects_enfile() { - let err = std::io::Error::from_raw_os_error(libc::ENFILE); - assert!(is_resource_pressure_error(&err)); + #[tokio::test] + async fn test_take_exit_receiver_second_call_returns_none() { + let (_tx, rx) = tokio::sync::oneshot::channel::<()>(); + let join = tokio::spawn(std::future::pending::<()>()); + let mut handle = ProxyHandle { + http_addr: None, + join, + exited_rx: Some(rx), + }; + let _first = handle.take_exit_receiver(); + assert!(handle.take_exit_receiver().is_none()); } - #[cfg(unix)] - #[test] - fn is_resource_pressure_detects_memory_pressure() { - assert!(is_resource_pressure_error( - &std::io::Error::from_raw_os_error(libc::ENOBUFS) - )); - assert!(is_resource_pressure_error( - &std::io::Error::from_raw_os_error(libc::ENOMEM) - )); - assert!(is_resource_pressure_error( - &std::io::Error::from_raw_os_error(libc::ENOSR) - )); + #[tokio::test] + async fn test_proxy_handle_drop_fires_exit_receiver() { + let (exited_tx, exited_rx) = tokio::sync::oneshot::channel::<()>(); + let join = tokio::spawn(async move { + let _guard = exited_tx; + std::future::pending::<()>().await; + }); + let mut handle = ProxyHandle { + http_addr: None, + join, + exited_rx: Some(exited_rx), + }; + let rx = handle.take_exit_receiver().expect("should return Some"); + drop(handle); + assert!(rx.await.is_err()); } - #[cfg(unix)] - #[test] - fn is_resource_pressure_rejects_other_errors() { - let err = std::io::Error::from_raw_os_error(libc::ECONNABORTED); - assert!(!is_resource_pressure_error(&err)); - } + // --- classify_accept_error tests --- #[cfg(unix)] #[test] - fn classify_accept_error_fd_exhaustion_is_transient() { - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::EMFILE)), - AcceptErrorClass::Transient, - ); + fn test_classify_terminal_error_ebadf() { + let err = std::io::Error::from_raw_os_error(libc::EBADF); + let mut fd = 0; + let mut unk = 0; assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENFILE)), - AcceptErrorClass::Transient, + classify_accept_error(&err, &mut fd, &mut unk), + AcceptAction::Terminal ); } #[cfg(unix)] #[test] - fn classify_accept_error_connection_errors_are_transient() { - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::ECONNABORTED)), - AcceptErrorClass::Transient, - ); - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::ECONNRESET)), - AcceptErrorClass::Transient, - ); + fn test_classify_terminal_error_einval() { + let err = std::io::Error::from_raw_os_error(libc::EINVAL); + let mut fd = 0; + let mut unk = 0; assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::EINTR)), - AcceptErrorClass::Transient, + classify_accept_error(&err, &mut fd, &mut unk), + AcceptAction::Terminal ); } #[cfg(unix)] #[test] - fn classify_accept_error_broken_listener_is_terminal() { - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::EBADF)), - AcceptErrorClass::Terminal, - ); - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::EINVAL)), - AcceptErrorClass::Terminal, - ); + fn test_classify_terminal_error_enotsock() { + let err = std::io::Error::from_raw_os_error(libc::ENOTSOCK); + let mut fd = 0; + let mut unk = 0; assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENOTSOCK)), - AcceptErrorClass::Terminal, + classify_accept_error(&err, &mut fd, &mut unk), + AcceptAction::Terminal ); } #[cfg(unix)] #[test] - fn classify_accept_error_unrecognized_errno_is_unknown() { - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::EPERM)), - AcceptErrorClass::Unknown, + fn test_classify_fd_exhaustion_returns_retry_medium() { + let err = std::io::Error::from_raw_os_error(libc::EMFILE); + let mut fd = 0; + let mut unk = 0; + let action = classify_accept_error(&err, &mut fd, &mut unk); + assert!( + matches!( + action, + AcceptAction::Retry { + severity: SeverityId::Medium, + .. + } + ), + "expected Retry/Medium for EMFILE, got {action:?}", ); } #[cfg(unix)] #[test] - fn handle_accept_error_terminal_exits_immediately() { - let mut res = 0; + fn test_classify_unknown_error_returns_retry_low() { + let err = std::io::Error::from_raw_os_error(libc::ECONNREFUSED); + let mut fd = 0; let mut unk = 0; - let err = std::io::Error::from_raw_os_error(libc::EBADF); - let outcome = handle_accept_error(&err, &mut res, &mut unk); - assert!(outcome.backoff.is_none()); - assert_eq!(outcome.severity, SeverityId::High); + let action = classify_accept_error(&err, &mut fd, &mut unk); + assert!( + matches!( + action, + AcceptAction::Retry { + severity: SeverityId::Low, + .. + } + ), + "expected Retry/Low for unknown error, got {action:?}", + ); } #[cfg(unix)] #[test] - fn handle_accept_error_transient_retries_indefinitely() { - let mut res = 0; + fn test_classify_fd_exhaustion_backoff_increases_and_caps() { + let mut fd = 0; let mut unk = 0; let err = std::io::Error::from_raw_os_error(libc::EMFILE); - for i in 1..=20 { - let outcome = handle_accept_error(&err, &mut res, &mut unk); - assert!(outcome.backoff.is_some(), "should retry on attempt {i}"); - assert_eq!(outcome.severity, SeverityId::Medium); + + let mut prev_backoff = std::time::Duration::ZERO; + for _ in 0..6 { + match classify_accept_error(&err, &mut fd, &mut unk) { + AcceptAction::Retry { backoff, .. } => { + assert!( + backoff > prev_backoff, + "backoff should increase: {backoff:?} <= {prev_backoff:?}", + ); + prev_backoff = backoff; + } + AcceptAction::Terminal => panic!("expected Retry, got Terminal"), + } + } + + // After enough consecutive errors the backoff should hit the 5s cap. + for _ in 6..12 { + classify_accept_error(&err, &mut fd, &mut unk); + } + match classify_accept_error(&err, &mut fd, &mut unk) { + AcceptAction::Retry { backoff, .. } => { + assert_eq!( + backoff, + std::time::Duration::from_secs(5), + "backoff should cap at 5000ms", + ); + } + AcceptAction::Terminal => panic!("expected Retry, got Terminal"), } - assert_eq!(res, 20); } #[cfg(unix)] #[test] - fn handle_accept_error_unknown_exits_after_limit() { - let mut res = 0; + fn test_classify_unknown_errors_exit_after_threshold() { + let mut fd = 0; let mut unk = 0; - let err = std::io::Error::from_raw_os_error(libc::EPERM); - for i in 1..=MAX_CONSECUTIVE_UNKNOWN_ERRORS { - let outcome = handle_accept_error(&err, &mut res, &mut unk); + let err = std::io::Error::from_raw_os_error(libc::ECONNREFUSED); + + for i in 1..MAX_CONSECUTIVE_UNKNOWN_ACCEPT_ERRORS { + let action = classify_accept_error(&err, &mut fd, &mut unk); assert!( - outcome.backoff.is_some(), - "should retry on attempt {i}/{MAX_CONSECUTIVE_UNKNOWN_ERRORS}", + matches!(action, AcceptAction::Retry { .. }), + "call {i} should be Retry, got {action:?}", ); - assert_eq!(outcome.severity, SeverityId::Medium); } - let outcome = handle_accept_error(&err, &mut res, &mut unk); - assert!( - outcome.backoff.is_none(), - "should exit after limit exceeded" + let final_action = classify_accept_error(&err, &mut fd, &mut unk); + assert_eq!( + final_action, + AcceptAction::Terminal, + "call {MAX_CONSECUTIVE_UNKNOWN_ACCEPT_ERRORS} should be Terminal", ); - assert_eq!(outcome.severity, SeverityId::High); } #[cfg(unix)] #[test] - fn handle_accept_error_transient_resets_unknown_counter() { - let mut res = 0; + fn test_classify_success_resets_counters() { + let mut fd = 0; let mut unk = 0; - let unknown_err = std::io::Error::from_raw_os_error(libc::EPERM); - let transient_err = std::io::Error::from_raw_os_error(libc::ECONNABORTED); + let err = std::io::Error::from_raw_os_error(libc::ECONNREFUSED); - // Accumulate unknowns up to the limit. - for _ in 1..=MAX_CONSECUTIVE_UNKNOWN_ERRORS { - handle_accept_error(&unknown_err, &mut res, &mut unk); + for _ in 1..MAX_CONSECUTIVE_UNKNOWN_ACCEPT_ERRORS { + classify_accept_error(&err, &mut fd, &mut unk); } - assert_eq!(unk, MAX_CONSECUTIVE_UNKNOWN_ERRORS); - // A transient error resets the unknown counter. - let outcome = handle_accept_error(&transient_err, &mut res, &mut unk); - assert!(outcome.backoff.is_some()); - assert_eq!(unk, 0); + fd = 0; + unk = 0; - // Unknown errors can retry again from zero. - let outcome = handle_accept_error(&unknown_err, &mut res, &mut unk); - assert!(outcome.backoff.is_some()); - assert_eq!(unk, 1); + for i in 1..MAX_CONSECUTIVE_UNKNOWN_ACCEPT_ERRORS { + let action = classify_accept_error(&err, &mut fd, &mut unk); + assert!( + matches!(action, AcceptAction::Retry { .. }), + "after reset, call {i} should be Retry, got {action:?}", + ); + } } #[cfg(unix)] #[test] - fn handle_accept_error_fd_exhaustion_uses_exponential_backoff() { - let mut res = 0; + fn test_classify_fd_error_resets_unknown_counter() { + let mut fd = 0; let mut unk = 0; - let err = std::io::Error::from_raw_os_error(libc::EMFILE); + let unknown_err = std::io::Error::from_raw_os_error(libc::ECONNREFUSED); + let fd_err = std::io::Error::from_raw_os_error(libc::EMFILE); - let b1 = handle_accept_error(&err, &mut res, &mut unk) - .backoff - .unwrap(); - let b2 = handle_accept_error(&err, &mut res, &mut unk) - .backoff - .unwrap(); - let b3 = handle_accept_error(&err, &mut res, &mut unk) - .backoff - .unwrap(); + for _ in 0..5 { + classify_accept_error(&unknown_err, &mut fd, &mut unk); + } - assert_eq!(b1.as_millis(), 100); - assert_eq!(b2.as_millis(), 200); - assert_eq!(b3.as_millis(), 400); + classify_accept_error(&fd_err, &mut fd, &mut unk); + + for i in 1..MAX_CONSECUTIVE_UNKNOWN_ACCEPT_ERRORS { + let action = classify_accept_error(&unknown_err, &mut fd, &mut unk); + assert!( + matches!(action, AcceptAction::Retry { .. }), + "after FD reset, call {i} should be Retry, got {action:?}", + ); + } } #[cfg(unix)] #[test] - fn classify_accept_error_network_errors_are_transient() { + fn test_classify_transient_and_terminal_are_disjoint() { + let mut res = 0; + let mut unk = 0; + for errno in [ + libc::EMFILE, + libc::ENFILE, + libc::ENOBUFS, + libc::ENOMEM, + libc::ECONNABORTED, + libc::ECONNRESET, + libc::EINTR, libc::ENETDOWN, - libc::EPROTO, - libc::ENOPROTOOPT, libc::EHOSTDOWN, libc::EHOSTUNREACH, libc::EOPNOTSUPP, libc::ENETUNREACH, - libc::ESOCKTNOSUPPORT, - libc::EPROTONOSUPPORT, + libc::ENOSR, libc::ETIMEDOUT, ] { - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(errno)), - AcceptErrorClass::Transient, - "errno {errno} should be transient", + let err = std::io::Error::from_raw_os_error(errno); + assert!( + matches!( + classify_accept_error(&err, &mut res, &mut unk), + AcceptAction::Retry { .. } + ), + "errno {errno} should be Retry", ); + res = 0; + unk = 0; } - } - #[cfg(target_os = "linux")] - #[test] - fn classify_accept_error_enonet_is_transient() { - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENONET)), - AcceptErrorClass::Transient, - ); - } - - #[cfg(unix)] - #[test] - fn classify_accept_error_resource_pressure_is_transient() { - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENOBUFS)), - AcceptErrorClass::Transient, - ); - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENOMEM)), - AcceptErrorClass::Transient, - ); - assert_eq!( - classify_accept_error(&std::io::Error::from_raw_os_error(libc::ENOSR)), - AcceptErrorClass::Transient, - ); + for errno in [libc::EBADF, libc::EINVAL, libc::ENOTSOCK] { + let err = std::io::Error::from_raw_os_error(errno); + assert_eq!( + classify_accept_error(&err, &mut res, &mut unk), + AcceptAction::Terminal, + "errno {errno} should be Terminal", + ); + } } #[cfg(unix)] #[test] - fn handle_accept_error_non_resource_transient_uses_fixed_backoff() { + fn test_transient_errors_never_hit_unknown_budget() { let mut res = 0; let mut unk = 0; let err = std::io::Error::from_raw_os_error(libc::ECONNABORTED); - let o1 = handle_accept_error(&err, &mut res, &mut unk); - let o2 = handle_accept_error(&err, &mut res, &mut unk); - - assert_eq!(o1.severity, SeverityId::Low); - assert_eq!(o1.backoff.unwrap().as_millis(), 100); - assert_eq!(o2.backoff.unwrap().as_millis(), 100); - assert_eq!(res, 0); - } - - #[cfg(unix)] - #[test] - fn handle_accept_error_unknown_uses_exponential_backoff() { - let mut res = 0; - let mut unk = 0; - let err = std::io::Error::from_raw_os_error(libc::EPERM); - - let b1 = handle_accept_error(&err, &mut res, &mut unk) - .backoff - .unwrap(); - let b2 = handle_accept_error(&err, &mut res, &mut unk) - .backoff - .unwrap(); - let b3 = handle_accept_error(&err, &mut res, &mut unk) - .backoff - .unwrap(); - - assert_eq!(b1.as_millis(), 100); - assert_eq!(b2.as_millis(), 200); - assert_eq!(b3.as_millis(), 400); - } - - #[cfg(unix)] - #[test] - fn handle_accept_error_resource_counter_persists_across_mixed_transient() { - let mut res = 0; - let mut unk = 0; - let resource_err = std::io::Error::from_raw_os_error(libc::EMFILE); - let transient_err = std::io::Error::from_raw_os_error(libc::ECONNABORTED); - - let o1 = handle_accept_error(&resource_err, &mut res, &mut unk); - assert_eq!(res, 1); - assert_eq!(o1.backoff.unwrap().as_millis(), 100); - - let o2 = handle_accept_error(&transient_err, &mut res, &mut unk); - assert_eq!(res, 1); - assert_eq!(o2.backoff.unwrap().as_millis(), 100); - - let o3 = handle_accept_error(&resource_err, &mut res, &mut unk); - assert_eq!(res, 2); - assert_eq!(o3.backoff.unwrap().as_millis(), 200); + for i in 0..(MAX_CONSECUTIVE_UNKNOWN_ACCEPT_ERRORS + 5) { + let action = classify_accept_error(&err, &mut res, &mut unk); + assert!( + matches!(action, AcceptAction::Retry { .. }), + "transient error on call {i} should always Retry, got {action:?}", + ); + } } - #[cfg(unix)] - #[test] - fn handle_accept_error_terminal_leaves_counters_unchanged() { - let mut res = 3; - let mut unk = 2; - let err = std::io::Error::from_raw_os_error(libc::EBADF); - - let outcome = handle_accept_error(&err, &mut res, &mut unk); - assert!(outcome.backoff.is_none()); - assert_eq!(res, 3); - assert_eq!(unk, 2); - } #[path = "compatibility.rs"] mod compatibility; } diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index 1619dab9fa..a5e14bcbab 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -711,6 +711,13 @@ pub struct App { pub draft_viewport_height: usize, /// When true, the detail popup is shown for the selected draft chunk. pub draft_detail_open: bool, + /// Scroll offset, in rendered rows, of the draft detail popup body. + pub draft_detail_scroll: usize, + /// Total rows of detail-popup content (set by the draw pass). + pub draft_detail_rows: usize, + /// Visible rows in the detail-popup body, excluding the pinned hint row + /// (set by the draw pass). + pub draft_detail_body_height: usize, /// Per-sandbox count of pending draft recommendations (parallel to `sandbox_names`). pub sandbox_draft_counts: Vec, @@ -1032,6 +1039,9 @@ impl App { draft_scroll: 0, draft_viewport_height: 0, draft_detail_open: false, + draft_detail_scroll: 0, + draft_detail_rows: 0, + draft_detail_body_height: 0, sandbox_draft_counts: Vec::new(), pending_draft_approve: false, pending_draft_reject: false, @@ -1648,6 +1658,7 @@ impl App { KeyCode::Esc => { self.cancel_log_stream(); self.draft_detail_open = false; + self.draft_detail_scroll = 0; self.sandbox_policy_tab = SandboxPolicyTab::Policy; self.screen = Screen::Dashboard; self.focus = Focus::Sandboxes; @@ -1856,6 +1867,25 @@ impl App { } } + /// Largest useful scroll offset for the draft detail popup. + fn draft_detail_max_scroll(&self) -> usize { + self.draft_detail_rows + .saturating_sub(self.draft_detail_body_height) + } + + /// One screenful of the draft detail popup body. + fn draft_detail_page(&self) -> isize { + isize::try_from(self.draft_detail_body_height.max(1)).unwrap_or(1) + } + + /// Move the draft detail popup by `delta` rows, clamped to the content. + fn scroll_draft_detail(&mut self, delta: isize) { + let max = isize::try_from(self.draft_detail_max_scroll()).unwrap_or(isize::MAX); + let current = isize::try_from(self.draft_detail_scroll).unwrap_or(0); + let next = current.saturating_add(delta).clamp(0, max); + self.draft_detail_scroll = usize::try_from(next).unwrap_or(0); + } + fn handle_draft_key(&mut self, key: KeyEvent) { // Approve-all confirmation modal intercepts all keys when open. if self.approve_all_confirm_open { @@ -1880,6 +1910,7 @@ impl App { match key.code { KeyCode::Esc | KeyCode::Enter => { self.draft_detail_open = false; + self.draft_detail_scroll = 0; } // Allow approve/reject toggle from within the popup. KeyCode::Char('a') => { @@ -1893,6 +1924,7 @@ impl App { if st == "pending" || st == "rejected" { self.pending_draft_approve = true; self.draft_detail_open = false; + self.draft_detail_scroll = 0; } } } @@ -1908,10 +1940,27 @@ impl App { if st == "pending" || st == "approved" { self.pending_draft_reject = true; self.draft_detail_open = false; + self.draft_detail_scroll = 0; } } } } + // Scroll the detail body; long rejection guidance and rationales + // can exceed the fixed popup height. + KeyCode::Down | KeyCode::Char('j') => self.scroll_draft_detail(1), + KeyCode::Up | KeyCode::Char('k') => self.scroll_draft_detail(-1), + KeyCode::PageDown => { + let page = self.draft_detail_page(); + self.scroll_draft_detail(page); + } + KeyCode::PageUp => { + let page = self.draft_detail_page(); + self.scroll_draft_detail(-page); + } + KeyCode::Home | KeyCode::Char('g') => self.draft_detail_scroll = 0, + KeyCode::End | KeyCode::Char('G') => { + self.draft_detail_scroll = self.draft_detail_max_scroll(); + } _ => {} } return; @@ -1937,6 +1986,7 @@ impl App { } KeyCode::Enter if !self.draft_chunks.is_empty() => { self.draft_detail_open = true; + self.draft_detail_scroll = 0; } KeyCode::Char('j') | KeyCode::Down => { if total == 0 { diff --git a/crates/openshell-tui/src/ui/mod.rs b/crates/openshell-tui/src/ui/mod.rs index 8df6dd3470..3078ff793f 100644 --- a/crates/openshell-tui/src/ui/mod.rs +++ b/crates/openshell-tui/src/ui/mod.rs @@ -103,8 +103,13 @@ fn draw_sandbox_screen(frame: &mut Frame<'_>, app: &mut App, area: Rect) { // Draft detail popup renders over the full frame. if app.focus == Focus::SandboxDraft && app.draft_detail_open { let abs = app.draft_scroll + app.draft_selected; - if let Some(chunk) = app.draft_chunks.get(abs) { - sandbox_draft::draw_detail_popup(frame, chunk, frame.size(), &app.theme); + let scroll = app.draft_detail_scroll; + let metrics = app.draft_chunks.get(abs).map(|chunk| { + sandbox_draft::draw_detail_popup(frame, chunk, frame.size(), &app.theme, scroll) + }); + if let Some(metrics) = metrics { + app.draft_detail_rows = metrics.total_rows; + app.draft_detail_body_height = metrics.body_height; } } diff --git a/crates/openshell-tui/src/ui/sandbox_draft.rs b/crates/openshell-tui/src/ui/sandbox_draft.rs index cda60d7742..470463b7d4 100644 --- a/crates/openshell-tui/src/ui/sandbox_draft.rs +++ b/crates/openshell-tui/src/ui/sandbox_draft.rs @@ -6,10 +6,10 @@ use crate::app::App; use openshell_core::proto::{L7Allow, L7DenyRule, L7QueryMatcher, NetworkEndpoint, PolicyChunk}; use ratatui::Frame; -use ratatui::layout::Rect; -use ratatui::style::Modifier; +use ratatui::layout::{Constraint, Direction, Layout, Rect}; +use ratatui::style::{Modifier, Style}; use ratatui::text::{Line, Span}; -use ratatui::widgets::{Block, Borders, Clear, Padding, Paragraph, Wrap}; +use ratatui::widgets::{Block, Borders, Clear, Padding, Paragraph}; use super::centered_rect; @@ -150,6 +150,12 @@ pub fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect) { if chunk.hit_count > 1 { spans.push(Span::styled(format!(" {}x", chunk.hit_count), t.accent)); } + if let Some(reason) = rejection_guidance(chunk) { + spans.push(Span::styled( + format!(" \"{}\"", truncate_display(reason, 32)), + t.muted, + )); + } let mut line = Line::from(spans); if is_selected { @@ -172,12 +178,22 @@ pub fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect) { // Detail popup (Enter key) // --------------------------------------------------------------------------- +/// What `draw_detail_popup` actually laid out, so the app can clamp its scroll +/// offset to content that exists. +pub struct DetailMetrics { + /// Total rows of content, after wrapping. + pub total_rows: usize, + /// Rows visible in the scrollable body, excluding the pinned hint row. + pub body_height: usize, +} + pub fn draw_detail_popup( frame: &mut Frame<'_>, chunk: &PolicyChunk, area: Rect, theme: &crate::theme::Theme, -) { + scroll: usize, +) -> DetailMetrics { let t = theme; let popup_width = (area.width * 4 / 5).min(area.width.saturating_sub(4)); let popup_height = 22u16.min(area.height.saturating_sub(4)); @@ -198,6 +214,11 @@ pub fn draw_detail_popup( .border_style(t.accent) .padding(Padding::new(1, 1, 0, 0)); + // Text columns inside the borders and the one-column padding on each side. + // Content is wrapped to this width here rather than by `Wrap`, so the row + // count below is exactly what renders and the scroll clamp stays honest. + let text_width = usize::from(popup_width).saturating_sub(4).max(1); + let mut lines: Vec> = vec![ Line::from(vec![ Span::styled("Status: ", t.muted), @@ -215,57 +236,100 @@ pub fn draw_detail_popup( ApprovalAnnotationKind::RequiresReview => t.status_warn.add_modifier(Modifier::BOLD), ApprovalAnnotationKind::Reviewed => t.muted, }; - lines.push(Line::from(vec![ - Span::styled("Review: ", t.muted), - Span::styled(annotation.detail_label, annotation_style), - ])); + push_wrapped( + &mut lines, + "Review: ", + t.muted, + &annotation.detail_label, + annotation_style, + text_width, + ); + } + + // Reviewer's persisted rejection guidance. The reason is free-form and has + // no server-side length cap, so it wraps and the popup scrolls instead of + // clipping the tail. + if let Some(reason) = rejection_guidance(chunk) { + push_wrapped( + &mut lines, + "Guidance: ", + t.muted, + reason, + t.status_err, + text_width, + ); } // Binary (denormalized from the denial). if !chunk.binary.is_empty() { - lines.push(Line::from(vec![ - Span::styled("Binary: ", t.muted), - Span::styled(&chunk.binary, t.text), - ])); + push_wrapped( + &mut lines, + "Binary: ", + t.muted, + &chunk.binary, + t.text, + text_width, + ); } - // Hit count (accumulated real denial count) and first/last seen. - lines.push(Line::from(vec![ - Span::styled("Denied: ", t.muted), - Span::styled( - format!( - "{} connection{}", - chunk.hit_count, - if chunk.hit_count == 1 { "" } else { "s" } - ), + // Hit count (accumulated real denial count) and first/last seen. Kept on one + // row while it fits, so a narrow terminal wraps it instead of losing the tail. + let denied_label = "Denied: "; + let denied_count = format!( + "{} connection{}", + chunk.hit_count, + if chunk.hit_count == 1 { "" } else { "s" } + ); + let denied_seen = format!( + "(first {} / last {})", + format_short_time(chunk.first_seen_ms), + format_short_time(chunk.last_seen_ms), + ); + let denied_width = display_width(denied_label) + + display_width(&denied_count) + + 2 + + display_width(&denied_seen); + if denied_width <= text_width { + lines.push(Line::from(vec![ + Span::styled(denied_label, t.muted), + Span::styled(denied_count, t.accent), + Span::styled(format!(" {denied_seen}"), t.muted), + ])); + } else { + push_wrapped( + &mut lines, + denied_label, + t.muted, + &denied_count, t.accent, - ), - Span::styled( - format!( - " (first {} / last {})", - format_short_time(chunk.first_seen_ms), - format_short_time(chunk.last_seen_ms), - ), + text_width, + ); + push_wrapped( + &mut lines, + &" ".repeat(display_width(denied_label)), t.muted, - ), - ])); + &denied_seen, + t.muted, + text_width, + ); + } // Endpoints. if let Some(ref rule) = chunk.proposed_rule { lines.push(Line::from("")); lines.push(Line::from(Span::styled("Endpoints:", t.muted))); for ep in &rule.endpoints { - lines.push(Line::from(vec![ - Span::raw(" "), - Span::styled("-> ", t.muted), - Span::styled(format_endpoint_summary(ep), t.accent), - ])); + push_wrapped( + &mut lines, + " -> ", + t.muted, + &format_endpoint_summary(ep), + t.accent, + text_width, + ); for detail in format_endpoint_details(ep) { - lines.push(Line::from(vec![ - Span::raw(" "), - Span::styled(detail, t.text), - ])); + push_wrapped(&mut lines, " ", t.text, &detail, t.text, text_width); } } @@ -274,10 +338,7 @@ pub fn draw_detail_popup( lines.push(Line::from("")); lines.push(Line::from(Span::styled("Binaries:", t.muted))); for b in &rule.binaries { - lines.push(Line::from(vec![ - Span::raw(" "), - Span::styled(&b.path, t.text), - ])); + push_wrapped(&mut lines, " ", t.text, &b.path, t.text, text_width); } } } @@ -285,59 +346,86 @@ pub fn draw_detail_popup( // Rationale. if !chunk.rationale.is_empty() { lines.push(Line::from("")); - lines.push(Line::from(vec![ - Span::styled("Rationale: ", t.muted), - Span::styled(&chunk.rationale, t.text), - ])); + push_wrapped( + &mut lines, + "Rationale: ", + t.muted, + &chunk.rationale, + t.text, + text_width, + ); } // Security notes. if !chunk.security_notes.is_empty() { lines.push(Line::from("")); - lines.push(Line::from(vec![Span::styled( - format!("! {}", chunk.security_notes), - t.status_warn.add_modifier(Modifier::BOLD), - )])); + let warn = t.status_warn.add_modifier(Modifier::BOLD); + push_wrapped( + &mut lines, + "! ", + warn, + &chunk.security_notes, + warn, + text_width, + ); } - // Action hints — state-aware toggle keys. - lines.push(Line::from("")); - let mut hint_spans: Vec> = Vec::new(); - match chunk.status.as_str() { - "pending" => { - hint_spans.extend([ - Span::styled("[a]", t.key_hint), - Span::styled(" Approve ", t.text), - Span::styled("[x]", t.key_hint), - Span::styled(" Reject ", t.text), - ]); - } - "approved" => { - hint_spans.extend([ - Span::styled("[x]", t.key_hint), - Span::styled(" Revoke ", t.text), - ]); - } - "rejected" => { - hint_spans.extend([ - Span::styled("[a]", t.key_hint), - Span::styled(" Approve ", t.text), - ]); + // Split the inner area into a scrollable body and pinned hint rows, so the + // action and close controls stay on screen however long the content is. The + // hints need a second row on a narrow terminal and that shrinks the body, so + // settle the two together. + let inner = block.inner(popup_area); + let inner_height = usize::from(inner.height); + let total_rows = lines.len(); + let max_footer = inner_height.saturating_sub(1).max(1); + + let mut footer_rows = 1usize; + let mut hint_rows = Vec::new(); + for _ in 0..2 { + let body = inner_height.saturating_sub(footer_rows); + let scrollable = total_rows.saturating_sub(body) > 0; + hint_rows = pack_hints(&hint_units(chunk, t, scrollable), text_width); + let needed = hint_rows.len().clamp(1, max_footer); + if needed == footer_rows { + break; } - _ => {} + footer_rows = needed; } - hint_spans.extend([ - Span::styled("[Esc]", t.muted), - Span::styled(" Close", t.muted), - ]); - lines.push(Line::from(hint_spans)); + let parts = Layout::default() + .direction(Direction::Vertical) + .constraints([ + Constraint::Min(0), + Constraint::Length(u16::try_from(footer_rows).unwrap_or(1)), + ]) + .split(inner); + let body_height = usize::from(parts[0].height); + let max_scroll = total_rows.saturating_sub(body_height); + let scroll = scroll.min(max_scroll); + + let block = if max_scroll > 0 { + block.title_bottom( + Line::from(Span::styled( + format!(" {}/{} ", scroll + 1, total_rows), + t.muted, + )) + .right_aligned(), + ) + } else { + block + }; + + frame.render_widget(block, popup_area); frame.render_widget( - Paragraph::new(lines) - .block(block) - .wrap(Wrap { trim: false }), - popup_area, + Paragraph::new(lines).scroll((u16::try_from(scroll).unwrap_or(u16::MAX), 0)), + parts[0], ); + frame.render_widget(Paragraph::new(hint_rows), parts[1]); + + DetailMetrics { + total_rows, + body_height, + } } // --------------------------------------------------------------------------- @@ -460,6 +548,188 @@ fn truncate_str(s: &str, max_len: usize) -> String { } } +/// Terminal display width of `text` in columns. +/// +/// Uses the same measurement ratatui applies when it lays cells out, so a +/// double-width glyph such as CJK counts as the two columns it will occupy. +/// Counting `chars` here instead would let CJK text render past the popup edge +/// with no way to scroll to the missing tail. +fn display_width(text: &str) -> usize { + Span::raw(text).width() +} + +/// Word-wrap `text` into rows of at most `width` display columns. +/// +/// A word wider than `width` is hard-broken rather than allowed to overflow. +/// Always returns at least one row so callers can index the first row safely. +fn wrap_value(text: &str, width: usize) -> Vec { + if width == 0 { + return vec![text.to_string()]; + } + let mut rows: Vec = Vec::new(); + let mut cur = String::new(); + let mut cur_width = 0usize; + let mut buf = [0u8; 4]; + for word in text.split_whitespace() { + let word_width = display_width(word); + if word_width > width { + if cur_width > 0 { + rows.push(std::mem::take(&mut cur)); + cur_width = 0; + } + for ch in word.chars() { + let ch_width = display_width(ch.encode_utf8(&mut buf)); + if cur_width + ch_width > width && cur_width > 0 { + rows.push(std::mem::take(&mut cur)); + cur_width = 0; + } + cur.push(ch); + cur_width += ch_width; + } + continue; + } + let needed = if cur_width == 0 { + word_width + } else { + cur_width + 1 + word_width + }; + if needed > width { + rows.push(std::mem::take(&mut cur)); + cur_width = 0; + } + if cur_width > 0 { + cur.push(' '); + cur_width += 1; + } + cur.push_str(word); + cur_width += word_width; + } + if cur_width > 0 || rows.is_empty() { + rows.push(cur); + } + rows +} + +/// Truncate `text` to `max_columns` display columns, appending `...` when cut. +/// +/// `truncate_str` counts chars, which is right for its existing callers but +/// would let a CJK value take twice its budget on the list row. +fn truncate_display(text: &str, max_columns: usize) -> String { + if display_width(text) <= max_columns { + return text.to_string(); + } + if max_columns <= 3 { + return ".".repeat(max_columns); + } + let budget = max_columns - 3; + let mut out = String::new(); + let mut width = 0usize; + let mut buf = [0u8; 4]; + for ch in text.chars() { + let ch_width = display_width(ch.encode_utf8(&mut buf)); + if width + ch_width > budget { + break; + } + out.push(ch); + width += ch_width; + } + out.push_str("..."); + out +} + +/// Push `text` wrapped to `width`, with `prefix` on the first row and a matching +/// indent on continuation rows so the label column stays aligned. +fn push_wrapped( + lines: &mut Vec>, + prefix: &str, + prefix_style: Style, + text: &str, + text_style: Style, + width: usize, +) { + let indent = display_width(prefix); + let available = width.saturating_sub(indent).max(1); + for (i, row) in wrap_value(text, available).into_iter().enumerate() { + let head = if i == 0 { + Span::styled(prefix.to_string(), prefix_style) + } else { + Span::raw(" ".repeat(indent)) + }; + lines.push(Line::from(vec![head, Span::styled(row, text_style)])); + } +} + +/// One footer hint: the spans that render it, and its display width. +type HintUnit = (Vec>, usize); + +/// State-aware hints for the detail popup footer. +fn hint_units(chunk: &PolicyChunk, t: &crate::theme::Theme, scrollable: bool) -> Vec { + let mut units: Vec = Vec::new(); + { + let mut add = |key: &str, label: &str, key_style: Style, label_style: Style| { + units.push(( + vec![ + Span::styled(key.to_string(), key_style), + Span::styled(label.to_string(), label_style), + ], + display_width(key) + display_width(label), + )); + }; + match chunk.status.as_str() { + "pending" => { + add("[a]", " Approve ", t.key_hint, t.text); + add("[x]", " Reject ", t.key_hint, t.text); + } + "approved" => add("[x]", " Revoke ", t.key_hint, t.text), + "rejected" => add("[a]", " Approve ", t.key_hint, t.text), + _ => {} + } + if scrollable { + add("[j/k]", " Scroll ", t.key_hint, t.text); + } + add("[Esc]", " Close", t.muted, t.muted); + } + units +} + +/// Pack hint units into rows no wider than `width`, never splitting a unit. +/// +/// A narrow terminal would otherwise clip the trailing hints, and `[Esc] Close` +/// is the last one. +fn pack_hints(units: &[HintUnit], width: usize) -> Vec> { + let mut rows: Vec> = Vec::new(); + let mut current: Vec> = Vec::new(); + let mut current_width = 0usize; + for (spans, unit_width) in units { + if current_width + unit_width > width && !current.is_empty() { + rows.push(Line::from(std::mem::take(&mut current))); + current_width = 0; + } + current.extend(spans.iter().cloned()); + current_width += unit_width; + } + if !current.is_empty() { + rows.push(Line::from(current)); + } + if rows.is_empty() { + rows.push(Line::from(String::new())); + } + rows +} + +/// The reviewer's persisted note for a rejected chunk. +/// +/// Gated on status rather than on the field alone: the gateway's +/// `update_draft_chunk_status` leaves `rejection_reason` untouched when a chunk +/// is later approved, so an approved chunk can still carry a stale note. +fn rejection_guidance(chunk: &PolicyChunk) -> Option<&str> { + if chunk.status != "rejected" { + return None; + } + let reason = chunk.rejection_reason.trim(); + (!reason.is_empty()).then_some(reason) +} + #[derive(Clone, Copy)] enum ApprovalAnnotationKind { AutoApproved, @@ -701,3 +971,396 @@ fn format_short_time(epoch_ms: i64) -> String { let seconds = time_of_day % 60; format!("{hours:02}:{minutes:02}:{seconds:02}") } + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::Theme; + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + /// Column width computed independently of the production `display_width`. + /// + /// Asserting with the helper under test would be tautological: if it + /// regressed to counting chars, the assertion would regress with it. + fn expected_columns(text: &str) -> usize { + text.chars() + .map(|c| { + let wide = ('\u{1100}'..='\u{115f}').contains(&c) + || ('\u{2e80}'..='\u{a4cf}').contains(&c) + || ('\u{ac00}'..='\u{d7a3}').contains(&c) + || ('\u{f900}'..='\u{faff}').contains(&c) + || ('\u{fe30}'..='\u{fe6f}').contains(&c) + || ('\u{ff00}'..='\u{ff60}').contains(&c) + || ('\u{ffe0}'..='\u{ffe6}').contains(&c); + usize::from(wide) + 1 + }) + .sum() + } + + fn make_chunk(status: &str, rejection_reason: &str) -> PolicyChunk { + PolicyChunk { + status: status.to_string(), + rejection_reason: rejection_reason.to_string(), + ..Default::default() + } + } + + #[test] + fn rejected_chunk_exposes_its_reason() { + let chunk = make_chunk("rejected", "too broad: allows any port"); + assert_eq!( + rejection_guidance(&chunk), + Some("too broad: allows any port") + ); + } + + #[test] + fn approved_chunk_hides_stale_reason() { + // Approving passes None for the reason, which leaves the stored value in + // place, so a chunk rejected and later approved still carries the note. + let chunk = make_chunk("approved", "too broad: allows any port"); + assert_eq!(rejection_guidance(&chunk), None); + } + + #[test] + fn pending_chunk_has_no_guidance() { + assert_eq!(rejection_guidance(&make_chunk("pending", "")), None); + } + + #[test] + fn blank_reason_is_dropped() { + assert_eq!(rejection_guidance(&make_chunk("rejected", "")), None); + assert_eq!(rejection_guidance(&make_chunk("rejected", " \n")), None); + } + + #[test] + fn reason_is_trimmed() { + let chunk = make_chunk("rejected", " needs a narrower host "); + assert_eq!(rejection_guidance(&chunk), Some("needs a narrower host")); + } + + #[test] + fn long_reason_truncates_for_the_list_row() { + let reason = "rejected because the endpoint list is far too permissive"; + let shown = truncate_display(reason, 32); + assert_eq!(display_width(&shown), 32); + assert!(shown.ends_with("...")); + assert!(shown.starts_with("rejected because")); + } + + #[test] + fn short_reason_is_not_truncated() { + assert_eq!(truncate_str("too broad", 32), "too broad"); + } + + // --- wrapping --------------------------------------------------------- + + #[test] + fn wrap_value_breaks_on_word_boundaries() { + assert_eq!( + wrap_value("alpha beta gamma", 11), + vec!["alpha beta", "gamma"] + ); + } + + #[test] + fn wrap_value_hard_breaks_a_word_longer_than_the_width() { + assert_eq!(wrap_value("abcdefghij", 4), vec!["abcd", "efgh", "ij"]); + } + + #[test] + fn wrap_value_always_returns_at_least_one_row() { + assert_eq!(wrap_value("", 10), vec![String::new()]); + } + + #[test] + fn wrap_value_never_exceeds_the_width() { + let text = "reject this rule because the endpoint list is far too permissive"; + for row in wrap_value(text, 17) { + assert!(display_width(&row) <= 17, "row too wide: {row:?}"); + } + } + + #[test] + fn wrap_value_measures_display_columns_not_chars() { + // CJK glyphs occupy two columns each, and with no spaces the whole + // string takes the hard-break path. + let cjk = "这条规则的范围太广".repeat(20); + for row in wrap_value(&cjk, 40) { + assert!( + expected_columns(&row) <= 40, + "row is {} columns: {row:?}", + expected_columns(&row) + ); + } + + // Mixed script exercises the word-packing path instead. + let mixed = "scope 这条规则 to docs 路径 only ".repeat(20); + for row in wrap_value(&mixed, 33) { + assert!( + expected_columns(&row) <= 33, + "row is {} columns: {row:?}", + expected_columns(&row) + ); + } + } + + #[test] + fn truncate_display_counts_columns_not_chars() { + let cjk = "这条规则的范围太广".repeat(10); + let shown = truncate_display(&cjk, 32); + assert!( + expected_columns(&shown) <= 32, + "truncated value is {} columns", + expected_columns(&shown) + ); + assert!(shown.ends_with("...")); + assert_eq!(truncate_display("too broad", 32), "too broad"); + } + + // --- rendering -------------------------------------------------------- + + fn render(chunk: &PolicyChunk, width: u16, height: u16, scroll: usize) -> (String, usize) { + let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); + let mut max_scroll = 0usize; + terminal + .draw(|frame| { + let metrics = draw_detail_popup( + frame, + chunk, + Rect::new(0, 0, width, height), + &Theme::dark(), + scroll, + ); + max_scroll = metrics.total_rows.saturating_sub(metrics.body_height); + }) + .unwrap(); + let buffer = terminal.backend().buffer(); + let text: String = buffer + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + (text, max_scroll) + } + + /// A rejection reason has no server-side length cap, so the popup has to keep + /// a paragraph-length one reachable rather than clipping its tail. + fn long_reason() -> String { + let mut reason = String::from("PREFIX_MARKER "); + while reason.len() < 1980 { + reason.push_str("this rule is far too broad and must be narrowed; "); + } + reason.push_str(" SUFFIX_MARKER"); + reason + } + + #[test] + fn long_guidance_head_and_tail_are_both_reachable() { + let chunk = PolicyChunk { + status: "rejected".to_string(), + rejection_reason: long_reason(), + rule_name: "allow-github".to_string(), + ..Default::default() + }; + + let (top, max_scroll) = render(&chunk, 80, 24, 0); + assert!(max_scroll > 0, "content should overflow an 80x24 popup"); + assert!( + top.contains("PREFIX_MARKER"), + "head not visible at scroll 0" + ); + + let (bottom, _) = render(&chunk, 80, 24, max_scroll); + assert!( + bottom.contains("SUFFIX_MARKER"), + "tail not reachable at max scroll" + ); + } + + #[test] + fn action_hints_stay_visible_at_every_scroll_position() { + let chunk = PolicyChunk { + status: "rejected".to_string(), + rejection_reason: long_reason(), + rule_name: "allow-github".to_string(), + ..Default::default() + }; + + let (top, max_scroll) = render(&chunk, 80, 24, 0); + let (bottom, _) = render(&chunk, 80, 24, max_scroll); + for (label, screen) in [("top", &top), ("bottom", &bottom)] { + assert!(screen.contains("Close"), "close hint missing at {label}"); + assert!( + screen.contains("Approve"), + "approve hint missing at {label}" + ); + assert!(screen.contains("Scroll"), "scroll hint missing at {label}"); + } + } + + #[test] + fn scrolling_past_the_end_is_clamped_to_the_last_page() { + let chunk = PolicyChunk { + status: "rejected".to_string(), + rejection_reason: long_reason(), + rule_name: "allow-github".to_string(), + ..Default::default() + }; + let (_, max_scroll) = render(&chunk, 80, 24, 0); + let (clamped, _) = render(&chunk, 80, 24, max_scroll + 500); + let (last, _) = render(&chunk, 80, 24, max_scroll); + assert_eq!( + clamped, last, + "over-scrolling should clamp to the last page" + ); + } + + /// The same overflow already affected `rationale` before this change, so the + /// scrollable body has to fix that case too. + #[test] + fn long_rationale_tail_is_reachable_on_a_pending_chunk() { + let mut rationale = String::from("PREFIX_MARKER "); + while rationale.len() < 1980 { + rationale.push_str("the agent needs broad network access; "); + } + rationale.push_str(" SUFFIX_MARKER"); + let chunk = PolicyChunk { + status: "pending".to_string(), + rule_name: "allow-github".to_string(), + rationale, + ..Default::default() + }; + + let (_, max_scroll) = render(&chunk, 80, 24, 0); + let (bottom, _) = render(&chunk, 80, 24, max_scroll); + assert!(bottom.contains("SUFFIX_MARKER")); + assert!(bottom.contains("Close")); + } + + /// Double-width guidance must stay reachable too. Counting chars rather than + /// columns made every wrapped row about twice as wide as the popup, so the + /// right half of each row was clipped with nowhere to scroll. Markers are + /// interleaved through the text rather than appended, because a trailing + /// marker lands on its own short row either way and would not detect this. + #[test] + fn cjk_guidance_is_fully_reachable_at_80x24() { + use std::fmt::Write as _; + + const MARKERS: usize = 16; + let mut reason = String::new(); + for i in 0..MARKERS { + let _ = write!(reason, "M{i:02}"); + reason.push_str(&"这条规则范围太广".repeat(4)); + } + let chunk = PolicyChunk { + status: "rejected".to_string(), + rejection_reason: reason, + rule_name: "allow-github".to_string(), + ..Default::default() + }; + + let (_, max_scroll) = render(&chunk, 80, 24, 0); + assert!(max_scroll > 0, "content should overflow an 80x24 popup"); + + let mut seen = String::new(); + for scroll in 0..=max_scroll { + seen.push_str(&render(&chunk, 80, 24, scroll).0); + } + for i in 0..MARKERS { + let marker = format!("M{i:02}"); + assert!( + seen.contains(&marker), + "guidance marker {marker} was clipped and is unreachable at every scroll offset" + ); + } + } + + #[test] + fn short_content_does_not_scroll() { + let chunk = PolicyChunk { + status: "rejected".to_string(), + rejection_reason: "too broad".to_string(), + rule_name: "allow-github".to_string(), + ..Default::default() + }; + let (screen, max_scroll) = render(&chunk, 80, 24, 0); + assert_eq!(max_scroll, 0, "short content should not be scrollable"); + assert!(screen.contains("too broad")); + assert!( + !screen.contains("Scroll"), + "scroll hint should be hidden when everything fits" + ); + } + + fn denied_chunk(status: &str, reason: &str) -> PolicyChunk { + PolicyChunk { + status: status.to_string(), + rejection_reason: reason.to_string(), + rule_name: "allow-github".to_string(), + confidence: 0.82, + hit_count: 3, + first_seen_ms: 1_700_000_000_000, + last_seen_ms: 1_700_000_100_000, + ..Default::default() + } + } + + /// Dropping `Wrap` means anything not routed through `push_wrapped` clips + /// horizontally, so the denial timestamps have to wrap on a narrow popup. + #[test] + fn denied_timestamps_survive_a_narrow_popup() { + for width in [60u16, 70u16, 80u16] { + let chunk = denied_chunk("rejected", "scope this to docs/ paths only"); + let (screen, _) = render(&chunk, width, 24, 0); + assert!( + screen.contains("22:13:20"), + "first-seen lost at width {width}" + ); + assert!( + screen.contains("22:15:00"), + "last-seen lost at width {width}" + ); + } + } + + /// The close hint is the last one, so a narrow footer would drop it first. + #[test] + fn close_hint_survives_a_narrow_popup_with_scrollable_content() { + for width in [60u16, 70u16, 80u16] { + let chunk = denied_chunk("pending", ""); + let chunk = PolicyChunk { + rationale: long_reason(), + ..chunk + }; + let (screen, max_scroll) = render(&chunk, width, 24, 0); + assert!(max_scroll > 0, "content should overflow at width {width}"); + assert!(screen.contains("Close"), "close hint lost at width {width}"); + assert!( + screen.contains("Approve"), + "approve hint lost at width {width}" + ); + assert!( + screen.contains("Reject"), + "reject hint lost at width {width}" + ); + } + } + + #[test] + fn hints_pack_onto_one_row_when_they_fit() { + let theme = Theme::dark(); + let chunk = denied_chunk("pending", ""); + let rows = pack_hints(&hint_units(&chunk, &theme, true), 200); + assert_eq!(rows.len(), 1); + } + + #[test] + fn hints_spill_onto_a_second_row_when_they_do_not_fit() { + let theme = Theme::dark(); + let chunk = denied_chunk("pending", ""); + let rows = pack_hints(&hint_units(&chunk, &theme, true), 30); + assert!(rows.len() > 1, "hints should wrap at 30 columns"); + } +} diff --git a/deploy/docker/Dockerfile.python-wheels b/deploy/docker/Dockerfile.python-wheels deleted file mode 100644 index fe58e3fcc7..0000000000 --- a/deploy/docker/Dockerfile.python-wheels +++ /dev/null @@ -1,115 +0,0 @@ -# syntax=docker/dockerfile:1.6 - -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - - -ARG PYTHON_VERSION=3.12 - -FROM --platform=$BUILDPLATFORM python:${PYTHON_VERSION}-slim AS base - -ENV PATH="/root/.cargo/bin:${PATH}" - -RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential \ - cmake \ - curl \ - gcc \ - libc6-dev \ - libclang-dev \ - pkg-config \ - libssl-dev \ - && rm -rf /var/lib/apt/lists/* - -RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.95.0 -RUN pip install --no-cache-dir maturin - -COPY deploy/docker/cross-build.sh /usr/local/bin/ - -FROM base AS builder - -ARG TARGETARCH -ARG BUILDARCH -ARG CARGO_TARGET_CACHE_SCOPE=default - -ARG SCCACHE_MEMCACHED_ENDPOINT - -WORKDIR /build - -RUN . cross-build.sh && install_cross_toolchain && install_sccache && add_rust_target - -# Copy dependency manifests first for better caching. -COPY Cargo.toml Cargo.lock ./ -COPY crates/openshell-cli/Cargo.toml crates/openshell-cli/Cargo.toml -COPY crates/openshell-core/Cargo.toml crates/openshell-core/Cargo.toml -COPY crates/openshell-ocsf/Cargo.toml crates/openshell-ocsf/Cargo.toml -COPY crates/openshell-providers/Cargo.toml crates/openshell-providers/Cargo.toml -COPY crates/openshell-router/Cargo.toml crates/openshell-router/Cargo.toml -COPY crates/openshell-sandbox/Cargo.toml crates/openshell-sandbox/Cargo.toml -COPY crates/openshell-server/Cargo.toml crates/openshell-server/Cargo.toml -COPY crates/openshell-bootstrap/Cargo.toml crates/openshell-bootstrap/Cargo.toml -COPY crates/openshell-policy/Cargo.toml crates/openshell-policy/Cargo.toml -COPY crates/openshell-prover/Cargo.toml crates/openshell-prover/Cargo.toml -COPY crates/openshell-tui/Cargo.toml crates/openshell-tui/Cargo.toml -COPY crates/openshell-core/build.rs crates/openshell-core/build.rs -COPY proto/ proto/ - -# Create dummy source files to build dependencies. -RUN mkdir -p crates/openshell-cli/src crates/openshell-core/src crates/openshell-ocsf/src crates/openshell-policy/src crates/openshell-providers/src crates/openshell-prover/src crates/openshell-router/src crates/openshell-sandbox/src crates/openshell-server/src crates/openshell-bootstrap/src crates/openshell-tui/src && \ - echo "fn main() {}" > crates/openshell-cli/src/main.rs && \ - echo "fn main() {}" > crates/openshell-sandbox/src/main.rs && \ - echo "fn main() {}" > crates/openshell-server/src/main.rs && \ - touch crates/openshell-core/src/lib.rs && \ - touch crates/openshell-ocsf/src/lib.rs && \ - touch crates/openshell-providers/src/lib.rs && \ - touch crates/openshell-router/src/lib.rs && \ - touch crates/openshell-bootstrap/src/lib.rs && \ - touch crates/openshell-policy/src/lib.rs && \ - touch crates/openshell-prover/src/lib.rs && \ - touch crates/openshell-tui/src/lib.rs - -# Build dependencies only (cached unless Cargo.toml/lock changes). -# sccache uses memcached in CI or the local disk cache mount for local dev. -# The cargo-target mount gives cargo a persistent target/ dir for incremental rebuilds. -RUN --mount=type=cache,id=cargo-registry-python-wheels-${TARGETARCH},sharing=locked,target=/root/.cargo/registry \ - --mount=type=cache,id=cargo-git-python-wheels-${TARGETARCH},sharing=locked,target=/root/.cargo/git \ - --mount=type=cache,id=cargo-target-python-wheels-${TARGETARCH}-${CARGO_TARGET_CACHE_SCOPE},sharing=locked,target=/build/target \ - --mount=type=cache,id=sccache-python-wheels-${TARGETARCH},sharing=locked,target=/tmp/sccache \ - . cross-build.sh && cargo_cross_build --release -p openshell-cli 2>/dev/null || true - -# Copy actual source code and Python packaging files. -COPY crates/ crates/ -COPY pyproject.toml README.md ./ -COPY python/ python/ - -# Touch source files to ensure they're rebuilt (not the cached dummy). -RUN touch crates/openshell-cli/src/main.rs \ - crates/openshell-cli/src/lib.rs \ - crates/openshell-bootstrap/src/lib.rs \ - crates/openshell-core/src/lib.rs \ - crates/openshell-providers/src/lib.rs \ - crates/openshell-router/src/lib.rs \ - crates/openshell-sandbox/src/main.rs \ - crates/openshell-server/src/main.rs \ - crates/openshell-core/build.rs \ - proto/*.proto - -# Declare version ARGs here (not earlier) so the git-hash-bearing values do not -# invalidate the expensive dependency-build layers above on every commit. -ARG OPENSHELL_CARGO_VERSION -ARG OPENSHELL_IMAGE_TAG -RUN --mount=type=cache,id=cargo-registry-python-wheels-${TARGETARCH},sharing=locked,target=/root/.cargo/registry \ - --mount=type=cache,id=cargo-git-python-wheels-${TARGETARCH},sharing=locked,target=/root/.cargo/git \ - --mount=type=cache,id=cargo-target-python-wheels-${TARGETARCH}-${CARGO_TARGET_CACHE_SCOPE},sharing=locked,target=/build/target \ - --mount=type=cache,id=sccache-python-wheels-${TARGETARCH},sharing=locked,target=/tmp/sccache \ - . cross-build.sh && \ - export_cross_env && \ - export RUSTC_WRAPPER=sccache && \ - export CARGO_BUILD_TARGET="$(rust_target)" && \ - if [ -n "${OPENSHELL_CARGO_VERSION:-}" ]; then \ - sed -i -E '/^\[workspace\.package\]/,/^\[/{s/^version[[:space:]]*=[[:space:]]*".*"/version = "'"${OPENSHELL_CARGO_VERSION}"'"/}' Cargo.toml; \ - fi && \ - maturin build --release --target "${CARGO_BUILD_TARGET}" --out /wheels - -FROM scratch AS wheels -COPY --from=builder /wheels/*.whl / diff --git a/deploy/docker/Dockerfile.python-wheels-macos b/deploy/docker/Dockerfile.python-wheels-macos deleted file mode 100644 index 1825dd6276..0000000000 --- a/deploy/docker/Dockerfile.python-wheels-macos +++ /dev/null @@ -1,126 +0,0 @@ -# syntax=docker/dockerfile:1.6 - -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 - - -ARG OSXCROSS_IMAGE=ghcr.io/crazy-max/osxcross:latest -ARG PYTHON_IMAGE=public.ecr.aws/docker/library/python -ARG PYTHON_VERSION=3.12 - -FROM ${OSXCROSS_IMAGE} AS osxcross - -FROM ${PYTHON_IMAGE}:${PYTHON_VERSION}-slim AS builder - -ARG TARGETARCH -ARG CARGO_TARGET_CACHE_SCOPE=default - -ENV PATH="/root/.cargo/bin:/usr/local/bin:/osxcross/bin:${PATH}" -ENV LD_LIBRARY_PATH="/osxcross/lib" - -COPY --from=osxcross /osxcross /osxcross - -RUN SDKROOT="$(echo /osxcross/SDK/MacOSX*.sdk)" && ln -sfn "${SDKROOT}" /osxcross/SDK/MacOSX.sdk - -RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential \ - ca-certificates \ - clang \ - cmake \ - curl \ - libclang-dev \ - libssl-dev \ - pkg-config \ - && rm -rf /var/lib/apt/lists/* - -# aws-lc-sys probes with --target=arm64-apple-macosx and clang then looks for -# arm64-apple-macosx-ld. Provide a linker alias to osxcross ld64. -RUN ln -sf /osxcross/bin/arm64-apple-darwin25.1-ld /usr/local/bin/arm64-apple-macosx-ld - -RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain 1.95.0 -RUN rustup target add aarch64-apple-darwin -RUN pip install --no-cache-dir maturin - -WORKDIR /build - -ENV CC_aarch64_apple_darwin=oa64-clang -ENV CXX_aarch64_apple_darwin=oa64-clang++ -ENV AR_aarch64_apple_darwin=aarch64-apple-darwin25.1-ar -ENV CARGO_TARGET_AARCH64_APPLE_DARWIN_LINKER=oa64-clang -ENV CARGO_TARGET_AARCH64_APPLE_DARWIN_AR=aarch64-apple-darwin25.1-ar -ENV SDKROOT=/osxcross/SDK/MacOSX.sdk -ENV MACOSX_DEPLOYMENT_TARGET=13.3 -ENV CFLAGS_aarch64_apple_darwin=--target=arm64-apple-macosx\ -mmacosx-version-min=13.3 -ENV CXXFLAGS_aarch64_apple_darwin=--target=arm64-apple-macosx\ -mmacosx-version-min=13.3 -ENV BINDGEN_EXTRA_CLANG_ARGS_aarch64_apple_darwin=--target=arm64-apple-macosx\ -isysroot\ ${SDKROOT} - -# Copy dependency manifests first for better caching. -COPY Cargo.toml Cargo.lock ./ -COPY crates/openshell-cli/Cargo.toml crates/openshell-cli/Cargo.toml -COPY crates/openshell-core/Cargo.toml crates/openshell-core/Cargo.toml -COPY crates/openshell-ocsf/Cargo.toml crates/openshell-ocsf/Cargo.toml -COPY crates/openshell-providers/Cargo.toml crates/openshell-providers/Cargo.toml -COPY crates/openshell-router/Cargo.toml crates/openshell-router/Cargo.toml -COPY crates/openshell-sandbox/Cargo.toml crates/openshell-sandbox/Cargo.toml -COPY crates/openshell-server/Cargo.toml crates/openshell-server/Cargo.toml -COPY crates/openshell-bootstrap/Cargo.toml crates/openshell-bootstrap/Cargo.toml -COPY crates/openshell-policy/Cargo.toml crates/openshell-policy/Cargo.toml -COPY crates/openshell-prover/Cargo.toml crates/openshell-prover/Cargo.toml -COPY crates/openshell-tui/Cargo.toml crates/openshell-tui/Cargo.toml -COPY crates/openshell-core/build.rs crates/openshell-core/build.rs -COPY proto/ proto/ - -# Create dummy source files to build dependencies. -RUN mkdir -p crates/openshell-cli/src crates/openshell-core/src crates/openshell-ocsf/src crates/openshell-policy/src crates/openshell-providers/src crates/openshell-prover/src crates/openshell-router/src crates/openshell-sandbox/src crates/openshell-server/src crates/openshell-bootstrap/src crates/openshell-tui/src && \ - echo "fn main() {}" > crates/openshell-cli/src/main.rs && \ - echo "fn main() {}" > crates/openshell-sandbox/src/main.rs && \ - echo "fn main() {}" > crates/openshell-server/src/main.rs && \ - touch crates/openshell-core/src/lib.rs && \ - touch crates/openshell-ocsf/src/lib.rs && \ - touch crates/openshell-providers/src/lib.rs && \ - touch crates/openshell-router/src/lib.rs && \ - touch crates/openshell-bootstrap/src/lib.rs && \ - touch crates/openshell-policy/src/lib.rs && \ - touch crates/openshell-prover/src/lib.rs && \ - touch crates/openshell-tui/src/lib.rs - -# Build dependencies only (cached unless Cargo.toml/lock changes). -RUN --mount=type=cache,id=cargo-registry-python-wheels-macos-${TARGETARCH},sharing=locked,target=/root/.cargo/registry \ - --mount=type=cache,id=cargo-git-python-wheels-macos-${TARGETARCH},sharing=locked,target=/root/.cargo/git \ - --mount=type=cache,id=cargo-target-python-wheels-macos-${TARGETARCH}-${CARGO_TARGET_CACHE_SCOPE},sharing=locked,target=/build/target \ - cargo build --release --target aarch64-apple-darwin -p openshell-cli 2>/dev/null || true - -# Copy actual source code and Python packaging files. -COPY crates/ crates/ -COPY providers/ providers/ -COPY pyproject.toml README.md ./ -COPY python/ python/ - -# Touch source files to ensure they're rebuilt (not the cached dummy). -# Touch build.rs and proto files to force proto code regeneration when the -# cargo target cache mount retains stale OUT_DIR artifacts from prior builds. -RUN touch crates/openshell-cli/src/main.rs \ - crates/openshell-cli/src/lib.rs \ - crates/openshell-bootstrap/src/lib.rs \ - crates/openshell-core/src/lib.rs \ - crates/openshell-providers/src/lib.rs \ - crates/openshell-router/src/lib.rs \ - crates/openshell-sandbox/src/main.rs \ - crates/openshell-server/src/main.rs \ - crates/openshell-core/build.rs \ - proto/*.proto - -# Declare version ARGs here (not earlier) so the git-hash-bearing values do not -# invalidate the expensive dependency-build layers above on every commit. -ARG OPENSHELL_CARGO_VERSION -ARG OPENSHELL_IMAGE_TAG -RUN --mount=type=cache,id=cargo-registry-python-wheels-macos-${TARGETARCH},sharing=locked,target=/root/.cargo/registry \ - --mount=type=cache,id=cargo-git-python-wheels-macos-${TARGETARCH},sharing=locked,target=/root/.cargo/git \ - --mount=type=cache,id=cargo-target-python-wheels-macos-${TARGETARCH}-${CARGO_TARGET_CACHE_SCOPE},sharing=locked,target=/build/target \ - if [ -n "${OPENSHELL_CARGO_VERSION:-}" ]; then \ - sed -i -E '/^\[workspace\.package\]/,/^\[/{s/^version[[:space:]]*=[[:space:]]*".*"/version = "'"${OPENSHELL_CARGO_VERSION}"'"/}' Cargo.toml; \ - fi && \ - maturin build --release --target aarch64-apple-darwin --out /wheels - -FROM scratch AS wheels -COPY --from=builder /wheels/*.whl / diff --git a/docs/about/installation.mdx b/docs/about/installation.mdx index e464d3da42..a733a1b881 100644 --- a/docs/about/installation.mdx +++ b/docs/about/installation.mdx @@ -20,6 +20,12 @@ The script detects your operating system and installs the OpenShell CLI and gate You can also download release artifacts directly from the [OpenShell GitHub Releases](https://github.com/NVIDIA/OpenShell/releases) page. +The `openshell` package on PyPI provides the Python SDK only. It does not install the `openshell` CLI. Add the SDK to a Python project with: + +```shell +uv add openshell +``` + Use `openshell status` to confirm the CLI can reach the gateway. ## Supported Compute Drivers diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index ebd7a9880c..8a8b82046e 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -30,12 +30,6 @@ curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh | The install script uses Homebrew, RPM, or a Debian package based on your machine. It starts the local gateway server after installation. -If you prefer [uv](https://docs.astral.sh/uv/): - -```shell -uv tool install -U openshell -``` - After installing the CLI, run `openshell --help` in your terminal to view the full CLI reference. diff --git a/docs/get-started/tutorials/docker-compose.mdx b/docs/get-started/tutorials/docker-compose.mdx index 4037c02995..677f34595b 100644 --- a/docs/get-started/tutorials/docker-compose.mdx +++ b/docs/get-started/tutorials/docker-compose.mdx @@ -72,13 +72,9 @@ curl -sf http://localhost:8080/healthz curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh | sh ``` -**From PyPI (any platform with [uv](https://docs.astral.sh/uv/)):** - -```shell -uv tool install -U openshell -``` - +The `openshell` package on PyPI provides the Python SDK only and does not install the CLI. + On Windows without WSL, install the CLI inside a WSL 2 distribution (for example AlmaLinux or Ubuntu) and run all `openshell` commands from that distribution. diff --git a/docs/reference/gateway-auth.mdx b/docs/reference/gateway-auth.mdx index e5dcb65adf..b5157b92a5 100644 --- a/docs/reference/gateway-auth.mdx +++ b/docs/reference/gateway-auth.mdx @@ -122,6 +122,59 @@ openshell gateway add https://gateway.example.com \ When you register or log in to an OIDC gateway, the CLI uses the Authorization Code flow with PKCE. It opens a browser, receives the authorization code on a localhost callback, exchanges the code for tokens, and stores the token bundle under the gateway credential directory. After `openshell gateway logout`, the next browser login asks the identity provider for a fresh login prompt so you can choose a different browser user instead of silently reusing the previous session. If `OPENSHELL_OIDC_CLIENT_SECRET` is set, the CLI uses the client credentials flow instead. Use that mode for CI and other non-interactive automation. +Official Python, TypeScript, and Go SDKs can perform renewable client-credentials +authentication directly. Configure the service account at the identity provider +with the audience, roles, scopes, and workspace membership required by the +gateway. The SDKs discover the token endpoint, attach the bearer token to each +RPC, and repeat the grant before expiry. They keep the client secret and access +token in memory and do not update the CLI's `oidc_token.json`. SDK clients +require TLS when sending these credentials to a non-loopback gateway. + + + + +```python +from openshell import ClientCredentialsAuth, SandboxClient + +auth = ClientCredentialsAuth( + client_secret=lambda: load_secret(), + # Omit issuer/client_id/scopes/audience to use active gateway metadata. +) +client = SandboxClient.from_active_cluster(client_credentials=auth) +``` + + + + +```ts +import { clientCredentials, OpenShellClient } from '@nvidia/openshell-sdk' + +const client = await OpenShellClient.connect({ + gateway: 'https://gateway.example.com', + oidcTokenProvider: clientCredentials({ + issuer: 'https://idp.example.com/realms/openshell', + clientId: 'openshell-service', + clientSecret: () => loadSecret(), + audience: 'openshell-gateway', + scopes: ['sandbox:read', 'sandbox:write'], + }), +}) +``` + + + + +```go +auth, err := oidc.NewClientCredentialsAuth( + oidc.WithGateway("production"), + oidc.WithClientSecretProvider(loadSecret), +) +client, err := v1.NewClient(v1.Config{Address: address, Auth: auth, TLS: tlsConfig}) +``` + + + + The connection flow: For a headless environment, set `OPENSHELL_NO_BROWSER=1` before registering or logging in to the gateway. When this variable is set and `OPENSHELL_OIDC_CLIENT_SECRET` is not configured, the CLI uses the Device Authorization Grant (RFC 8628) with S256 PKCE. This flow prompts the user to visit a verification URL on any device with a browser and enter a displayed code. The CLI polls the token endpoint until the user completes authorization. This requires the OIDC client to have the device authorization grant enabled on the identity provider. diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index a287d3d5b0..d1fed9ae44 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -616,8 +616,9 @@ compute_drivers = ["podman"] [openshell.drivers.podman] # Rootless socket path. For root Podman use /run/podman/podman.sock. -# Omit to auto-detect: the driver probes for a responsive Podman socket and -# fails to start if none respond. +# Omit to auto-detect: the driver probes for a responsive Podman socket, then +# asks the podman CLI where its socket is, and fails to start if neither finds +# one. Set this to pin a specific Podman machine instead. socket_path = "/run/user/1000/podman/podman.sock" default_image = "ghcr.io/nvidia/openshell/sandbox:latest" image_pull_policy = "missing" # always | missing | never | newer diff --git a/docs/sandboxes/manage-sandboxes.mdx b/docs/sandboxes/manage-sandboxes.mdx index ead6533294..e5a27879f3 100644 --- a/docs/sandboxes/manage-sandboxes.mdx +++ b/docs/sandboxes/manage-sandboxes.mdx @@ -267,6 +267,18 @@ with SandboxClient.from_active_cluster() as client: assert sandbox.id in {s.id for s in matches} ``` +For non-interactive automation, pass a renewable client-credentials provider. +Omitted issuer, client ID, audience, and scopes are read from the active +gateway's metadata. The client requires TLS for non-loopback gateways: + +```python +from openshell import ClientCredentialsAuth, SandboxClient + +auth = ClientCredentialsAuth(client_secret=lambda: load_secret()) +with SandboxClient.from_active_cluster(client_credentials=auth) as client: + sandboxes = client.list(workspace="default") +``` + ## Expose Long Running Services Service forwarding makes a long-running process inside a sandbox reachable through a gateway-managed URL. Use it for development servers, notebooks, dashboards, or other services that keep listening after the sandbox starts. Run the service on loopback inside the sandbox, expose its port, then open the URL printed by OpenShell. diff --git a/docs/sandboxes/policy-advisor.mdx b/docs/sandboxes/policy-advisor.mdx index bc09468cdb..b4d607cb33 100644 --- a/docs/sandboxes/policy-advisor.mdx +++ b/docs/sandboxes/policy-advisor.mdx @@ -231,6 +231,8 @@ openshell rule reject \ The rejection reason is returned to the agent through `policy.local`. The agent can use it to draft a narrower proposal. +Reviewers see the same guidance in the terminal UI. Run `openshell term`, open the sandbox's draft inbox, and select a rejected chunk to open its detail popup. The stored reason appears on a `Guidance:` line, and the list row shows a shortened copy of it. Rejection reasons have no length limit, so long guidance wraps and the popup body scrolls with `j`/`k`, `PageUp`/`PageDown`, and `g`/`G`; the approve and close controls stay pinned below the body, and the bottom border shows the scroll position. + ## Agent API `policy.local` is available only inside the sandbox and uses plain HTTP: diff --git a/docs/sandboxes/providers-v2.mdx b/docs/sandboxes/providers-v2.mdx index 96ce68ab32..7a0f96b5ac 100644 --- a/docs/sandboxes/providers-v2.mdx +++ b/docs/sandboxes/providers-v2.mdx @@ -663,6 +663,21 @@ The gateway sends a complete host, port, and path binding for every emitted stat Refresh configuration is stored separately from the current injectable credential value. Non-secret refresh configuration remains in the refresh-state record. Secret material is resolved from the active credential driver only while the gateway mints a new short-lived token. The gateway writes the token back through credential storage and updates credential expiry metadata. If an OAuth issuer rotates its refresh token, the gateway stages the replacement through credential storage before committing the refresh generation and removes the previous handle afterward. +For OAuth token endpoint failures, the gateway parses the bounded standard OAuth +error response and reports a structured recovery action through `provider +refresh status`. It does not retain provider error descriptions or raw response +bodies. The recovery actions are: + +- `retry`: a network, rate-limit, or temporary issuer failure; the worker retries automatically. +- `reauthorize`: a user refresh grant is no longer usable, such as `invalid_grant`; obtain a new grant and run `provider refresh configure`. +- `fix_configuration`: the OAuth client, scopes, grant type, or administrator policy must be corrected. +- `investigate`: the issuer returned an unrecognized response; the worker retries, but the operator should investigate persistent failures. + +The gateway parks `reauthorize` and `fix_configuration` failures instead of +retrying them every worker tick. A manual `provider refresh rotate` still +attempts the exchange. The current access token remains available only until +its recorded expiry, after which credential resolution fails closed. + Before OpenShell 0.1.0, refresh-state and credential-driver migrations are not supported. Upgrading from a build that stored refresh material inline requires reconfiguring the refresh grant. To change credential drivers, delete or @@ -770,11 +785,22 @@ Check refresh status: openshell provider refresh status my-graph ``` +The status table includes `RECOVERY` and `FAILURE_CODE`. Clients should use the +structured recovery action rather than parsing `LAST_ERROR`. For example, +`oauth_invalid_grant` with recovery action `reauthorize` means the user must +complete OAuth authorization again; `oauth_invalid_client` with +`fix_configuration` means changing the user login alone will not repair the +grant. OpenShell parks `reauthorize` failures until an explicit rotation or +reconfiguration. It retries `fix_configuration` failures hourly so externally +repaired clocks, policies, or credential-store values can recover without +creating rapid token-endpoint traffic. Transient and unrecognized failures use +the existing bounded 60-second retry interval. + The status table reports operational state without printing token values or refresh material: ```text -PROVIDER CREDENTIAL_KEY STRATEGY STATUS EXPIRES_AT NEXT_REFRESH LAST_REFRESH LAST_ERROR -my-graph MS_GRAPH_ACCESS_TOKEN oauth2_refresh_token refreshed 2026-06-01 00:00:00 2026-05-31 23:50:00 2026-05-31 23:00:00 - +PROVIDER CREDENTIAL_KEY STRATEGY STATUS RECOVERY EXPIRES_AT NEXT_REFRESH LAST_REFRESH FAILURE_CODE LAST_ERROR +my-graph MS_GRAPH_ACCESS_TOKEN oauth2_refresh_token reauthorization_required reauthorize 2026-06-01 00:00:00 - 2026-05-31 23:00:00 oauth_invalid_grant OAuth refresh grant is no longer usable ``` When no refresh configuration exists, the CLI distinguishes whole-provider checks from credential-specific checks: diff --git a/e2e/python/oidc/oidc_auth_test.py b/e2e/python/oidc/oidc_auth_test.py index bbea1aac3d..1ed8d56fc2 100644 --- a/e2e/python/oidc/oidc_auth_test.py +++ b/e2e/python/oidc/oidc_auth_test.py @@ -15,17 +15,23 @@ import contextlib import os +import urllib.parse +from pathlib import Path import grpc import pytest +from openshell import ClientCredentialsAuth, SandboxClient, TlsConfig from openshell._proto import datamodel_pb2, openshell_pb2, openshell_pb2_grpc from .helpers import ( + KEYCLOAK_REALM, + _gateway_endpoint, + _mtls_dir, extract_sub, - get_ci_token, get_token, grpc_channel, + keycloak_url, stub_with_token, ) @@ -180,9 +186,28 @@ class TestClientCredentials: def test_ci_token_can_list_sandboxes(self) -> None: admin_token = get_token("admin@test", "admin", scopes="openid openshell:all") admin_stub, admin_md = stub_with_token(admin_token) - ci_token = get_ci_token() + auth = ClientCredentialsAuth( + issuer=f"{keycloak_url()}/realms/{KEYCLOAK_REALM}", + client_id="openshell-ci", + client_secret="ci-test-secret", + ) + ci_token = auth() ci_sub = extract_sub(ci_token) - ci_stub, ci_md = stub_with_token(ci_token) + gateway_endpoint, is_tls = _gateway_endpoint() + parsed = urllib.parse.urlparse(gateway_endpoint) + target = f"{parsed.hostname}:{parsed.port or (443 if is_tls else 80)}" + tls = None + if is_tls: + if ca_path := os.environ.get("OPENSHELL_E2E_GATEWAY_CA_CERT"): + tls = TlsConfig(ca_path=Path(ca_path)) + else: + mtls = _mtls_dir() + tls = TlsConfig( + ca_path=mtls / "ca.crt", + cert_path=mtls / "tls.crt", + key_path=mtls / "tls.key", + ) + ci_client = SandboxClient(target, tls=tls, client_credentials=auth) with contextlib.suppress(grpc.RpcError): admin_stub.AddWorkspaceMember( @@ -194,8 +219,9 @@ def test_ci_token_can_list_sandboxes(self) -> None: metadata=admin_md, ) try: - ci_stub.ListSandboxes(openshell_pb2.ListSandboxesRequest(), metadata=ci_md) + ci_client.list(workspace="default") finally: + ci_client.close() with contextlib.suppress(grpc.RpcError): admin_stub.RemoveWorkspaceMember( openshell_pb2.RemoveWorkspaceMemberRequest( diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 42f989ce42..44881e1682 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -34,6 +34,7 @@ e2e-kubernetes-workspace-operator = ["e2e-kubernetes"] e2e-podman = ["e2e", "e2e-host-gateway", "e2e-local-container-driver"] e2e-podman-gpu = ["e2e-podman", "e2e-gpu"] e2e-oidc-pkce = [] +e2e-provider-refresh-keycloak = [] e2e-vm = ["e2e", "e2e-host-gateway"] [[test]] @@ -41,6 +42,11 @@ name = "oidc_pkce" path = "tests/oidc_pkce.rs" required-features = ["e2e-oidc-pkce"] +[[test]] +name = "provider_refresh_keycloak" +path = "tests/provider_refresh_keycloak.rs" +required-features = ["e2e-provider-refresh-keycloak"] + [[test]] name = "custom_image" path = "tests/custom_image.rs" diff --git a/e2e/rust/tests/provider_refresh_keycloak.rs b/e2e/rust/tests/provider_refresh_keycloak.rs new file mode 100644 index 0000000000..57bcb45fb7 --- /dev/null +++ b/e2e/rust/tests/provider_refresh_keycloak.rs @@ -0,0 +1,417 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(target_os = "linux")] + +//! End-to-end coverage for provider OAuth refresh recovery against Keycloak. +//! +//! OpenShell itself uses the local gateway's mTLS authentication. Keycloak is +//! only the provider token issuer: the test refreshes a valid grant, revokes +//! its Keycloak session, and verifies that the gateway reports the next +//! refresh as requiring user reauthorization. + +use std::io::Write as _; +use std::process::{Output, Stdio}; + +use openshell_e2e::harness::binary::openshell_cmd; +use serde_json::Value; +use tempfile::{Builder as TempFileBuilder, NamedTempFile}; +use tokio::io::AsyncWriteExt as _; +use tokio::process::Command; + +const PROVIDER_NAME: &str = "e2e-keycloak-refresh"; +const PROFILE_ID: &str = "e2e-keycloak-refresh"; +const CREDENTIAL_KEY: &str = "KEYCLOAK_ACCESS_TOKEN"; + +fn combined_output(output: &Output) -> String { + format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) +} + +async fn run_cli(args: &[&str], env: &[(&str, &str)]) -> Result { + openshell_cmd() + .args(args) + .env("NO_COLOR", "1") + .envs(env.iter().copied()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await + .map_err(|error| format!("run openshell command: {error}")) +} + +async fn run_cli_success(args: &[&str], env: &[(&str, &str)]) -> Result { + let output = run_cli(args, env).await?; + let combined = combined_output(&output); + if !output.status.success() { + return Err(format!( + "openshell command failed (exit {:?}):\n{combined}", + output.status.code() + )); + } + Ok(combined) +} + +async fn acquire_keycloak_grant( + issuer: &str, + username: &str, + password: &str, +) -> Result<(String, String), String> { + let token_endpoint = format!("{issuer}/protocol/openid-connect/token"); + let username_form = format!("username={username}"); + let password_form = format!("password={password}"); + let output = Command::new("curl") + .args([ + "--fail", + "--silent", + "--show-error", + "--request", + "POST", + &token_endpoint, + "--data-urlencode", + "grant_type=password", + "--data-urlencode", + "client_id=openshell-cli", + "--data-urlencode", + &username_form, + "--data-urlencode", + &password_form, + "--data-urlencode", + "scope=openid", + ]) + .output() + .await + .map_err(|error| format!("request Keycloak grant: {error}"))?; + if !output.status.success() { + return Err(format!( + "Keycloak grant request failed (exit {:?}): {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + )); + } + + let response: Value = serde_json::from_slice(&output.stdout) + .map_err(|error| format!("decode Keycloak grant response: {error}"))?; + let access_token = response + .get("access_token") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or_else(|| "Keycloak grant response omitted access_token".to_string())?; + let refresh_token = response + .get("refresh_token") + .and_then(Value::as_str) + .filter(|value| !value.is_empty()) + .ok_or_else(|| "Keycloak grant response omitted refresh_token".to_string())?; + Ok((access_token.to_string(), refresh_token.to_string())) +} + +async fn revoke_keycloak_grant(issuer: &str, refresh_token: &str) -> Result<(), String> { + let logout_endpoint = format!("{issuer}/protocol/openid-connect/logout"); + let mut child = Command::new("curl") + .args([ + "--fail", + "--silent", + "--show-error", + "--output", + "/dev/null", + "--request", + "POST", + &logout_endpoint, + "--data-urlencode", + "client_id=openshell-cli", + "--data-urlencode", + "refresh_token@-", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| format!("start Keycloak logout request: {error}"))?; + child + .stdin + .take() + .ok_or_else(|| "Keycloak logout stdin was not piped".to_string())? + .write_all(refresh_token.as_bytes()) + .await + .map_err(|error| format!("write Keycloak logout request: {error}"))?; + let output = child + .wait_with_output() + .await + .map_err(|error| format!("wait for Keycloak logout request: {error}"))?; + if !output.status.success() { + return Err(format!( + "Keycloak logout failed (exit {:?}): {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + )); + } + Ok(()) +} + +fn write_profile(issuer: &str) -> Result { + let mut file = TempFileBuilder::new() + .suffix(".yaml") + .tempfile() + .map_err(|error| format!("create provider profile: {error}"))?; + let profile = format!( + r#"id: {PROFILE_ID} +display_name: Keycloak provider refresh E2E +category: other +credentials: + - name: access_token + env_vars: [{CREDENTIAL_KEY}] + required: true + auth_style: bearer + header_name: authorization + refresh: + strategy: oauth2_refresh_token + token_url: {issuer}/protocol/openid-connect/token + scopes: [openid] + refresh_before_seconds: 60 + max_lifetime_seconds: 3600 + material: + - name: client_id + required: true + - name: refresh_token + required: true + secret: true +endpoints: + - host: keycloak.test.invalid + port: 443 + protocol: rest + access: read-only + enforcement: enforce +binaries: + - /usr/bin/curl +"# + ); + file.write_all(profile.as_bytes()) + .map_err(|error| format!("write provider profile: {error}"))?; + file.flush() + .map_err(|error| format!("flush provider profile: {error}"))?; + Ok(file) +} + +async fn delete_provider_resources() { + let _ = run_cli(&["provider", "delete", PROVIDER_NAME], &[]).await; + let _ = run_cli(&["provider", "profile", "delete", PROFILE_ID], &[]).await; +} + +async fn read_providers_v2_setting() -> Result, String> { + let output = run_cli(&["settings", "get", "--global", "--json"], &[]).await?; + if !output.status.success() { + return Err(format!( + "read global settings failed (exit {:?}):\n{}", + output.status.code(), + combined_output(&output) + )); + } + let response: Value = serde_json::from_slice(&output.stdout) + .map_err(|error| format!("decode global settings: {error}"))?; + let value = response + .get("settings") + .and_then(|settings| settings.get("providers_v2_enabled")) + .and_then(Value::as_str) + .filter(|value| *value != "") + .map(ToString::to_string); + Ok(value) +} + +async fn restore_providers_v2_setting(previous: Option<&str>) -> Result<(), String> { + if let Some(value) = previous { + run_cli_success( + &[ + "settings", + "set", + "--global", + "--key", + "providers_v2_enabled", + "--value", + value, + "--yes", + ], + &[], + ) + .await?; + } else { + run_cli_success( + &[ + "settings", + "delete", + "--global", + "--key", + "providers_v2_enabled", + "--yes", + ], + &[], + ) + .await?; + } + Ok(()) +} + +#[tokio::test] +async fn revoked_refresh_grant_requires_user_reauthorization() -> Result<(), String> { + let issuer = std::env::var("OPENSHELL_E2E_OIDC_ISSUER") + .map_err(|_| "OPENSHELL_E2E_OIDC_ISSUER is required".to_string())?; + let username = std::env::var("OPENSHELL_E2E_OIDC_USERNAME") + .map_err(|_| "OPENSHELL_E2E_OIDC_USERNAME is required".to_string())?; + let password = std::env::var("OPENSHELL_E2E_OIDC_PASSWORD") + .map_err(|_| "OPENSHELL_E2E_OIDC_PASSWORD is required".to_string())?; + let previous_providers_v2_setting = read_providers_v2_setting().await?; + let (access_token, refresh_token) = + acquire_keycloak_grant(&issuer, &username, &password).await?; + let profile = write_profile(&issuer)?; + let profile_path = profile.path().to_string_lossy().into_owned(); + + delete_provider_resources().await; + let result = async { + run_cli_success( + &[ + "settings", + "set", + "--global", + "--key", + "providers_v2_enabled", + "--value", + "true", + "--yes", + ], + &[], + ) + .await?; + run_cli_success( + &["provider", "profile", "import", "--file", &profile_path], + &[], + ) + .await?; + run_cli_success( + &[ + "provider", + "create", + "--name", + PROVIDER_NAME, + "--type", + PROFILE_ID, + "--credential", + CREDENTIAL_KEY, + ], + &[(CREDENTIAL_KEY, &access_token)], + ) + .await?; + run_cli_success( + &[ + "provider", + "refresh", + "configure", + PROVIDER_NAME, + "--credential-key", + CREDENTIAL_KEY, + "--strategy", + "oauth2-refresh-token", + "--material", + "client_id=openshell-cli", + "--secret-material-env", + "refresh_token=KEYCLOAK_REFRESH_TOKEN", + ], + &[("KEYCLOAK_REFRESH_TOKEN", &refresh_token)], + ) + .await?; + + run_cli_success( + &[ + "provider", + "refresh", + "rotate", + PROVIDER_NAME, + "--credential-key", + CREDENTIAL_KEY, + ], + &[], + ) + .await?; + let valid_status = run_cli_success( + &[ + "provider", + "refresh", + "status", + PROVIDER_NAME, + "--credential-key", + CREDENTIAL_KEY, + ], + &[], + ) + .await?; + if !valid_status.contains("refreshed") { + return Err(format!( + "valid Keycloak refresh did not reach refreshed state:\n{valid_status}" + )); + } + + revoke_keycloak_grant(&issuer, &refresh_token).await?; + let failed_rotation = run_cli( + &[ + "provider", + "refresh", + "rotate", + PROVIDER_NAME, + "--credential-key", + CREDENTIAL_KEY, + ], + &[], + ) + .await?; + let failed_rotation_output = combined_output(&failed_rotation); + if failed_rotation.status.success() || !failed_rotation_output.contains("invalid_grant") { + return Err(format!( + "revoked Keycloak refresh did not fail with invalid_grant:\n{failed_rotation_output}" + )); + } + + let revoked_status = run_cli_success( + &[ + "provider", + "refresh", + "status", + PROVIDER_NAME, + "--credential-key", + CREDENTIAL_KEY, + ], + &[], + ) + .await?; + for expected in [ + "reauthorization_required", + "reauthorize", + "oauth_invalid_grant", + ] { + if !revoked_status.contains(expected) { + return Err(format!( + "revoked refresh status omitted {expected}:\n{revoked_status}" + )); + } + } + if revoked_status.contains("292278994") { + return Err(format!( + "parked refresh rendered the i64::MAX scheduling sentinel as a date:\n{revoked_status}" + )); + } + Ok(()) + } + .await; + + delete_provider_resources().await; + let cleanup_result = + restore_providers_v2_setting(previous_providers_v2_setting.as_deref()).await; + match (result, cleanup_result) { + (Ok(()), Ok(())) => Ok(()), + (Err(test_error), Ok(())) => Err(test_error), + (Ok(()), Err(cleanup_error)) => Err(cleanup_error), + (Err(test_error), Err(cleanup_error)) => Err(format!( + "{test_error}\ncleanup also failed: {cleanup_error}" + )), + } +} diff --git a/flake.lock b/flake.lock index 746d9b48a4..b5861792ac 100644 --- a/flake.lock +++ b/flake.lock @@ -34,10 +34,27 @@ "type": "github" } }, + "nixpkgs-test-guest": { + "locked": { + "lastModified": 1785318670, + "narHash": "sha256-dN6Ou5x/+23FZLEpYP3IffO+NyJFzUlGumt1uu3MMaY=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "0954f7ee2f6bb3dc7d4e3d0d8bcb8fd4bde4cfc5", + "type": "github" + }, + "original": { + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "0954f7ee2f6bb3dc7d4e3d0d8bcb8fd4bde4cfc5", + "type": "github" + } + }, "root": { "inputs": { "flake-utils": "flake-utils", "nixpkgs": "nixpkgs", + "nixpkgs-test-guest": "nixpkgs-test-guest", "rust-overlay": "rust-overlay", "treefmt-nix": "treefmt-nix" } diff --git a/flake.nix b/flake.nix index ec21dd3b8b..9491ebeae3 100644 --- a/flake.nix +++ b/flake.nix @@ -14,6 +14,9 @@ inputs = { flake-utils.url = "github:numtide/flake-utils"; nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + # Keep the QEMU and OVMF runtime used by Apple Silicon test guests on a + # known-good release. Development shells and cross toolchains use nixpkgs. + nixpkgs-test-guest.url = "github:NixOS/nixpkgs/0954f7ee2f6bb3dc7d4e3d0d8bcb8fd4bde4cfc5"; rust-overlay = { url = "github:oxalica/rust-overlay"; inputs.nixpkgs.follows = "nixpkgs"; @@ -29,6 +32,7 @@ { flake-utils, nixpkgs, + nixpkgs-test-guest, treefmt-nix, rust-overlay, ... @@ -40,6 +44,7 @@ inherit system; overlays = [ (import rust-overlay) ]; }; + testGuestPkgs = import nixpkgs-test-guest { inherit system; }; commonDevShellPackages = with pkgs; [ # Assemble Debian artifacts on macOS and Linux. dpkg @@ -47,6 +52,7 @@ pkg-config # Coverage. lcov + uv ]; treefmtEval = treefmt-nix.lib.evalModule pkgs { projectRootFile = "flake.nix"; @@ -55,7 +61,11 @@ rustToolchain = pkgs.rust-bin.fromRustupToolchainFile ./rust-toolchain.toml; z3-static = pkgs.callPackage ./nix/pkgs/z3-static.nix { }; aws-lc-static = pkgs.callPackage ./nix/pkgs/aws-lc-static.nix { }; - testGuest = import ./nix/test-guest { inherit pkgs; }; + testGuest = import ./nix/test-guest { + inherit pkgs; + qemuPkgs = testGuestPkgs; + firmwarePkgs = testGuestPkgs; + }; in { apps.test-guest = testGuest.app; diff --git a/mise.lock b/mise.lock index e24bd77225..23ce8b24e0 100644 --- a/mise.lock +++ b/mise.lock @@ -158,6 +158,30 @@ checksum = "sha256:675804464634cf068dc206e9fafc1bd4557ffcc0b1638a1ff246d899b776f url = "https://github.com/rust-cross/cargo-zigbuild/releases/download/v0.22.3/cargo-zigbuild-x86_64-pc-windows-msvc.zip" url_api = "https://api.github.com/repos/rust-cross/cargo-zigbuild/releases/assets/405676944" +[[tools."github:rust-secure-code/cargo-auditable"]] +version = "0.7.5" +backend = "github:rust-secure-code/cargo-auditable" + +[tools."github:rust-secure-code/cargo-auditable"."platforms.linux-arm64"] +checksum = "sha256:6d364879b516fa914f98504e551faddedf35b71543b4331a6d26e4e217778cfa" +url = "https://github.com/rust-secure-code/cargo-auditable/releases/download/v0.7.5/cargo-auditable-aarch64-unknown-linux-gnu.tar.xz" +url_api = "https://api.github.com/repos/rust-secure-code/cargo-auditable/releases/assets/426566627" + +[tools."github:rust-secure-code/cargo-auditable"."platforms.linux-x64"] +checksum = "sha256:322eda09f24e5dba97371c6c2c6949569c411ddf893852e88135cc5b51d5a719" +url = "https://github.com/rust-secure-code/cargo-auditable/releases/download/v0.7.5/cargo-auditable-x86_64-unknown-linux-gnu.tar.xz" +url_api = "https://api.github.com/repos/rust-secure-code/cargo-auditable/releases/assets/426566663" + +[tools."github:rust-secure-code/cargo-auditable"."platforms.macos-arm64"] +checksum = "sha256:92720fff2be27492ca7b216510a27e88a835b526e9e94e46bc36b502ba17d8f0" +url = "https://github.com/rust-secure-code/cargo-auditable/releases/download/v0.7.5/cargo-auditable-aarch64-apple-darwin.tar.xz" +url_api = "https://api.github.com/repos/rust-secure-code/cargo-auditable/releases/assets/426566625" + +[tools."github:rust-secure-code/cargo-auditable"."platforms.windows-x64"] +checksum = "sha256:83a7d5955c7ac96ede5d896ac9ede5f7ecce9ece0e95d9e47acd766b09e2ef1b" +url = "https://github.com/rust-secure-code/cargo-auditable/releases/download/v0.7.5/cargo-auditable-x86_64-pc-windows-msvc.zip" +url_api = "https://api.github.com/repos/rust-secure-code/cargo-auditable/releases/assets/426566657" + [[tools.go]] version = "1.26.5" backend = "core:go" diff --git a/mise.toml b/mise.toml index 8e1cd4c4d6..ec643ed08e 100644 --- a/mise.toml +++ b/mise.toml @@ -42,6 +42,7 @@ k3d = { version = "5.8.3", os = ["macos"] } "github:EmbarkStudios/cargo-about" = { version = "0.8.4", version_prefix = "" } "github:EmbarkStudios/cargo-deny" = { version = "0.20.2", version_prefix = "" } zig = "0.14.1" +"github:rust-secure-code/cargo-auditable" = "0.7.5" "github:rust-cross/cargo-zigbuild" = "0.22.3" "npm:markdownlint-cli2" = "0.22.0" diff --git a/nix/test-guest/README.md b/nix/test-guest/README.md index ae28452056..ca62f893e6 100644 --- a/nix/test-guest/README.md +++ b/nix/test-guest/README.md @@ -16,6 +16,12 @@ This prototype uses Nix, QEMU, and Ansible to boot and configure disposable Linu The first run downloads the selected cloud image and VM runtime. Nix reuses those immutable inputs on later runs, while each guest starts from a fresh writable overlay. +On Apple Silicon, test guests deliberately take QEMU 11.0.2 and its matching OVMF +firmware from a separately pinned Nixpkgs revision. All other guest-runtime tools, +development dependencies, and cross-toolchain dependencies continue to use the main +current Nixpkgs input. This avoids a QEMU 11.1 HVF guest boot regression. Update +this pair only after validating an ARM64 Ubuntu guest boot with HVF. + ## Directory structure ```text diff --git a/nix/test-guest/default.nix b/nix/test-guest/default.nix index 2cfc772279..72937cfec2 100644 --- a/nix/test-guest/default.nix +++ b/nix/test-guest/default.nix @@ -3,13 +3,17 @@ # PROTOTYPE: Composable distro VMs for installing and exercising artifacts. -{ pkgs }: +{ + pkgs, + qemuPkgs ? pkgs, + firmwarePkgs ? pkgs, +}: let isAarch64 = pkgs.stdenv.hostPlatform.isAarch64; isDarwin = pkgs.stdenv.hostPlatform.isDarwin; architecture = if isAarch64 then "aarch64" else "x86_64"; - qemu = pkgs.qemu.override { hostCpuOnly = true; }; + qemu = qemuPkgs.qemu.override { hostCpuOnly = true; }; qemuBinary = if isAarch64 then "${qemu}/bin/qemu-system-aarch64" else "${qemu}/bin/qemu-system-x86_64"; @@ -75,8 +79,8 @@ let export OPENSHELL_TEST_GUEST_RUNNER=${./run.sh} export TEST_GUEST_BASH=${pkgs.bash}/bin/bash export TEST_GUEST_QEMU=${qemuBinary} - export TEST_GUEST_FIRMWARE_CODE=${pkgs.OVMF.firmware} - export TEST_GUEST_FIRMWARE_VARS=${pkgs.OVMF.variables} + export TEST_GUEST_FIRMWARE_CODE=${firmwarePkgs.OVMF.firmware} + export TEST_GUEST_FIRMWARE_VARS=${firmwarePkgs.OVMF.variables} export TEST_GUEST_MACHINE=${if isAarch64 then "virt" else "q35"} export TEST_GUEST_ACCELERATOR=${if isDarwin then "hvf" else "kvm"} export TEST_GUEST_ARCHITECTURE=${architecture} diff --git a/proto/openshell.proto b/proto/openshell.proto index 6f1481b521..246fe0626f 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1620,9 +1620,23 @@ message ProviderCredentialRefreshStatus { ProviderCredentialRefreshStrategy strategy = 4; string status = 5; int64 expires_at_ms = 6; + // Next automatic refresh time in Unix epoch milliseconds. A value of + // 9223372036854775807 (int64 max) means no automatic retry is scheduled; + // consumers should render it as unset and use recovery_action to determine + // the required recovery workflow. int64 next_refresh_at_ms = 7; int64 last_refresh_at_ms = 8; string last_error = 9; + ProviderCredentialRefreshRecoveryAction recovery_action = 10; + // Stable gateway-owned failure identifier, for example + // "oauth_invalid_grant". This is not provider-controlled prose and + // incorporates any recognized top-level OAuth error classification. + string failure_code = 11; + // A bounded, recognized provider subtype that refines failure_code; clients + // do not need a separate provider_error field. Unknown provider-controlled + // values are not persisted or returned. + string provider_error_subtype = 12; + int64 last_error_at_ms = 13; } // Provider profile local discovery declaration. @@ -1643,6 +1657,7 @@ message StoredProviderCredentialRefreshState { // are not automatically migrated before OpenShell 0.1.0. repeated string secret_material_keys = 7; int64 expires_at_ms = 8; + // int64 max parks the refresh until an explicit rotation or reconfiguration. int64 next_refresh_at_ms = 9; int64 last_refresh_at_ms = 10; string status = 11; @@ -1671,6 +1686,12 @@ message StoredProviderCredentialRefreshState { // Cleanup is retried by the refresh worker so a gateway crash or temporary // credential-backend outage does not lose the deletion reference. repeated StoredRefreshMaterialDeletion pending_secret_deletions = 20; + // Structured recovery details for the most recent refresh failure. These + // fields contain only gateway-owned codes and recognized bounded values. + ProviderCredentialRefreshRecoveryAction recovery_action = 21; + string failure_code = 22; + string provider_error_subtype = 23; + int64 last_error_at_ms = 24; } message StoredRefreshMaterialDeletion { @@ -2787,6 +2808,18 @@ enum WorkspaceRole { WORKSPACE_ROLE_ADMIN = 2; } +// Stable recovery action for the most recent provider credential refresh +// failure. Kept after the pre-existing enums so adding it does not renumber +// their generated descriptors. Clients should use this field instead of +// parsing last_error. +enum ProviderCredentialRefreshRecoveryAction { + PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_UNSPECIFIED = 0; + PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_RETRY = 1; + PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE = 2; + PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_FIX_CONFIGURATION = 3; + PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE = 4; +} + // Workspace membership record. message WorkspaceMember { openshell.datamodel.v1.ObjectMeta metadata = 1; diff --git a/pyproject.toml b/pyproject.toml index fb8aac17a2..247a40b412 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,8 +2,8 @@ # SPDX-License-Identifier: Apache-2.0 [build-system] -requires = ["maturin>=1.5,<2.0"] -build-backend = "maturin" +requires = ["setuptools>=80", "setuptools-scm[simple]>=8"] +build-backend = "setuptools.build_meta" [project] name = "openshell" @@ -29,8 +29,6 @@ classifiers = [ "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", - "Programming Language :: Rust", - "License :: OSI Approved :: Apache Software License", "Topic :: Security", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Artificial Intelligence", @@ -51,33 +49,23 @@ dev = [ "pytest-xdist>=3.0", "ruff>=0.4", "ty>=0.0.1a6", - "maturin>=1.5,<2.0", - "setuptools-scm>=8", "grpcio-tools>=1.60", "pyelftools>=0.30", "pyyaml==6.0.2", "types-pyyaml>=6.0.12.20260518", ] -[tool.uv] -# Don't try to install the root package with uv sync - use uv pip install . instead -# This is needed because maturin bin packages don't install the binary with editable installs -# (both `uv pip install -e .` and `maturin develop` skip binary installation) -# Use `uv pip install .` (without -e) to install the openshell CLI binary -package = false +[tool.setuptools] +package-dir = { "" = "python" } +include-package-data = false -[tool.maturin] -bindings = "bin" -manifest-path = "crates/openshell-cli/Cargo.toml" -python-source = "python" -module-name = "openshell" -# _proto/ stubs are gitignored; force them into the wheel so git-aware -# maturin builds don't drop them (package-relative paths). -include = [ - "openshell/_proto/*_pb2.py", - "openshell/_proto/*_pb2_grpc.py", - "openshell/_proto/*.pyi", -] +[tool.setuptools.packages.find] +where = ["python"] +include = ["openshell*"] +namespaces = false + +[tool.setuptools.package-data] +openshell = ["py.typed", "_proto/*.py", "_proto/*.pyi"] [tool.ruff] target-version = "py311" diff --git a/python/openshell/__init__.py b/python/openshell/__init__.py index 0aa343ed60..27f317578b 100644 --- a/python/openshell/__init__.py +++ b/python/openshell/__init__.py @@ -6,6 +6,7 @@ from __future__ import annotations from .sandbox import ( + ClientCredentialsAuth, ExecChunk, ExecResult, InferenceRouteClient, @@ -29,6 +30,7 @@ __version__ = "0.0.0" __all__ = [ + "ClientCredentialsAuth", "ExecChunk", "ExecResult", "InferenceRouteClient", diff --git a/python/openshell/sandbox.py b/python/openshell/sandbox.py index b66ed936b6..94f3c57def 100644 --- a/python/openshell/sandbox.py +++ b/python/openshell/sandbox.py @@ -6,7 +6,9 @@ import base64 import contextlib import errno +import ipaddress import json +import math import os import pathlib import sys @@ -34,6 +36,8 @@ ("method", "timeout", "metadata", "credentials", "wait_for_ready", "compression"), ) +_OAUTH_MAX_RESPONSE_BYTES = 1 << 20 + class _ClientCallDetails(_ClientCallDetailsBase, grpc.ClientCallDetails): pass @@ -126,6 +130,238 @@ def _normalize_bearer( return lambda: token +def _is_loopback_host(hostname: str | None) -> bool: + if hostname is None: + return False + if hostname.lower() == "localhost": + return True + with contextlib.suppress(ValueError): + return ipaddress.ip_address(hostname).is_loopback + return False + + +def _is_local_grpc_endpoint(endpoint: str) -> bool: + if endpoint.startswith("unix:"): + return True + return _is_loopback_host(urlparse(f"//{endpoint}").hostname) + + +def _validate_oauth_url(name: str, raw: str) -> str: + """Validate an OAuth endpoint without reflecting attacker-controlled URLs.""" + parsed = urlparse(raw) + if not parsed.scheme or not parsed.hostname or parsed.username or parsed.password: + raise SandboxError(f"invalid OAuth {name} URL") + if parsed.fragment: + raise SandboxError(f"OAuth {name} URL must not contain a fragment") + if parsed.scheme == "https": + return raw + if parsed.scheme == "http" and _is_loopback_host(parsed.hostname): + return raw + raise SandboxError( + f"OAuth {name} URL must use HTTPS (HTTP is allowed only for loopback hosts)" + ) + + +def _oauth_json_request( + client: httpx.Client, + method: str, + url: str, + *, + kind: str, + headers: Mapping[str, str], + data: Mapping[str, str] | None = None, +) -> tuple[int, dict[str, object]]: + """Read a bounded JSON response without retaining arbitrary error bodies.""" + with client.stream(method, url, headers=headers, data=data) as response: + if response.status_code != 200: + return response.status_code, {} + content = bytearray() + for chunk in response.iter_bytes(): + content.extend(chunk) + if len(content) > _OAUTH_MAX_RESPONSE_BYTES: + raise SandboxError(f"OAuth {kind} response is too large") + try: + payload = json.loads(content) + except (UnicodeDecodeError, json.JSONDecodeError): + raise SandboxError(f"OAuth {kind} returned invalid JSON") from None + if not isinstance(payload, dict): + raise SandboxError(f"OAuth {kind} returned invalid JSON") + return 200, payload + + +class ClientCredentialsAuth: + """Renewable OAuth 2.0 client-credentials bearer provider. + + Tokens and client secrets remain in memory. The first RPC lazily performs + discovery and an exchange; later RPCs share the cached token until it is + within 30 seconds of expiry. Concurrent callers share one exchange. + """ + + def __init__( + self, + *, + client_secret: str | Callable[[], str], + issuer: str | None = None, + client_id: str | None = None, + scopes: Sequence[str] | None = None, + audience: str | None = None, + insecure: bool = False, + timeout: float = 30.0, + _transport: httpx.BaseTransport | None = None, + ) -> None: + if not isinstance(client_secret, str) and not callable(client_secret): + raise TypeError("client_secret must be a string or zero-argument callable") + if isinstance(client_secret, str) and not client_secret: + raise SandboxError("OAuth client secret must not be empty") + self._secret = client_secret + self._issuer = issuer + self._client_id = client_id + self._scopes = tuple(scopes) if scopes is not None else None + self._audience = audience + self._insecure = insecure + self._timeout = timeout + self._transport = _transport + self._lock = threading.Lock() + self._access_token: str | None = None + self._expires_at = 0.0 + self._token_endpoint: str | None = None + + def __repr__(self) -> str: + return ( + "ClientCredentialsAuth(issuer=" + f"{self._issuer!r}, client_id={self._client_id!r}, " + f"scopes={self._scopes!r}, audience={self._audience!r})" + ) + + def _apply_gateway_metadata( + self, metadata: Mapping[str, object], *, insecure: bool = False + ) -> None: + """Fill omitted fields and apply active-gateway transport settings.""" + if self._issuer is None: + value = metadata.get("oidc_issuer") + self._issuer = value if isinstance(value, str) and value else None + if self._client_id is None: + value = metadata.get("oidc_client_id") + self._client_id = value if isinstance(value, str) and value else None + if self._audience is None: + value = metadata.get("oidc_audience") + self._audience = value if isinstance(value, str) and value else None + if self._scopes is None: + value = metadata.get("oidc_scopes") + if isinstance(value, str): + self._scopes = tuple(value.split()) + # Preserve an explicit provider-level opt-in while also honoring the + # active-gateway construction flag used by the existing OIDC refresher. + self._insecure = self._insecure or insecure + + def __call__(self) -> str: + if ( + self._access_token is not None + and time.time() + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS < self._expires_at + ): + return self._access_token + with self._lock: + if ( + self._access_token is not None + and time.time() + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS < self._expires_at + ): + return self._access_token + token, expires_at = self._exchange() + self._access_token = token + self._expires_at = expires_at + return token + + def _exchange(self) -> tuple[str, float]: + if not self._issuer or not self._client_id: + raise SandboxError("OAuth client credentials require issuer and client_id") + issuer = _validate_oauth_url("issuer", self._issuer).rstrip("/") + headers = {"accept": "application/json"} + try: + with httpx.Client( + verify=not self._insecure, + follow_redirects=False, + timeout=self._timeout, + transport=self._transport, + ) as client: + if self._token_endpoint is None: + status, discovery = _oauth_json_request( + client, + "GET", + f"{issuer}/.well-known/openid-configuration", + kind="discovery", + headers=headers, + ) + if status != 200: + raise SandboxError(f"OAuth discovery failed with HTTP {status}") + discovered = discovery.get("issuer") + if ( + not isinstance(discovered, str) + or discovered.rstrip("/") != issuer + ): + raise SandboxError("OAuth discovery issuer mismatch") + endpoint = discovery.get("token_endpoint") + if not isinstance(endpoint, str) or not endpoint: + raise SandboxError( + "OAuth discovery document is missing token_endpoint" + ) + self._token_endpoint = _validate_oauth_url( + "token endpoint", endpoint + ) + secret = self._resolve_secret() + data = { + "grant_type": "client_credentials", + "client_id": self._client_id, + "client_secret": secret, + } + if self._scopes: + data["scope"] = " ".join(self._scopes) + if self._audience: + data["audience"] = self._audience + status, payload = _oauth_json_request( + client, + "POST", + self._token_endpoint, + kind="client credentials response", + data=data, + headers=headers, + ) + except SandboxError: + raise + except httpx.HTTPError: + raise SandboxError("OAuth client credentials request failed") from None + if status != 200: + raise SandboxError( + f"OAuth client credentials exchange failed with HTTP {status}" + ) + access_token = payload.get("access_token") + expires_in = payload.get("expires_in") + if not isinstance(access_token, str) or not access_token: + raise SandboxError( + "OAuth client credentials response is missing access_token" + ) + if ( + isinstance(expires_in, bool) + or not isinstance(expires_in, (int, float)) + or not math.isfinite(expires_in) + or expires_in <= 0 + ): + raise SandboxError( + "OAuth client credentials response requires a positive finite expires_in" + ) + return access_token, time.time() + float(expires_in) + + def _resolve_secret(self) -> str: + if isinstance(self._secret, str): + return self._secret + try: + value = self._secret() + except Exception: + raise SandboxError("OAuth client secret supplier failed") from None + if not isinstance(value, str) or not value: + raise SandboxError("OAuth client secret supplier returned an empty secret") + return value + + @dataclass(frozen=True) class SandboxStatusRef: phase: int @@ -270,6 +506,7 @@ def __init__( *, tls: TlsConfig | None = None, bearer_token: str | Callable[[], str] | None = None, + client_credentials: ClientCredentialsAuth | None = None, timeout: float = 30.0, cluster_name: str | None = None, _bearer_close: Callable[[], None] | None = None, @@ -284,6 +521,9 @@ def __init__( runtime refresh). Combines with `tls` — pass both when the gateway uses mTLS for transport identity and OIDC for user identity. + client_credentials: renewable OAuth client-credentials provider. + Mutually exclusive with `bearer_token`. A non-loopback endpoint + requires `tls` so the acquired bearer is never sent in cleartext. timeout: default per-call timeout in seconds. cluster_name: optional friendly name for error messages. _bearer_close: internal — wired by `from_active_cluster` @@ -293,6 +533,18 @@ def __init__( lifecycle of any callable they supplied as `bearer_token`. """ + if bearer_token is not None and client_credentials is not None: + raise SandboxError( + "bearer_token and client_credentials are mutually exclusive" + ) + if ( + client_credentials is not None + and tls is None + and not _is_local_grpc_endpoint(endpoint) + ): + raise SandboxError( + "OAuth client credentials require TLS for non-loopback gateway endpoints" + ) self._endpoint = endpoint self._timeout = timeout self._cluster_name = cluster_name @@ -312,7 +564,7 @@ def __init__( ), ) self._channel = grpc.secure_channel(endpoint, credentials) - provider = _normalize_bearer(bearer_token) + provider = _normalize_bearer(client_credentials or bearer_token) if provider is not None: self._channel = grpc.intercept_channel( self._channel, @@ -329,6 +581,7 @@ def from_active_cluster( auto_refresh: bool = True, write_back: bool = True, insecure: bool = False, + client_credentials: ClientCredentialsAuth | None = None, ) -> SandboxClient: """Construct a `SandboxClient` from the active gateway's on-disk state. @@ -357,6 +610,10 @@ def from_active_cluster( for OIDC discovery and refresh calls. Mirrors the Rust CLI's `--insecure` flag for issuers behind self-signed certs. Off by default. + client_credentials: renewable OAuth client-credentials provider. + Omitted issuer, client ID, audience, and scopes are filled from + the registered gateway metadata. This provider does not read or + write `oidc_token.json`. Remote plaintext gateways are rejected. """ cluster_name = cluster or _resolve_active_cluster() gateway_dir = _xdg_config_home() / "openshell" / "gateways" / cluster_name @@ -396,7 +653,13 @@ def from_active_cluster( # a non-OIDC gateway should NOT cause us to attach a bearer. bearer_token: Callable[[], str] | None = None bearer_close: Callable[[], None] | None = None - if metadata.get("auth_mode") == "oidc": + if client_credentials is not None: + if metadata.get("auth_mode") != "oidc": + raise SandboxError( + f"gateway '{cluster_name}' is not configured for OIDC" + ) + client_credentials._apply_gateway_metadata(metadata, insecure=insecure) + elif metadata.get("auth_mode") == "oidc": bearer_token, bearer_close = _make_cluster_bearer_provider( gateway_dir, cluster_name, @@ -409,6 +672,7 @@ def from_active_cluster( endpoint, tls=tls, bearer_token=bearer_token, + client_credentials=client_credentials, timeout=timeout, cluster_name=cluster_name, _bearer_close=bearer_close, @@ -905,10 +1169,12 @@ def __init__( auto_refresh: bool = True, write_back: bool = True, insecure: bool = False, + client_credentials: ClientCredentialsAuth | None = None, ) -> None: """Bind a Sandbox context to the active gateway. - OIDC kwargs (`auto_refresh`, `write_back`, `insecure`) forward + OIDC kwargs (`auto_refresh`, `write_back`, `insecure`, and + `client_credentials`) forward directly to `SandboxClient.from_active_cluster` and have the same semantics. They're surfaced on `Sandbox` so callers using the higher-level wrapper get parity with `SandboxClient` for @@ -928,6 +1194,7 @@ def __init__( self._auto_refresh = auto_refresh self._write_back = write_back self._insecure = insecure + self._client_credentials = client_credentials self._client: SandboxClient | None = None self._session: SandboxSession | None = None @@ -959,6 +1226,7 @@ def __enter__(self) -> Sandbox: auto_refresh=self._auto_refresh, write_back=self._write_back, insecure=self._insecure, + client_credentials=self._client_credentials, ) self._client = client diff --git a/python/openshell/sandbox_test.py b/python/openshell/sandbox_test.py index a059192460..d70aae49cc 100644 --- a/python/openshell/sandbox_test.py +++ b/python/openshell/sandbox_test.py @@ -19,8 +19,10 @@ import openshell.sandbox as sandbox_module from openshell._proto import openshell_pb2 from openshell.sandbox import ( + _OIDC_TOKEN_EXPIRY_GRACE_SECONDS, _PYTHON_CLOUDPICKLE_BOOTSTRAP, _SANDBOX_PYTHON_BIN, + ClientCredentialsAuth, InferenceRouteClient, Sandbox, SandboxClient, @@ -36,9 +38,354 @@ _OidcRefresher, _read_oidc_token_bundle, _sandbox_ref, + _validate_oauth_url, ) +def _client_credentials_fixture() -> dict[str, Any]: + return json.loads( + ( + Path(__file__).parents[2] / "sdk/conformance/oauth-client-credentials.json" + ).read_text() + ) + + +def test_oauth_client_credentials_conformance_fixture() -> None: + fixture = _client_credentials_fixture() + assert fixture["expiry"]["leeway_seconds"] == _OIDC_TOKEN_EXPIRY_GRACE_SECONDS + for value in fixture["urls"]["allowed"]: + assert _validate_oauth_url("issuer", value) == value + for value in fixture["urls"]["rejected"]: + with pytest.raises(SandboxError): + _validate_oauth_url("issuer", value) + + +def test_client_credentials_auth_exact_form_cache_and_redaction() -> None: + fixture = _client_credentials_fixture() + seen: list[tuple[str, bytes]] = [] + + def handler(request: Any) -> Any: + import httpx + + seen.append((str(request.url), bytes(request.content))) + if request.method == "GET": + return httpx.Response( + 200, + json={ + "issuer": "https://issuer.example.com/", + "token_endpoint": "https://issuer.example.com/token", + }, + ) + return httpx.Response( + 200, + json={ + "access_token": "service-token", + "expires_in": fixture["expiry"]["valid_expires_in"], + }, + ) + + import httpx + + auth = ClientCredentialsAuth( + issuer="https://issuer.example.com", + client_id="service-client", + client_secret="conformance-secret", + scopes=("sandbox:read", "sandbox:write"), + audience="openshell-gateway", + _transport=httpx.MockTransport(handler), + ) + assert auth() == "service-token" + assert auth() == "service-token" + assert len(seen) == 2 + form = dict(__import__("urllib.parse").parse.parse_qsl(seen[1][1].decode())) + assert form == { + field: fixture["request"][field] + for field in ( + "grant_type", + "client_id", + "client_secret", + "scope", + "audience", + ) + } + assert "conformance-secret" not in repr(auth) + + +def test_client_credentials_auth_preserves_explicit_empty_scopes() -> None: + import httpx + + form: dict[str, str] = {} + + def handler(request: Any) -> Any: + if request.method == "GET": + return httpx.Response( + 200, + json={ + "issuer": "https://issuer.example.com", + "token_endpoint": "https://issuer.example.com/token", + }, + ) + form.update( + __import__("urllib.parse").parse.parse_qsl(request.content.decode()) + ) + return httpx.Response(200, json={"access_token": "token", "expires_in": 120}) + + auth = ClientCredentialsAuth( + issuer="https://issuer.example.com", + client_id="client", + client_secret="secret", + scopes=(), + _transport=httpx.MockTransport(handler), + ) + auth._apply_gateway_metadata({"oidc_scopes": "sandbox:read sandbox:write"}) + + assert auth() == "token" + assert auth._scopes == () + assert "scope" not in form + + +@pytest.mark.parametrize( + "expires_in", _client_credentials_fixture()["expiry"]["invalid_expires_in"] +) +def test_client_credentials_auth_rejects_invalid_expiry(expires_in: object) -> None: + import httpx + + fixture = _client_credentials_fixture() + + def handler(request: Any) -> Any: + if request.method == "GET": + return httpx.Response( + 200, + json={ + "issuer": fixture["discovery"]["matching_issuer"], + "token_endpoint": "https://issuer.example.com/token", + }, + ) + return httpx.Response( + 200, json={"access_token": "token", "expires_in": expires_in} + ) + + auth = ClientCredentialsAuth( + issuer=fixture["discovery"]["configured_issuer"], + client_id="client", + client_secret="secret", + _transport=httpx.MockTransport(handler), + ) + with pytest.raises(SandboxError, match="positive finite expires_in"): + auth() + + +@pytest.mark.parametrize( + "status", _client_credentials_fixture()["discovery"]["redirect_statuses"] +) +def test_client_credentials_auth_refuses_discovery_redirect(status: int) -> None: + import httpx + + requests = 0 + + def handler(_request: Any) -> Any: + nonlocal requests + requests += 1 + return httpx.Response( + status, + headers={"location": "https://attacker.example.com/discovery"}, + ) + + auth = ClientCredentialsAuth( + issuer="https://issuer.example.com", + client_id="client", + client_secret="secret", + _transport=httpx.MockTransport(handler), + ) + with pytest.raises(SandboxError, match=f"HTTP {status}"): + auth() + assert requests == 1 + + +@pytest.mark.parametrize( + "status", _client_credentials_fixture()["discovery"]["redirect_statuses"] +) +def test_client_credentials_auth_refuses_token_redirect(status: int) -> None: + import httpx + + requests: list[str] = [] + + def handler(request: Any) -> Any: + requests.append(str(request.url)) + if request.method == "GET": + return httpx.Response( + 200, + json={ + "issuer": "https://issuer.example.com", + "token_endpoint": "https://issuer.example.com/token", + }, + ) + return httpx.Response( + status, + headers={"location": "https://attacker.example.com/token"}, + ) + + auth = ClientCredentialsAuth( + issuer="https://issuer.example.com", + client_id="client", + client_secret="secret", + _transport=httpx.MockTransport(handler), + ) + with pytest.raises(SandboxError, match=f"HTTP {status}"): + auth() + assert requests == [ + "https://issuer.example.com/.well-known/openid-configuration", + "https://issuer.example.com/token", + ] + + +def test_client_credentials_auth_rejects_discovery_issuer_mismatch() -> None: + import httpx + + fixture = _client_credentials_fixture() + auth = ClientCredentialsAuth( + issuer=fixture["discovery"]["configured_issuer"], + client_id="client", + client_secret="secret", + _transport=httpx.MockTransport( + lambda _request: httpx.Response( + 200, + json={ + "issuer": fixture["discovery"]["mismatched_issuer"], + "token_endpoint": "https://attacker.example.com/token", + }, + ) + ), + ) + with pytest.raises(SandboxError, match="issuer mismatch"): + auth() + + +def test_client_credentials_auth_rejects_oversized_response() -> None: + import httpx + + fixture = _client_credentials_fixture() + auth = ClientCredentialsAuth( + issuer="https://issuer.example.com", + client_id="client", + client_secret="secret", + _transport=httpx.MockTransport( + lambda _request: httpx.Response( + 200, content=b"x" * (fixture["limits"]["max_response_bytes"] + 1) + ) + ), + ) + with pytest.raises(SandboxError, match="too large"): + auth() + + +def test_client_credentials_auth_single_flight_and_retry() -> None: + import httpx + + token_calls = 0 + release = threading.Event() + + def handler(request: Any) -> Any: + nonlocal token_calls + if request.method == "GET": + return httpx.Response( + 200, + json={ + "issuer": "http://127.0.0.1:8080", + "token_endpoint": "http://127.0.0.1:8080/token", + }, + ) + token_calls += 1 + release.wait(timeout=2) + return httpx.Response(200, json={"access_token": "shared", "expires_in": 120}) + + auth = ClientCredentialsAuth( + issuer="http://127.0.0.1:8080", + client_id="client", + client_secret="secret", + _transport=httpx.MockTransport(handler), + ) + results: list[str] = [] + threads = [ + threading.Thread(target=lambda: results.append(auth())) for _ in range(8) + ] + for thread in threads: + thread.start() + while token_calls == 0: + time.sleep(0.001) + release.set() + for thread in threads: + thread.join() + assert results == ["shared"] * 8 + assert token_calls == 1 + + +def test_client_credentials_auth_fails_closed_and_redacts_errors() -> None: + import httpx + + def supplier() -> str: + raise RuntimeError("supplier-sensitive-detail") + + auth = ClientCredentialsAuth( + issuer="http://localhost:8080", + client_id="client", + client_secret=supplier, + _transport=httpx.MockTransport( + lambda _request: httpx.Response( + 200, + json={ + "issuer": "http://localhost:8080", + "token_endpoint": "http://localhost:8080/token", + }, + ) + ), + ) + with pytest.raises(SandboxError, match="supplier failed") as exc_info: + auth() + assert "supplier-sensitive-detail" not in str(exc_info.value) + with pytest.raises(SandboxError, match="must use HTTPS"): + ClientCredentialsAuth( + issuer="http://remote.example.com", + client_id="client", + client_secret="secret", + )() + + +def test_client_credentials_auth_does_not_use_stale_token_after_renewal_failure() -> ( + None +): + import httpx + + exchanges = 0 + + def handler(request: Any) -> Any: + nonlocal exchanges + if request.method == "GET": + return httpx.Response( + 200, + json={ + "issuer": "http://localhost:8080", + "token_endpoint": "http://localhost:8080/token", + }, + ) + exchanges += 1 + if exchanges == 1: + return httpx.Response(200, json={"access_token": "stale", "expires_in": 30}) + return httpx.Response(503, json={"error": "provider-sensitive-detail"}) + + auth = ClientCredentialsAuth( + issuer="http://localhost:8080", + client_id="client", + client_secret="secret", + _transport=httpx.MockTransport(handler), + ) + assert auth() == "stale" + with pytest.raises(SandboxError, match="HTTP 503") as exc_info: + auth() + assert "stale" not in str(exc_info.value) + assert "provider-sensitive-detail" not in str(exc_info.value) + + class _FakeStub: def __init__(self) -> None: self.request: openshell_pb2.ExecSandboxRequest | None = None @@ -1187,6 +1534,113 @@ def bearer_close() -> None: assert closed[0] == 1 +def test_from_active_cluster_fills_client_credentials_from_metadata( + tmp_path: Path, + monkeypatch: Any, +) -> None: + gateway_dir = _setup_gateway_dir(tmp_path, monkeypatch, auth_mode="oidc") + metadata_path = gateway_dir / "metadata.json" + metadata = json.loads(metadata_path.read_text()) + metadata.update( + { + "oidc_issuer": "https://issuer.example.com", + "oidc_client_id": "service-client", + "oidc_audience": "gateway", + "oidc_scopes": "sandbox:read sandbox:write", + } + ) + metadata_path.write_text(json.dumps(metadata)) + auth = ClientCredentialsAuth(client_secret="secret") + client = SandboxClient.from_active_cluster( + client_credentials=auth, + insecure=True, + ) + try: + assert auth._issuer == "https://issuer.example.com" + assert auth._client_id == "service-client" + assert auth._audience == "gateway" + assert auth._scopes == ("sandbox:read", "sandbox:write") + assert auth._insecure is True + finally: + client.close() + + +def test_sandbox_client_rejects_client_credentials_on_remote_plaintext( + monkeypatch: Any, +) -> None: + channel_opened = False + + def insecure_channel(_endpoint: str) -> Any: + nonlocal channel_opened + channel_opened = True + raise AssertionError("plaintext channel must not be opened") + + monkeypatch.setattr(sandbox_module.grpc, "insecure_channel", insecure_channel) + auth = ClientCredentialsAuth( + issuer="https://issuer.example.com", + client_id="client", + client_secret="secret", + ) + with pytest.raises(SandboxError, match="require TLS"): + SandboxClient("gateway.example.com:50051", client_credentials=auth) + assert not channel_opened + + +@pytest.mark.parametrize( + "endpoint", + ["localhost:50051", "127.42.0.1:50051", "[::1]:50051"], +) +def test_sandbox_client_allows_client_credentials_on_plaintext_loopback( + endpoint: str, +) -> None: + auth = ClientCredentialsAuth( + issuer="https://issuer.example.com", + client_id="client", + client_secret="secret", + ) + client = SandboxClient(endpoint, client_credentials=auth) + client.close() + + +def test_from_active_cluster_rejects_client_credentials_on_remote_plaintext( + tmp_path: Path, + monkeypatch: Any, +) -> None: + gateway_dir = _setup_gateway_dir( + tmp_path, + monkeypatch, + endpoint="http://gateway.example.com:8080", + auth_mode="oidc", + ) + metadata_path = gateway_dir / "metadata.json" + metadata = json.loads(metadata_path.read_text()) + metadata.update( + { + "oidc_issuer": "https://issuer.example.com", + "oidc_client_id": "service-client", + } + ) + metadata_path.write_text(json.dumps(metadata)) + + auth = ClientCredentialsAuth(client_secret="secret") + with pytest.raises(SandboxError, match="require TLS"): + SandboxClient.from_active_cluster(client_credentials=auth) + + +def test_sandbox_client_rejects_ambiguous_bearer_configuration() -> None: + auth = ClientCredentialsAuth( + issuer="https://issuer.example.com", + client_id="client", + client_secret="secret", + ) + with pytest.raises(SandboxError, match="mutually exclusive"): + SandboxClient( + "localhost:50051", + bearer_token="static", + client_credentials=auth, + ) + + def test_sandbox_client_close_releases_refresher_http_client( tmp_path: Path, monkeypatch: Any, diff --git a/python/wheel_verifier_test.py b/python/wheel_verifier_test.py new file mode 100644 index 0000000000..777f348f73 --- /dev/null +++ b/python/wheel_verifier_test.py @@ -0,0 +1,143 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import importlib.util +import sys +from pathlib import Path +from zipfile import ZipFile + +import pytest + + +def _load_verifier_module(): + path = Path(__file__).resolve().parents[1] / "tasks/scripts/verify-python-wheel.py" + spec = importlib.util.spec_from_file_location("openshell_wheel_verifier", path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +verifier = _load_verifier_module() + + +def _wheel_files() -> set[str]: + files = { + "openshell/__init__.py", + "openshell/sandbox.py", + "openshell/py.typed", + "openshell/_proto/__init__.py", + } + for stem in ("datamodel", "inference", "openshell", "options", "sandbox"): + files.add(f"openshell/_proto/{stem}_pb2.py") + files.add(f"openshell/_proto/{stem}_pb2.pyi") + files.add(f"openshell/_proto/{stem}_pb2_grpc.py") + return files + + +def _write_wheel( + directory: Path, + *, + version: str = "1.2.3", + tag: str = "py3-none-any", + files: set[str] | None = None, + entry_points: str | None = None, +) -> Path: + wheel = directory / f"openshell-{version}-{tag}.whl" + dist_info = f"openshell-{version}.dist-info" + with ZipFile(wheel, "w") as archive: + for name in files if files is not None else _wheel_files(): + archive.writestr(name, "") + archive.writestr( + f"{dist_info}/METADATA", + f"Metadata-Version: 2.4\nName: openshell\nVersion: {version}\n", + ) + archive.writestr( + f"{dist_info}/WHEEL", + f"Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: {tag}\n", + ) + if entry_points is not None: + archive.writestr(f"{dist_info}/entry_points.txt", entry_points) + return wheel + + +def test_accepts_pure_python_sdk_wheel(tmp_path: Path) -> None: + wheel = _write_wheel(tmp_path) + + assert verifier.verify_wheel(wheel, "1.2.3") == wheel + + +def test_requires_exactly_one_wheel_in_directory(tmp_path: Path) -> None: + _write_wheel(tmp_path, version="1.2.3") + _write_wheel(tmp_path, version="1.2.4") + + with pytest.raises(ValueError, match="expected exactly one wheel"): + verifier.verify_wheel(tmp_path) + + +def test_rejects_missing_generated_proto(tmp_path: Path) -> None: + files = _wheel_files() - {"openshell/_proto/sandbox_pb2.py"} + wheel = _write_wheel(tmp_path, files=files) + + with pytest.raises(ValueError, match=r"sandbox_pb2\.py"): + verifier.verify_wheel(wheel) + + +def test_rejects_bundled_cli(tmp_path: Path) -> None: + files = _wheel_files() | {"openshell-1.2.3.data/scripts/openshell"} + wheel = _write_wheel(tmp_path, files=files) + + with pytest.raises(ValueError, match="contains an openshell executable"): + verifier.verify_wheel(wheel) + + +def test_rejects_bundled_windows_cli(tmp_path: Path) -> None: + files = _wheel_files() | {"openshell-1.2.3.data/scripts/openshell.exe"} + wheel = _write_wheel(tmp_path, files=files) + + with pytest.raises(ValueError, match="contains an openshell executable"): + verifier.verify_wheel(wheel) + + +def test_rejects_openshell_console_script(tmp_path: Path) -> None: + wheel = _write_wheel( + tmp_path, + entry_points="[console_scripts]\nopenshell = openshell.cli:main\n", + ) + + with pytest.raises(ValueError, match="defines an openshell console script"): + verifier.verify_wheel(wheel) + + +def test_rejects_native_extension(tmp_path: Path) -> None: + files = _wheel_files() | {"openshell/_native.so"} + wheel = _write_wheel(tmp_path, files=files) + + with pytest.raises(ValueError, match="contains native files"): + verifier.verify_wheel(wheel) + + +def test_rejects_bytecode(tmp_path: Path) -> None: + files = _wheel_files() | {"openshell/__pycache__/sandbox.cpython-314.pyc"} + wheel = _write_wheel(tmp_path, files=files) + + with pytest.raises(ValueError, match="contains Python bytecode"): + verifier.verify_wheel(wheel) + + +def test_rejects_platform_wheel(tmp_path: Path) -> None: + wheel = _write_wheel(tmp_path, tag="cp311-cp311-manylinux_2_28_x86_64") + + with pytest.raises(ValueError, match="not platform-independent"): + verifier.verify_wheel(wheel) + + +def test_rejects_unexpected_version(tmp_path: Path) -> None: + wheel = _write_wheel(tmp_path) + + with pytest.raises(ValueError, match=r"expected version 1\.2\.4"): + verifier.verify_wheel(wheel, "1.2.4") diff --git a/sdk/conformance/oauth-client-credentials.json b/sdk/conformance/oauth-client-credentials.json new file mode 100644 index 0000000000..f31d0fe683 --- /dev/null +++ b/sdk/conformance/oauth-client-credentials.json @@ -0,0 +1,44 @@ +{ + "request": { + "grant_type": "client_credentials", + "client_id": "service-client", + "client_secret": "conformance-secret", + "scopes": ["sandbox:read", "sandbox:write"], + "scope": "sandbox:read sandbox:write", + "audience": "openshell-gateway", + "forbidden_implicit_scopes": ["openid", "profile", "email"] + }, + "expiry": { + "leeway_seconds": 30, + "valid_expires_in": 120, + "invalid_expires_in": [0, -1, "NaN", null] + }, + "discovery": { + "configured_issuer": "https://issuer.example.com", + "matching_issuer": "https://issuer.example.com/", + "mismatched_issuer": "https://attacker.example.com", + "redirect_statuses": [301, 302, 307, 308] + }, + "limits": { + "max_response_bytes": 1048576 + }, + "urls": { + "allowed": [ + "https://issuer.example.com", + "http://localhost:8080", + "http://127.0.0.1:8080", + "http://127.42.0.1:8080", + "http://[::1]:8080" + ], + "rejected": [ + "http://issuer.example.com", + "https://user@issuer.example.com", + "https://issuer.example.com/#fragment" + ] + }, + "redaction": { + "secret": "conformance-secret", + "supplier_error": "supplier-sensitive-detail", + "provider_body": "provider-sensitive-detail" + } +} diff --git a/sdk/go/README.md b/sdk/go/README.md index 9357ffa412..42207faf13 100644 --- a/sdk/go/README.md +++ b/sdk/go/README.md @@ -179,15 +179,35 @@ token, err := oidc.DeviceLogin(ctx, ) ``` -For service accounts, use client credentials: +For a one-shot service-account token exchange, use `ClientCredentials`. For a +long-running SDK client, attach the renewable, memory-only auth provider: ```go -token, err := oidc.ClientCredentials(ctx, +auth, err := oidc.NewClientCredentialsAuth( oidc.WithGateway("my-gateway"), - oidc.WithClientSecret("service-secret"), + oidc.WithClientSecretProvider(func(context.Context) (string, error) { + return os.Getenv("OPENSHELL_OIDC_CLIENT_SECRET"), nil + }), ) +if err != nil { + log.Fatal(err) +} + +client, err := v1.NewClient(v1.Config{ + Address: "gateway.example.com:443", + Auth: auth, + TLS: tlsConfig, +}) +if err != nil { + log.Fatal(err) +} +defer client.Close() ``` +You can use explicit `WithIssuer`, `WithClientID`, `WithScopes`, and +`WithAudience` options instead of `WithGateway`. The provider repeats the grant +before expiry and never writes the secret or access token to disk. + See the [oidc package docs](https://pkg.go.dev/github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/oidc) for all options and flows. See the [Getting Started](https://ro14nd.de/openshell-sdk-go/getting-started.html) guide for the full walkthrough. @@ -281,7 +301,7 @@ consumers import a single package. See the [Architecture](https://ro14nd.de/open | Typed errors (`IsNotFound`, `IsAlreadyExists`, `IsConflict`, ...) | `StatusError` | [Error Handling](https://ro14nd.de/openshell-sdk-go/error-handling.html) | | Real-time watch with auto-stop on terminal phase | `WatchInterface[T]` | [Sandboxes](https://ro14nd.de/openshell-sdk-go/api/sandboxes.html) | | Fake client for testing (no gRPC server needed) | `fake.Client` | [Testing](https://ro14nd.de/openshell-sdk-go/testing.html) | -| OIDC login (browser, keyboard, device code, client credentials) | `oidc.Login`, `oidc.DeviceLogin`, `oidc.ClientCredentials` | [OIDC](https://pkg.go.dev/github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/oidc) | +| OIDC login and renewable service auth | `oidc.Login`, `oidc.DeviceLogin`, `oidc.ClientCredentials`, `oidc.NewClientCredentialsAuth` | [OIDC](https://pkg.go.dev/github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/oidc) | | Gateway config convenience (load CLI gateway configs, auto-wire auth) | `gateway.NewClient`, `gateway.LoadConfig` | [Gateway](https://ro14nd.de/openshell-sdk-go/api/gateway.html) | ## Prerequisites diff --git a/sdk/go/docs/src/api/oidc.md b/sdk/go/docs/src/api/oidc.md index ae30f35a1c..110015ae60 100644 --- a/sdk/go/docs/src/api/oidc.md +++ b/sdk/go/docs/src/api/oidc.md @@ -69,6 +69,17 @@ Performs a non-interactive OAuth2 client credentials grant. Requires combined with `WithClientSecret`). The client secret is never included in error messages. +### NewClientCredentialsAuth + +```go +func NewClientCredentialsAuth(opts ...LoginOption) (types.AuthProvider, error) +``` + +Returns a lazy renewable auth provider for `v1.Config.Auth` or +`gateway.WithAuth`. It caches access tokens in memory, renews within 30 seconds +of expiry, coalesces concurrent exchanges, and fails closed if renewal fails. +Use `WithClientSecretProvider` when the application rotates secret material. + ## Options | Option | Description | @@ -76,7 +87,9 @@ in error messages. | `WithIssuer(url)` | OIDC provider issuer URL | | `WithClientID(id)` | OAuth2 client ID | | `WithClientSecret(secret)` | OAuth2 client secret (for client credentials) | -| `WithScopes(scopes...)` | Custom scopes (default: openid, profile, email) | +| `WithClientSecretProvider(provider)` | Resolve the client secret for each exchange | +| `WithAudience(audience)` | Optional OAuth2 resource-server audience | +| `WithScopes(scopes...)` | Custom scopes (client credentials has no implicit scopes) | | `WithCallbackPort(port)` | Fixed port for localhost callback (default: tries 8000, then 18000) | | `WithTimeout(d)` | Auth flow timeout (default: 2 minutes) | | `WithKeyboardFlow()` | Use keyboard flow instead of browser | diff --git a/sdk/go/openshell/v1/gateway/config.go b/sdk/go/openshell/v1/gateway/config.go index c0813986e9..c35581653b 100644 --- a/sdk/go/openshell/v1/gateway/config.go +++ b/sdk/go/openshell/v1/gateway/config.go @@ -76,6 +76,12 @@ type Config struct { // OIDCClientID is the OAuth2 client ID read from metadata.json. // Empty when the gateway does not use OIDC auth. OIDCClientID string + + // OIDCAudience is the optional resource-server audience. + OIDCAudience string + + // OIDCScopes contains the configured space-separated OAuth2 scopes. + OIDCScopes string } // Info is a lightweight summary of a gateway for listing purposes. @@ -100,6 +106,8 @@ type metadataJSON struct { Name string `json:"name"` OIDCIssuer string `json:"oidc_issuer"` OIDCClientID string `json:"oidc_client_id"` + OIDCAudience string `json:"oidc_audience"` + OIDCScopes string `json:"oidc_scopes"` } // parseAuthMode converts a raw auth_mode string to the typed AuthMode. @@ -153,5 +161,7 @@ func parseMetadata(dir string) (*Config, error) { Dir: dir, OIDCIssuer: meta.OIDCIssuer, OIDCClientID: meta.OIDCClientID, + OIDCAudience: meta.OIDCAudience, + OIDCScopes: meta.OIDCScopes, }, nil } diff --git a/sdk/go/openshell/v1/gateway/config_test.go b/sdk/go/openshell/v1/gateway/config_test.go index 8411d2eef9..8ec604d2fc 100644 --- a/sdk/go/openshell/v1/gateway/config_test.go +++ b/sdk/go/openshell/v1/gateway/config_test.go @@ -158,6 +158,8 @@ func TestParseMetadata_OIDCFields(t *testing.T) { "name":"oidc-gw", "oidc_issuer":"https://auth.example.com", "oidc_client_id":"my-client-id" + ,"oidc_audience":"openshell-api", + "oidc_scopes":"sandbox:read sandbox:write" }`) cfg, err := parseMetadata(dir) @@ -166,6 +168,8 @@ func TestParseMetadata_OIDCFields(t *testing.T) { assert.Equal(t, AuthModeOIDC, cfg.AuthMode) assert.Equal(t, "https://auth.example.com", cfg.OIDCIssuer) assert.Equal(t, "my-client-id", cfg.OIDCClientID) + assert.Equal(t, "openshell-api", cfg.OIDCAudience) + assert.Equal(t, "sandbox:read sandbox:write", cfg.OIDCScopes) } func TestParseMetadata_OIDCFieldsMissing(t *testing.T) { diff --git a/sdk/go/openshell/v1/internal/converter/refresh.go b/sdk/go/openshell/v1/internal/converter/refresh.go index b417718a5b..be5ee8d03a 100644 --- a/sdk/go/openshell/v1/internal/converter/refresh.go +++ b/sdk/go/openshell/v1/internal/converter/refresh.go @@ -4,6 +4,9 @@ package converter import ( + "math" + "time" + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1" ) @@ -30,6 +33,31 @@ func RefreshStrategyFromProto(s pb.ProviderCredentialRefreshStrategy) types.Refr } } +// --- RefreshRecoveryAction enum mapping --- + +// RefreshRecoveryActionFromProto converts a proto recovery action to the curated SDK type. +func RefreshRecoveryActionFromProto(a pb.ProviderCredentialRefreshRecoveryAction) types.RefreshRecoveryAction { + switch a { + case pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_RETRY: + return types.RefreshRecoveryActionRetry + case pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE: + return types.RefreshRecoveryActionReauthorize + case pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_FIX_CONFIGURATION: + return types.RefreshRecoveryActionFixConfiguration + case pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE: + return types.RefreshRecoveryActionInvestigate + default: + return types.RefreshRecoveryActionUnspecified + } +} + +func refreshNextTimeFromMillis(ms int64) time.Time { + if ms == math.MaxInt64 { + return time.Time{} + } + return TimeFromMillis(ms) +} + // RefreshStrategyToProto converts an SDK RefreshStrategy to a proto ProviderCredentialRefreshStrategy. func RefreshStrategyToProto(s types.RefreshStrategy) pb.ProviderCredentialRefreshStrategy { switch s { @@ -58,15 +86,19 @@ func RefreshStatusFromProto(s *pb.ProviderCredentialRefreshStatus) *types.Refres return nil } return &types.RefreshStatus{ - ProviderName: s.GetProviderName(), - ProviderID: s.GetProviderId(), - CredentialKey: s.GetCredentialKey(), - Strategy: RefreshStrategyFromProto(s.GetStrategy()), - Status: s.GetStatus(), - ExpiresAt: TimeFromMillis(s.GetExpiresAtMs()), - NextRefreshAt: TimeFromMillis(s.GetNextRefreshAtMs()), - LastRefreshAt: TimeFromMillis(s.GetLastRefreshAtMs()), - LastError: s.GetLastError(), + ProviderName: s.GetProviderName(), + ProviderID: s.GetProviderId(), + CredentialKey: s.GetCredentialKey(), + Strategy: RefreshStrategyFromProto(s.GetStrategy()), + Status: s.GetStatus(), + ExpiresAt: TimeFromMillis(s.GetExpiresAtMs()), + NextRefreshAt: refreshNextTimeFromMillis(s.GetNextRefreshAtMs()), + LastRefreshAt: TimeFromMillis(s.GetLastRefreshAtMs()), + LastError: s.GetLastError(), + RecoveryAction: RefreshRecoveryActionFromProto(s.GetRecoveryAction()), + FailureCode: s.GetFailureCode(), + ProviderErrorSubtype: s.GetProviderErrorSubtype(), + LastErrorAt: TimeFromMillis(s.GetLastErrorAtMs()), } } diff --git a/sdk/go/openshell/v1/internal/converter/refresh_test.go b/sdk/go/openshell/v1/internal/converter/refresh_test.go index b426857c96..9ffa6e590a 100644 --- a/sdk/go/openshell/v1/internal/converter/refresh_test.go +++ b/sdk/go/openshell/v1/internal/converter/refresh_test.go @@ -4,6 +4,7 @@ package converter import ( + "math" "testing" "time" @@ -35,6 +36,23 @@ func TestRefreshStrategyFromProto(t *testing.T) { } } +func TestRefreshRecoveryActionFromProto(t *testing.T) { + tests := []struct { + proto pb.ProviderCredentialRefreshRecoveryAction + want v1.RefreshRecoveryAction + }{ + {pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_UNSPECIFIED, v1.RefreshRecoveryActionUnspecified}, + {pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_RETRY, v1.RefreshRecoveryActionRetry}, + {pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE, v1.RefreshRecoveryActionReauthorize}, + {pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_FIX_CONFIGURATION, v1.RefreshRecoveryActionFixConfiguration}, + {pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE, v1.RefreshRecoveryActionInvestigate}, + {pb.ProviderCredentialRefreshRecoveryAction(999), v1.RefreshRecoveryActionUnspecified}, + } + for _, tt := range tests { + assert.Equal(t, tt.want, RefreshRecoveryActionFromProto(tt.proto)) + } +} + func TestRefreshStrategyToProto(t *testing.T) { tests := []struct { sdk v1.RefreshStrategy @@ -60,15 +78,19 @@ func TestRefreshStrategyToProto(t *testing.T) { func TestRefreshStatusFromProto(t *testing.T) { proto := &pb.ProviderCredentialRefreshStatus{ - ProviderName: "anthropic", - ProviderId: "prov-1", - CredentialKey: "API_KEY", - Strategy: pb.ProviderCredentialRefreshStrategy_PROVIDER_CREDENTIAL_REFRESH_STRATEGY_OAUTH2_REFRESH_TOKEN, - Status: "active", - ExpiresAtMs: 1700000000000, - NextRefreshAtMs: 1699999000000, - LastRefreshAtMs: 1699998000000, - LastError: "none", + ProviderName: "anthropic", + ProviderId: "prov-1", + CredentialKey: "API_KEY", + Strategy: pb.ProviderCredentialRefreshStrategy_PROVIDER_CREDENTIAL_REFRESH_STRATEGY_OAUTH2_REFRESH_TOKEN, + Status: "active", + ExpiresAtMs: 1700000000000, + NextRefreshAtMs: 1699999000000, + LastRefreshAtMs: 1699998000000, + LastError: "none", + RecoveryAction: pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE, + FailureCode: "oauth_invalid_grant", + ProviderErrorSubtype: "invalid_rapt", + LastErrorAtMs: 1699997000000, } status := RefreshStatusFromProto(proto) @@ -83,6 +105,10 @@ func TestRefreshStatusFromProto(t *testing.T) { assert.Equal(t, TimeFromMillis(1699999000000), status.NextRefreshAt) assert.Equal(t, TimeFromMillis(1699998000000), status.LastRefreshAt) assert.Equal(t, "none", status.LastError) + assert.Equal(t, v1.RefreshRecoveryActionReauthorize, status.RecoveryAction) + assert.Equal(t, "oauth_invalid_grant", status.FailureCode) + assert.Equal(t, "invalid_rapt", status.ProviderErrorSubtype) + assert.Equal(t, TimeFromMillis(1699997000000), status.LastErrorAt) } func TestRefreshStatusFromProto_Nil(t *testing.T) { @@ -104,6 +130,24 @@ func TestRefreshStatusFromProto_ZeroTimestamps(t *testing.T) { assert.True(t, status.ExpiresAt.IsZero()) assert.True(t, status.NextRefreshAt.IsZero()) assert.True(t, status.LastRefreshAt.IsZero()) + assert.True(t, status.LastErrorAt.IsZero()) + assert.Equal(t, v1.RefreshRecoveryActionUnspecified, status.RecoveryAction) +} + +func TestRefreshStatusFromProto_ParkedRefreshHasNoNextTime(t *testing.T) { + proto := &pb.ProviderCredentialRefreshStatus{ + ProviderName: "test", + CredentialKey: "KEY", + NextRefreshAtMs: math.MaxInt64, + RecoveryAction: pb.ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE, + } + + status := RefreshStatusFromProto(proto) + + require.NotNil(t, status) + assert.True(t, status.NextRefreshAt.IsZero()) + assert.Equal(t, v1.RefreshRecoveryActionReauthorize, status.RecoveryAction) + assert.False(t, TimeFromMillis(math.MaxInt64).IsZero()) } // --- RefreshConfig --- diff --git a/sdk/go/openshell/v1/oidc/credentials.go b/sdk/go/openshell/v1/oidc/credentials.go index b88fe7e3df..e0971442b2 100644 --- a/sdk/go/openshell/v1/oidc/credentials.go +++ b/sdk/go/openshell/v1/oidc/credentials.go @@ -28,6 +28,14 @@ import ( // // The client secret is never included in error messages (FR-014). func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, error) { + cfg, err := resolveClientCredentialsConfig(opts...) + if err != nil { + return nil, err + } + return exchangeClientCredentials(ctx, cfg, false) +} + +func resolveClientCredentialsConfig(opts ...LoginOption) (*loginConfig, error) { cfg := &loginConfig{} for _, opt := range opts { opt(cfg) @@ -50,14 +58,19 @@ func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, if err != nil { return nil, fmt.Errorf("failed to load gateway %q: %w", cfg.gateway, err) } - if gwCfg.OIDCIssuer == "" || gwCfg.OIDCClientID == "" { - return nil, fmt.Errorf( - "%w: gateway %q has no OIDC configuration (missing oidc_issuer or oidc_client_id in metadata.json)", - ErrOIDCConfig, cfg.gateway, - ) + if cfg.issuer == "" { + cfg.issuer = gwCfg.OIDCIssuer + } + if cfg.clientID == "" { + cfg.clientID = gwCfg.OIDCClientID + } + if !cfg.audienceSet { + cfg.audience = gwCfg.OIDCAudience + } + if !cfg.scopesSet && gwCfg.OIDCScopes != "" { + cfg.scopes = strings.Fields(gwCfg.OIDCScopes) + cfg.scopesSet = true } - cfg.issuer = gwCfg.OIDCIssuer - cfg.clientID = gwCfg.OIDCClientID } // Validate required configuration. @@ -67,12 +80,27 @@ func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, ErrOIDCConfig, ) } - if cfg.clientSecret == "" { + if cfg.clientSecret == "" && cfg.secretProvider == nil { return nil, fmt.Errorf( - "%w: client secret is required (use WithClientSecret)", + "%w: client secret is required (use WithClientSecret or WithClientSecretProvider)", ErrClientCredentials, ) } + return cfg, nil +} + +func exchangeClientCredentials(ctx context.Context, cfg *loginConfig, requirePositiveExpiry bool) (*oauth2.Token, error) { + secret := cfg.clientSecret + if cfg.secretProvider != nil { + value, err := cfg.secretProvider(ctx) + if err != nil { + return nil, fmt.Errorf("%w: client secret provider failed", ErrClientCredentials) + } + secret = value + } + if secret == "" { + return nil, fmt.Errorf("%w: client secret must not be empty", ErrClientCredentials) + } // Discover provider endpoints. provider, err := discover(ctx, cfg.issuer) @@ -84,11 +112,14 @@ func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, data := url.Values{ "grant_type": {"client_credentials"}, "client_id": {cfg.clientID}, - "client_secret": {cfg.clientSecret}, + "client_secret": {secret}, } if len(cfg.scopes) > 0 { data.Set("scope", strings.Join(cfg.scopes, " ")) } + if cfg.audience != "" { + data.Set("audience", cfg.audience) + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, provider.TokenEndpoint, strings.NewReader(data.Encode())) if err != nil { @@ -110,27 +141,25 @@ func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, defer func() { _ = resp.Body.Close() }() const maxResponseBytes = 1 << 20 - body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1)) if err != nil { return nil, fmt.Errorf("%w: failed to read token response", ErrClientCredentials) } + if len(body) > maxResponseBytes { + return nil, fmt.Errorf("%w: token response is too large", ErrClientCredentials) + } var tokResp tokenResponse if err := json.Unmarshal(body, &tokResp); err != nil { return nil, fmt.Errorf("%w: invalid token response JSON", ErrClientCredentials) } + var fields map[string]json.RawMessage + if err := json.Unmarshal(body, &fields); err != nil { + return nil, fmt.Errorf("%w: invalid token response JSON", ErrClientCredentials) + } if resp.StatusCode != http.StatusOK || tokResp.Error != "" { - // FR-014: Never include the client secret in error messages. - // Only include the provider's error code and description. - msg := "client credentials exchange failed" - if tokResp.Error != "" { - msg = fmt.Sprintf("provider error: %s", tokResp.Error) - if tokResp.ErrorDesc != "" { - msg += ": " + tokResp.ErrorDesc - } - } - return nil, fmt.Errorf("%w: %s", ErrClientCredentials, msg) + return nil, fmt.Errorf("%w: provider rejected the exchange (HTTP %d)", ErrClientCredentials, resp.StatusCode) } if tokResp.AccessToken == "" { @@ -142,9 +171,17 @@ func ClientCredentials(ctx context.Context, opts ...LoginOption) (*oauth2.Token, RefreshToken: tokResp.RefreshToken, TokenType: tokResp.TokenType, } - if tokResp.ExpiresIn > 0 { - tok.Expiry = time.Now().Add(time.Duration(tokResp.ExpiresIn) * time.Second) + _, expiresInPresent := fields["expires_in"] + if expiresInPresent && tokResp.ExpiresIn <= 0 { + return nil, fmt.Errorf("%w: token response requires a positive expires_in", ErrClientCredentials) + } + if !expiresInPresent { + if requirePositiveExpiry { + return nil, fmt.Errorf("%w: token response requires a positive expires_in", ErrClientCredentials) + } + return tok, nil } + tok.Expiry = time.Now().Add(time.Duration(tokResp.ExpiresIn) * time.Second) return tok, nil } diff --git a/sdk/go/openshell/v1/oidc/credentials_auth.go b/sdk/go/openshell/v1/oidc/credentials_auth.go new file mode 100644 index 0000000000..d4a511d900 --- /dev/null +++ b/sdk/go/openshell/v1/oidc/credentials_auth.go @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package oidc + +import ( + "context" + "sync" + "time" + + "golang.org/x/oauth2" + "golang.org/x/sync/singleflight" + + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" +) + +const clientCredentialsLeeway = 30 * time.Second + +type clientCredentialsAuth struct { + cfg *loginConfig + mu sync.Mutex + token *oauth2.Token + group singleflight.Group +} + +// NewClientCredentialsAuth returns a renewable, memory-only client-credentials +// AuthProvider suitable for v1.Config.Auth or gateway.WithAuth. Acquisition is +// lazy, concurrent RPCs share one exchange, and expired tokens are never used +// when renewal fails. +func NewClientCredentialsAuth(opts ...LoginOption) (types.AuthProvider, error) { + cfg, err := resolveClientCredentialsConfig(opts...) + if err != nil { + return nil, err + } + return &clientCredentialsAuth{cfg: cfg}, nil +} + +func (a *clientCredentialsAuth) GetRequestMetadata(ctx context.Context, _ ...string) (map[string]string, error) { + a.mu.Lock() + if a.token != nil && time.Now().Add(clientCredentialsLeeway).Before(a.token.Expiry) { + accessToken := a.token.AccessToken + a.mu.Unlock() + return map[string]string{"authorization": "Bearer " + accessToken}, nil + } + a.mu.Unlock() + + result := a.group.DoChan("exchange", func() (any, error) { + exchangeCtx, cancel := context.WithTimeout(context.Background(), a.cfg.timeout) + defer cancel() + token, err := exchangeClientCredentials(exchangeCtx, a.cfg, true) + if err != nil { + return nil, err + } + a.mu.Lock() + a.token = token + a.mu.Unlock() + return token.AccessToken, nil + }) + select { + case <-ctx.Done(): + return nil, ctx.Err() + case exchange := <-result: + if exchange.Err != nil { + return nil, exchange.Err + } + return map[string]string{"authorization": "Bearer " + exchange.Val.(string)}, nil + } +} + +func (*clientCredentialsAuth) RequireTransportSecurity() bool { return true } + +func (*clientCredentialsAuth) String() string { return "oidc.ClientCredentialsAuth" } + +func (*clientCredentialsAuth) GoString() string { return "oidc.ClientCredentialsAuth{}" } diff --git a/sdk/go/openshell/v1/oidc/credentials_test.go b/sdk/go/openshell/v1/oidc/credentials_test.go index f87c6b31fb..51266202cb 100644 --- a/sdk/go/openshell/v1/oidc/credentials_test.go +++ b/sdk/go/openshell/v1/oidc/credentials_test.go @@ -7,8 +7,14 @@ import ( "context" "encoding/json" "errors" + "fmt" "net/http" "net/http/httptest" + "net/url" + "os" + "path/filepath" + "sync" + "sync/atomic" "testing" "time" @@ -18,6 +24,370 @@ import ( "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway" ) +type clientCredentialsFixture struct { + Request struct { + GrantType string `json:"grant_type"` + ClientID string `json:"client_id"` + ClientSecret string `json:"client_secret"` + Scopes []string `json:"scopes"` + Scope string `json:"scope"` + Audience string `json:"audience"` + } `json:"request"` + Expiry struct { + LeewaySeconds int `json:"leeway_seconds"` + ValidExpiresIn int64 `json:"valid_expires_in"` + InvalidExpiresIn []json.RawMessage `json:"invalid_expires_in"` + } `json:"expiry"` + Discovery struct { + ConfiguredIssuer string `json:"configured_issuer"` + MatchingIssuer string `json:"matching_issuer"` + MismatchedIssuer string `json:"mismatched_issuer"` + RedirectStatuses []int `json:"redirect_statuses"` + } `json:"discovery"` + Limits struct { + MaxResponseBytes int `json:"max_response_bytes"` + } `json:"limits"` + URLs struct { + Allowed []string `json:"allowed"` + Rejected []string `json:"rejected"` + } `json:"urls"` +} + +func loadClientCredentialsFixture(t *testing.T) clientCredentialsFixture { + t.Helper() + data, err := os.ReadFile(filepath.Join("..", "..", "..", "..", "conformance", "oauth-client-credentials.json")) + require.NoError(t, err) + var fixture clientCredentialsFixture + require.NoError(t, json.Unmarshal(data, &fixture)) + return fixture +} + +func TestClientCredentialsConformanceFixture(t *testing.T) { + fixture := loadClientCredentialsFixture(t) + assert.Equal(t, int(clientCredentialsLeeway/time.Second), fixture.Expiry.LeewaySeconds) + for _, raw := range fixture.URLs.Allowed { + assert.NoError(t, validateSecureURL("issuer", raw), raw) + } + for _, raw := range fixture.URLs.Rejected { + assert.Error(t, validateSecureURL("issuer", raw), raw) + } +} + +func TestClientCredentialsRejectsInvalidExpiryConformance(t *testing.T) { + fixture := loadClientCredentialsFixture(t) + for _, raw := range fixture.Expiry.InvalidExpiresIn { + raw := raw + t.Run(string(raw), func(t *testing.T) { + resetDiscoveryCache() + var server *httptest.Server + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/openid-configuration" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": server.URL, + "authorization_endpoint": server.URL + "/authorize", + "token_endpoint": server.URL + "/token", + }) + return + } + _, _ = fmt.Fprintf(w, `{"access_token":"sensitive-access-token","expires_in":%s}`, raw) + })) + t.Cleanup(server.Close) + + _, err := ClientCredentials( + context.Background(), + WithIssuer(server.URL), + WithClientID("client"), + WithClientSecret("secret"), + ) + require.Error(t, err) + assert.NotContains(t, err.Error(), "sensitive-access-token") + }) + } +} + +func TestClientCredentialsMissingExpiryCompatibility(t *testing.T) { + resetDiscoveryCache() + var server *httptest.Server + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/openid-configuration" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": server.URL, + "authorization_endpoint": server.URL + "/authorize", + "token_endpoint": server.URL + "/token", + }) + return + } + _, _ = w.Write([]byte(`{"access_token":"token","token_type":"Bearer"}`)) + })) + t.Cleanup(server.Close) + + opts := []LoginOption{ + WithIssuer(server.URL), + WithClientID("client"), + WithClientSecret("secret"), + } + token, err := ClientCredentials(context.Background(), opts...) + require.NoError(t, err) + assert.True(t, token.Expiry.IsZero()) + + auth, err := NewClientCredentialsAuth(opts...) + require.NoError(t, err) + metadata, err := auth.GetRequestMetadata(context.Background()) + require.Error(t, err) + assert.Nil(t, metadata) + assert.Contains(t, err.Error(), "positive expires_in") +} + +func TestClientCredentialsRefusesRedirectsConformance(t *testing.T) { + fixture := loadClientCredentialsFixture(t) + for _, status := range fixture.Discovery.RedirectStatuses { + status := status + for _, endpoint := range []string{"discovery", "token"} { + endpoint := endpoint + t.Run(fmt.Sprintf("%s_%d", endpoint, status), func(t *testing.T) { + resetDiscoveryCache() + var server *httptest.Server + var redirected atomic.Bool + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/.well-known/openid-configuration": + if endpoint == "discovery" { + w.Header().Set("Location", server.URL+"/redirected") + w.WriteHeader(status) + return + } + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": server.URL, + "authorization_endpoint": server.URL + "/authorize", + "token_endpoint": server.URL + "/token", + }) + case "/token": + w.Header().Set("Location", server.URL+"/redirected") + w.WriteHeader(status) + case "/redirected": + redirected.Store(true) + } + })) + t.Cleanup(server.Close) + + _, err := ClientCredentials( + context.Background(), + WithIssuer(server.URL), + WithClientID("client"), + WithClientSecret("secret"), + ) + require.Error(t, err) + assert.False(t, redirected.Load()) + }) + } + } +} + +func TestClientCredentialsRejectsMismatchedIssuerConformance(t *testing.T) { + resetDiscoveryCache() + fixture := loadClientCredentialsFixture(t) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": fixture.Discovery.MismatchedIssuer, + "authorization_endpoint": fixture.Discovery.MismatchedIssuer + "/authorize", + "token_endpoint": fixture.Discovery.MismatchedIssuer + "/token", + }) + })) + t.Cleanup(server.Close) + + _, err := ClientCredentials( + context.Background(), + WithIssuer(server.URL), + WithClientID("client"), + WithClientSecret("secret"), + ) + require.Error(t, err) + assert.Contains(t, err.Error(), "issuer") +} + +func TestClientCredentialsRejectsOversizedResponseConformance(t *testing.T) { + resetDiscoveryCache() + fixture := loadClientCredentialsFixture(t) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write(make([]byte, fixture.Limits.MaxResponseBytes+1)) + })) + t.Cleanup(server.Close) + + _, err := ClientCredentials( + context.Background(), + WithIssuer(server.URL), + WithClientID("client"), + WithClientSecret("secret"), + ) + require.Error(t, err) + assert.Contains(t, err.Error(), "too large") +} + +func TestClientCredentialsAuthSingleFlightRenewalAndFields(t *testing.T) { + resetDiscoveryCache() + fixture := loadClientCredentialsFixture(t) + var server *httptest.Server + var calls atomic.Int32 + var formsMu sync.Mutex + var forms []url.Values + release := make(chan struct{}) + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/openid-configuration" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": server.URL, + "authorization_endpoint": server.URL + "/authorize", + "token_endpoint": server.URL + "/token", + }) + return + } + if calls.Add(1) == 1 { + <-release + } + require.NoError(t, r.ParseForm()) + formsMu.Lock() + forms = append(forms, r.Form) + formsMu.Unlock() + _, _ = w.Write([]byte(tokenResponseJSON("token", "", 3600))) + })) + t.Cleanup(server.Close) + + auth, err := NewClientCredentialsAuth( + WithIssuer(server.URL), + WithClientID(fixture.Request.ClientID), + WithClientSecret(fixture.Request.ClientSecret), + WithScopes(fixture.Request.Scopes...), + WithAudience(fixture.Request.Audience), + ) + require.NoError(t, err) + assert.NotContains(t, fmt.Sprintf("%#v", auth), "secret") + + results := make(chan error, 12) + for range 12 { + go func() { + metadata, callErr := auth.GetRequestMetadata(context.Background()) + if callErr == nil && metadata["authorization"] != "Bearer token" { + callErr = errors.New("unexpected authorization metadata") + } + results <- callErr + }() + } + require.Eventually(t, func() bool { return calls.Load() == 1 }, time.Second, time.Millisecond) + close(release) + for range 12 { + require.NoError(t, <-results) + } + assert.Equal(t, int32(1), calls.Load()) + require.Len(t, forms, 1) + assert.Equal(t, fixture.Request.GrantType, forms[0].Get("grant_type")) + assert.Equal(t, fixture.Request.ClientID, forms[0].Get("client_id")) + assert.Equal(t, fixture.Request.ClientSecret, forms[0].Get("client_secret")) + assert.Equal(t, fixture.Request.Scope, forms[0].Get("scope")) + assert.Equal(t, fixture.Request.Audience, forms[0].Get("audience")) + + concrete := auth.(*clientCredentialsAuth) + concrete.mu.Lock() + concrete.token.Expiry = time.Now() + concrete.mu.Unlock() + _, err = auth.GetRequestMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, int32(2), calls.Load()) +} + +func TestClientCredentialsAuthCancellationDoesNotPoisonSharedExchange(t *testing.T) { + resetDiscoveryCache() + var server *httptest.Server + started := make(chan struct{}) + release := make(chan struct{}) + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/openid-configuration" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": server.URL, + "authorization_endpoint": server.URL + "/authorize", + "token_endpoint": server.URL + "/token", + }) + return + } + close(started) + <-release + _, _ = w.Write([]byte(tokenResponseJSON("token", "", 3600))) + })) + t.Cleanup(server.Close) + auth, err := NewClientCredentialsAuth( + WithIssuer(server.URL), WithClientID("client"), WithClientSecret("secret"), + ) + require.NoError(t, err) + + canceled, cancel := context.WithCancel(context.Background()) + first := make(chan error, 1) + go func() { + _, callErr := auth.GetRequestMetadata(canceled) + first <- callErr + }() + <-started + second := make(chan error, 1) + go func() { + _, callErr := auth.GetRequestMetadata(context.Background()) + second <- callErr + }() + cancel() + assert.ErrorIs(t, <-first, context.Canceled) + close(release) + require.NoError(t, <-second) +} + +func TestClientCredentialsAuthRedactsSecretProviderError(t *testing.T) { + auth, err := NewClientCredentialsAuth( + WithIssuer("http://localhost:8080"), + WithClientID("client"), + WithClientSecretProvider(func(context.Context) (string, error) { + return "", errors.New("supplier-sensitive-detail") + }), + ) + require.NoError(t, err) + _, err = auth.GetRequestMetadata(context.Background()) + require.Error(t, err) + assert.NotContains(t, err.Error(), "supplier-sensitive-detail") +} + +func TestClientCredentialsAuthFailsClosedOnRenewalError(t *testing.T) { + resetDiscoveryCache() + var server *httptest.Server + var fail atomic.Bool + server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/openid-configuration" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "issuer": server.URL, + "authorization_endpoint": server.URL + "/authorize", + "token_endpoint": server.URL + "/token", + }) + return + } + if fail.Load() { + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte(`{"error":"provider-sensitive-detail"}`)) + return + } + _, _ = w.Write([]byte(tokenResponseJSON("stale", "", 3600))) + })) + t.Cleanup(server.Close) + auth, err := NewClientCredentialsAuth( + WithIssuer(server.URL), WithClientID("client"), WithClientSecret("secret"), + ) + require.NoError(t, err) + _, err = auth.GetRequestMetadata(context.Background()) + require.NoError(t, err) + concrete := auth.(*clientCredentialsAuth) + concrete.mu.Lock() + concrete.token.Expiry = time.Now() + concrete.mu.Unlock() + fail.Store(true) + metadata, err := auth.GetRequestMetadata(context.Background()) + require.Error(t, err) + assert.Nil(t, metadata) + assert.NotContains(t, err.Error(), "stale") + assert.NotContains(t, err.Error(), "provider-sensitive-detail") +} + // --- T023: Client credentials tests --- // setupCredentialsMockProvider creates a mock OIDC provider for client diff --git a/sdk/go/openshell/v1/oidc/discovery.go b/sdk/go/openshell/v1/oidc/discovery.go index d872027e88..1c1dcef2a2 100644 --- a/sdk/go/openshell/v1/oidc/discovery.go +++ b/sdk/go/openshell/v1/oidc/discovery.go @@ -16,7 +16,12 @@ import ( "time" ) -var oidcHTTPClient = &http.Client{Timeout: 30 * time.Second} +var oidcHTTPClient = &http.Client{ + Timeout: 30 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, +} // providerConfig holds parsed fields from an OIDC discovery document // (.well-known/openid-configuration). @@ -115,17 +120,20 @@ func fetchDiscovery(ctx context.Context, issuer string) (*providerConfig, error) } const maxResponseBytes = 1 << 20 - body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1)) if err != nil { return nil, fmt.Errorf("%w: failed to read discovery response: %v", ErrDiscovery, err) } + if len(body) > maxResponseBytes { + return nil, fmt.Errorf("%w: discovery response is too large", ErrDiscovery) + } var cfg providerConfig if err := json.Unmarshal(body, &cfg); err != nil { return nil, fmt.Errorf("%w: invalid discovery JSON: %v", ErrDiscovery, err) } if normalizeIssuer(cfg.Issuer) != normalizeIssuer(issuer) { - return nil, fmt.Errorf("%w: discovery issuer %q does not match configured issuer %q", ErrDiscovery, cfg.Issuer, issuer) + return nil, fmt.Errorf("%w: discovery issuer does not match configured issuer", ErrDiscovery) } if cfg.TokenEndpoint == "" { diff --git a/sdk/go/openshell/v1/oidc/doc.go b/sdk/go/openshell/v1/oidc/doc.go index 2575a09127..1e3c0ac5a4 100644 --- a/sdk/go/openshell/v1/oidc/doc.go +++ b/sdk/go/openshell/v1/oidc/doc.go @@ -48,7 +48,7 @@ // // For non-interactive service accounts: // -// token, err := oidc.ClientCredentials(ctx, +// auth, err := oidc.NewClientCredentialsAuth( // oidc.WithIssuer("https://auth.example.com"), // oidc.WithClientID("my-service"), // oidc.WithClientSecret("secret"), diff --git a/sdk/go/openshell/v1/oidc/options.go b/sdk/go/openshell/v1/oidc/options.go index 00dcd1e741..d4d856ba4b 100644 --- a/sdk/go/openshell/v1/oidc/options.go +++ b/sdk/go/openshell/v1/oidc/options.go @@ -4,6 +4,7 @@ package oidc import ( + "context" "io" "time" @@ -22,17 +23,20 @@ const defaultTimeout = 2 * time.Minute // attempt. It is built by applying [LoginOption] functions to a // zero-value struct and then filling in defaults. type loginConfig struct { - issuer string - clientID string - clientSecret string - scopes []string - scopesSet bool - callbackPort int - timeout time.Duration - keyboardFlow bool - inMemory bool - displayFunc func(verificationURL, userCode string) - gateway string + issuer string + clientID string + clientSecret string + secretProvider func(context.Context) (string, error) + audience string + audienceSet bool + scopes []string + scopesSet bool + callbackPort int + timeout time.Duration + keyboardFlow bool + inMemory bool + displayFunc func(verificationURL, userCode string) + gateway string // Internal fields for testing. Not exposed via public API. tokenDir string // override token directory @@ -75,13 +79,29 @@ func WithClientID(id string) LoginOption { } // WithClientSecret sets the client secret for the client credentials -// grant. Required for [ClientCredentials]. +// grant. Required for [ClientCredentials] and [NewClientCredentialsAuth]. func WithClientSecret(secret string) LoginOption { return func(c *loginConfig) { c.clientSecret = secret } } +// WithClientSecretProvider resolves the client secret for each exchange. +// Provider errors and returned secrets are never included in SDK errors. +func WithClientSecretProvider(provider func(context.Context) (string, error)) LoginOption { + return func(c *loginConfig) { + c.secretProvider = provider + } +} + +// WithAudience sets the optional OAuth2 resource-server audience. +func WithAudience(audience string) LoginOption { + return func(c *loginConfig) { + c.audience = audience + c.audienceSet = true + } +} + // WithScopes overrides the default scopes (openid, profile, email). // The provided scopes replace the defaults entirely. func WithScopes(scopes ...string) LoginOption { @@ -134,10 +154,9 @@ func WithDisplayFunc(fn func(verificationURL, userCode string)) LoginOption { } } -// WithGateway sets the gateway name for [DeviceLogin] and -// [ClientCredentials]. When set, OIDC config is read from the -// gateway's metadata.json and tokens are persisted to the gateway -// directory. +// WithGateway sets the gateway name for [DeviceLogin], [ClientCredentials], +// and [NewClientCredentialsAuth]. OIDC configuration is read from the +// gateway's metadata.json. Client-credentials tokens are never persisted. func WithGateway(name string) LoginOption { return func(c *loginConfig) { c.gateway = name diff --git a/sdk/go/openshell/v1/types/refresh.go b/sdk/go/openshell/v1/types/refresh.go index b67ba35849..6ca49310e4 100644 --- a/sdk/go/openshell/v1/types/refresh.go +++ b/sdk/go/openshell/v1/types/refresh.go @@ -18,6 +18,40 @@ const ( RefreshStrategyAWSStsAssumeRole RefreshStrategy = "AWSStsAssumeRole" ) +// RefreshRecoveryAction describes the action required after a refresh failure. +type RefreshRecoveryAction int + +const ( + // RefreshRecoveryActionUnspecified means no recovery action is required. + RefreshRecoveryActionUnspecified RefreshRecoveryAction = iota + // RefreshRecoveryActionRetry means OpenShell will retry automatically. + RefreshRecoveryActionRetry + // RefreshRecoveryActionReauthorize means the user must replace the OAuth grant. + RefreshRecoveryActionReauthorize + // RefreshRecoveryActionFixConfiguration means an operator must repair configuration. + RefreshRecoveryActionFixConfiguration + // RefreshRecoveryActionInvestigate means the failure is not recognized. + RefreshRecoveryActionInvestigate +) + +// String returns the provider-neutral recovery action name. +func (a RefreshRecoveryAction) String() string { + switch a { + case RefreshRecoveryActionUnspecified: + return "unspecified" + case RefreshRecoveryActionRetry: + return "retry" + case RefreshRecoveryActionReauthorize: + return "reauthorize" + case RefreshRecoveryActionFixConfiguration: + return "fix_configuration" + case RefreshRecoveryActionInvestigate: + return "investigate" + default: + return "unknown" + } +} + // RefreshStatus reports the current state of credential refresh for a specific // provider credential. type RefreshStatus struct { @@ -27,9 +61,15 @@ type RefreshStatus struct { Strategy RefreshStrategy Status string ExpiresAt time.Time - NextRefreshAt time.Time - LastRefreshAt time.Time - LastError string + // NextRefreshAt is zero when no automatic refresh is scheduled. Use + // RecoveryAction to distinguish a parked refresh from an unset timestamp. + NextRefreshAt time.Time + LastRefreshAt time.Time + LastError string + RecoveryAction RefreshRecoveryAction + FailureCode string + ProviderErrorSubtype string + LastErrorAt time.Time } // RefreshConfig holds configuration parameters for gateway-owned credential diff --git a/sdk/go/proto/openshellv1/openshell.pb.go b/sdk/go/proto/openshellv1/openshell.pb.go index 778bf4f985..6b3b740a0b 100644 --- a/sdk/go/proto/openshellv1/openshell.pb.go +++ b/sdk/go/proto/openshellv1/openshell.pb.go @@ -439,6 +439,65 @@ func (WorkspaceRole) EnumDescriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{6} } +// Stable recovery action for the most recent provider credential refresh +// failure. Kept after the pre-existing enums so adding it does not renumber +// their generated descriptors. Clients should use this field instead of +// parsing last_error. +type ProviderCredentialRefreshRecoveryAction int32 + +const ( + ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_UNSPECIFIED ProviderCredentialRefreshRecoveryAction = 0 + ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_RETRY ProviderCredentialRefreshRecoveryAction = 1 + ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE ProviderCredentialRefreshRecoveryAction = 2 + ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_FIX_CONFIGURATION ProviderCredentialRefreshRecoveryAction = 3 + ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE ProviderCredentialRefreshRecoveryAction = 4 +) + +// Enum value maps for ProviderCredentialRefreshRecoveryAction. +var ( + ProviderCredentialRefreshRecoveryAction_name = map[int32]string{ + 0: "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_UNSPECIFIED", + 1: "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_RETRY", + 2: "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE", + 3: "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_FIX_CONFIGURATION", + 4: "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE", + } + ProviderCredentialRefreshRecoveryAction_value = map[string]int32{ + "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_UNSPECIFIED": 0, + "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_RETRY": 1, + "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE": 2, + "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_FIX_CONFIGURATION": 3, + "PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE": 4, + } +) + +func (x ProviderCredentialRefreshRecoveryAction) Enum() *ProviderCredentialRefreshRecoveryAction { + p := new(ProviderCredentialRefreshRecoveryAction) + *p = x + return p +} + +func (x ProviderCredentialRefreshRecoveryAction) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ProviderCredentialRefreshRecoveryAction) Descriptor() protoreflect.EnumDescriptor { + return file_openshell_proto_enumTypes[7].Descriptor() +} + +func (ProviderCredentialRefreshRecoveryAction) Type() protoreflect.EnumType { + return &file_openshell_proto_enumTypes[7] +} + +func (x ProviderCredentialRefreshRecoveryAction) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ProviderCredentialRefreshRecoveryAction.Descriptor instead. +func (ProviderCredentialRefreshRecoveryAction) EnumDescriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{7} +} + // IssueSandboxToken request. Empty body; identity is established by the // authentication credentials carried in the request headers (a projected // Kubernetes ServiceAccount JWT in the K8s driver path). @@ -5861,18 +5920,32 @@ func (x *ProviderCredentialRefresh) GetAdditionalOutputs() []*ProviderCredential } type ProviderCredentialRefreshStatus struct { - state protoimpl.MessageState `protogen:"open.v1"` - ProviderName string `protobuf:"bytes,1,opt,name=provider_name,json=providerName,proto3" json:"provider_name,omitempty"` - ProviderId string `protobuf:"bytes,2,opt,name=provider_id,json=providerId,proto3" json:"provider_id,omitempty"` - CredentialKey string `protobuf:"bytes,3,opt,name=credential_key,json=credentialKey,proto3" json:"credential_key,omitempty"` - Strategy ProviderCredentialRefreshStrategy `protobuf:"varint,4,opt,name=strategy,proto3,enum=openshell.v1.ProviderCredentialRefreshStrategy" json:"strategy,omitempty"` - Status string `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` - ExpiresAtMs int64 `protobuf:"varint,6,opt,name=expires_at_ms,json=expiresAtMs,proto3" json:"expires_at_ms,omitempty"` - NextRefreshAtMs int64 `protobuf:"varint,7,opt,name=next_refresh_at_ms,json=nextRefreshAtMs,proto3" json:"next_refresh_at_ms,omitempty"` - LastRefreshAtMs int64 `protobuf:"varint,8,opt,name=last_refresh_at_ms,json=lastRefreshAtMs,proto3" json:"last_refresh_at_ms,omitempty"` - LastError string `protobuf:"bytes,9,opt,name=last_error,json=lastError,proto3" json:"last_error,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + ProviderName string `protobuf:"bytes,1,opt,name=provider_name,json=providerName,proto3" json:"provider_name,omitempty"` + ProviderId string `protobuf:"bytes,2,opt,name=provider_id,json=providerId,proto3" json:"provider_id,omitempty"` + CredentialKey string `protobuf:"bytes,3,opt,name=credential_key,json=credentialKey,proto3" json:"credential_key,omitempty"` + Strategy ProviderCredentialRefreshStrategy `protobuf:"varint,4,opt,name=strategy,proto3,enum=openshell.v1.ProviderCredentialRefreshStrategy" json:"strategy,omitempty"` + Status string `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` + ExpiresAtMs int64 `protobuf:"varint,6,opt,name=expires_at_ms,json=expiresAtMs,proto3" json:"expires_at_ms,omitempty"` + // Next automatic refresh time in Unix epoch milliseconds. A value of + // 9223372036854775807 (int64 max) means no automatic retry is scheduled; + // consumers should render it as unset and use recovery_action to determine + // the required recovery workflow. + NextRefreshAtMs int64 `protobuf:"varint,7,opt,name=next_refresh_at_ms,json=nextRefreshAtMs,proto3" json:"next_refresh_at_ms,omitempty"` + LastRefreshAtMs int64 `protobuf:"varint,8,opt,name=last_refresh_at_ms,json=lastRefreshAtMs,proto3" json:"last_refresh_at_ms,omitempty"` + LastError string `protobuf:"bytes,9,opt,name=last_error,json=lastError,proto3" json:"last_error,omitempty"` + RecoveryAction ProviderCredentialRefreshRecoveryAction `protobuf:"varint,10,opt,name=recovery_action,json=recoveryAction,proto3,enum=openshell.v1.ProviderCredentialRefreshRecoveryAction" json:"recovery_action,omitempty"` + // Stable gateway-owned failure identifier, for example + // "oauth_invalid_grant". This is not provider-controlled prose and + // incorporates any recognized top-level OAuth error classification. + FailureCode string `protobuf:"bytes,11,opt,name=failure_code,json=failureCode,proto3" json:"failure_code,omitempty"` + // A bounded, recognized provider subtype that refines failure_code; clients + // do not need a separate provider_error field. Unknown provider-controlled + // values are not persisted or returned. + ProviderErrorSubtype string `protobuf:"bytes,12,opt,name=provider_error_subtype,json=providerErrorSubtype,proto3" json:"provider_error_subtype,omitempty"` + LastErrorAtMs int64 `protobuf:"varint,13,opt,name=last_error_at_ms,json=lastErrorAtMs,proto3" json:"last_error_at_ms,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *ProviderCredentialRefreshStatus) Reset() { @@ -5968,6 +6041,34 @@ func (x *ProviderCredentialRefreshStatus) GetLastError() string { return "" } +func (x *ProviderCredentialRefreshStatus) GetRecoveryAction() ProviderCredentialRefreshRecoveryAction { + if x != nil { + return x.RecoveryAction + } + return ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_UNSPECIFIED +} + +func (x *ProviderCredentialRefreshStatus) GetFailureCode() string { + if x != nil { + return x.FailureCode + } + return "" +} + +func (x *ProviderCredentialRefreshStatus) GetProviderErrorSubtype() string { + if x != nil { + return x.ProviderErrorSubtype + } + return "" +} + +func (x *ProviderCredentialRefreshStatus) GetLastErrorAtMs() int64 { + if x != nil { + return x.LastErrorAtMs + } + return 0 +} + // Provider profile local discovery declaration. type ProviderProfileDiscovery struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -6025,8 +6126,9 @@ type StoredProviderCredentialRefreshState struct { // Material names classified as secret. Newly configured values live in the // active credential driver and are absent from material. Legacy inline values // are not automatically migrated before OpenShell 0.1.0. - SecretMaterialKeys []string `protobuf:"bytes,7,rep,name=secret_material_keys,json=secretMaterialKeys,proto3" json:"secret_material_keys,omitempty"` - ExpiresAtMs int64 `protobuf:"varint,8,opt,name=expires_at_ms,json=expiresAtMs,proto3" json:"expires_at_ms,omitempty"` + SecretMaterialKeys []string `protobuf:"bytes,7,rep,name=secret_material_keys,json=secretMaterialKeys,proto3" json:"secret_material_keys,omitempty"` + ExpiresAtMs int64 `protobuf:"varint,8,opt,name=expires_at_ms,json=expiresAtMs,proto3" json:"expires_at_ms,omitempty"` + // int64 max parks the refresh until an explicit rotation or reconfiguration. NextRefreshAtMs int64 `protobuf:"varint,9,opt,name=next_refresh_at_ms,json=nextRefreshAtMs,proto3" json:"next_refresh_at_ms,omitempty"` LastRefreshAtMs int64 `protobuf:"varint,10,opt,name=last_refresh_at_ms,json=lastRefreshAtMs,proto3" json:"last_refresh_at_ms,omitempty"` Status string `protobuf:"bytes,11,opt,name=status,proto3" json:"status,omitempty"` @@ -6055,8 +6157,14 @@ type StoredProviderCredentialRefreshState struct { // Cleanup is retried by the refresh worker so a gateway crash or temporary // credential-backend outage does not lose the deletion reference. PendingSecretDeletions []*StoredRefreshMaterialDeletion `protobuf:"bytes,20,rep,name=pending_secret_deletions,json=pendingSecretDeletions,proto3" json:"pending_secret_deletions,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Structured recovery details for the most recent refresh failure. These + // fields contain only gateway-owned codes and recognized bounded values. + RecoveryAction ProviderCredentialRefreshRecoveryAction `protobuf:"varint,21,opt,name=recovery_action,json=recoveryAction,proto3,enum=openshell.v1.ProviderCredentialRefreshRecoveryAction" json:"recovery_action,omitempty"` + FailureCode string `protobuf:"bytes,22,opt,name=failure_code,json=failureCode,proto3" json:"failure_code,omitempty"` + ProviderErrorSubtype string `protobuf:"bytes,23,opt,name=provider_error_subtype,json=providerErrorSubtype,proto3" json:"provider_error_subtype,omitempty"` + LastErrorAtMs int64 `protobuf:"varint,24,opt,name=last_error_at_ms,json=lastErrorAtMs,proto3" json:"last_error_at_ms,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *StoredProviderCredentialRefreshState) Reset() { @@ -6229,6 +6337,34 @@ func (x *StoredProviderCredentialRefreshState) GetPendingSecretDeletions() []*St return nil } +func (x *StoredProviderCredentialRefreshState) GetRecoveryAction() ProviderCredentialRefreshRecoveryAction { + if x != nil { + return x.RecoveryAction + } + return ProviderCredentialRefreshRecoveryAction_PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_UNSPECIFIED +} + +func (x *StoredProviderCredentialRefreshState) GetFailureCode() string { + if x != nil { + return x.FailureCode + } + return "" +} + +func (x *StoredProviderCredentialRefreshState) GetProviderErrorSubtype() string { + if x != nil { + return x.ProviderErrorSubtype + } + return "" +} + +func (x *StoredProviderCredentialRefreshState) GetLastErrorAtMs() int64 { + if x != nil { + return x.LastErrorAtMs + } + return 0 +} + type StoredRefreshMaterialDeletion struct { state protoimpl.MessageState `protogen:"open.v1"` // Original material name used to derive the credential driver's storage key. @@ -14233,7 +14369,7 @@ const file_openshell_proto_rawDesc = "" + "\x16refresh_before_seconds\x18\x04 \x01(\x03R\x14refreshBeforeSeconds\x120\n" + "\x14max_lifetime_seconds\x18\x05 \x01(\x03R\x12maxLifetimeSeconds\x12K\n" + "\bmaterial\x18\x06 \x03(\v2/.openshell.v1.ProviderCredentialRefreshMaterialR\bmaterial\x12\\\n" + - "\x12additional_outputs\x18\a \x03(\v2-.openshell.v1.ProviderCredentialRefreshOutputR\x11additionalOutputs\"\x90\x03\n" + + "\x12additional_outputs\x18\a \x03(\v2-.openshell.v1.ProviderCredentialRefreshOutputR\x11additionalOutputs\"\xf2\x04\n" + "\x1fProviderCredentialRefreshStatus\x12#\n" + "\rprovider_name\x18\x01 \x01(\tR\fproviderName\x12\x1f\n" + "\vprovider_id\x18\x02 \x01(\tR\n" + @@ -14245,9 +14381,14 @@ const file_openshell_proto_rawDesc = "" + "\x12next_refresh_at_ms\x18\a \x01(\x03R\x0fnextRefreshAtMs\x12+\n" + "\x12last_refresh_at_ms\x18\b \x01(\x03R\x0flastRefreshAtMs\x12\x1d\n" + "\n" + - "last_error\x18\t \x01(\tR\tlastError\"<\n" + + "last_error\x18\t \x01(\tR\tlastError\x12^\n" + + "\x0frecovery_action\x18\n" + + " \x01(\x0e25.openshell.v1.ProviderCredentialRefreshRecoveryActionR\x0erecoveryAction\x12!\n" + + "\ffailure_code\x18\v \x01(\tR\vfailureCode\x124\n" + + "\x16provider_error_subtype\x18\f \x01(\tR\x14providerErrorSubtype\x12'\n" + + "\x10last_error_at_ms\x18\r \x01(\x03R\rlastErrorAtMs\"<\n" + "\x18ProviderProfileDiscovery\x12 \n" + - "\vcredentials\x18\x01 \x03(\tR\vcredentials\"\xa7\v\n" + + "\vcredentials\x18\x01 \x03(\tR\vcredentials\"\x89\r\n" + "$StoredProviderCredentialRefreshState\x12>\n" + "\bmetadata\x18\x01 \x01(\v2\".openshell.datamodel.v1.ObjectMetaR\bmetadata\x12\x1f\n" + "\vprovider_id\x18\x02 \x01(\tR\n" + @@ -14271,7 +14412,11 @@ const file_openshell_proto_rawDesc = "" + "\x16additional_output_keys\x18\x11 \x03(\v2L.openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntryR\x14additionalOutputKeys\x12/\n" + "\x13authorization_epoch\x18\x12 \x01(\tR\x12authorizationEpoch\x12\x85\x01\n" + "\x17secret_material_handles\x18\x13 \x03(\v2M.openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntryR\x15secretMaterialHandles\x12e\n" + - "\x18pending_secret_deletions\x18\x14 \x03(\v2+.openshell.v1.StoredRefreshMaterialDeletionR\x16pendingSecretDeletions\x1a;\n" + + "\x18pending_secret_deletions\x18\x14 \x03(\v2+.openshell.v1.StoredRefreshMaterialDeletionR\x16pendingSecretDeletions\x12^\n" + + "\x0frecovery_action\x18\x15 \x01(\x0e25.openshell.v1.ProviderCredentialRefreshRecoveryActionR\x0erecoveryAction\x12!\n" + + "\ffailure_code\x18\x16 \x01(\tR\vfailureCode\x124\n" + + "\x16provider_error_subtype\x18\x17 \x01(\tR\x14providerErrorSubtype\x12'\n" + + "\x10last_error_at_ms\x18\x18 \x01(\x03R\rlastErrorAtMs\x1a;\n" + "\rMaterialEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1aG\n" + @@ -14930,7 +15075,13 @@ const file_openshell_proto_rawDesc = "" + "\rWorkspaceRole\x12\x1e\n" + "\x1aWORKSPACE_ROLE_UNSPECIFIED\x10\x00\x12\x17\n" + "\x13WORKSPACE_ROLE_USER\x10\x01\x12\x18\n" + - "\x14WORKSPACE_ROLE_ADMIN\x10\x022\xacF\n" + + "\x14WORKSPACE_ROLE_ADMIN\x10\x02*\xda\x02\n" + + "'ProviderCredentialRefreshRecoveryAction\x12;\n" + + "7PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_UNSPECIFIED\x10\x00\x125\n" + + "1PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_RETRY\x10\x01\x12;\n" + + "7PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE\x10\x02\x12A\n" + + "=PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_FIX_CONFIGURATION\x10\x03\x12;\n" + + "7PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE\x10\x042\xacF\n" + "\tOpenShell\x12Z\n" + "\x06Health\x12\x1b.openshell.v1.HealthRequest\x1a\x1c.openshell.v1.HealthResponse\"\x15\x82\xb5\x18\x11\n" + "\x0funauthenticated\x12i\n" + @@ -15084,7 +15235,7 @@ func file_openshell_proto_rawDescGZIP() []byte { return file_openshell_proto_rawDescData } -var file_openshell_proto_enumTypes = make([]protoimpl.EnumInfo, 7) +var file_openshell_proto_enumTypes = make([]protoimpl.EnumInfo, 8) var file_openshell_proto_msgTypes = make([]protoimpl.MessageInfo, 217) var file_openshell_proto_goTypes = []any{ (SandboxPhase)(0), // 0: openshell.v1.SandboxPhase @@ -15094,546 +15245,549 @@ var file_openshell_proto_goTypes = []any{ (PolicyStatus)(0), // 4: openshell.v1.PolicyStatus (ServiceStatus)(0), // 5: openshell.v1.ServiceStatus (WorkspaceRole)(0), // 6: openshell.v1.WorkspaceRole - (*IssueSandboxTokenRequest)(nil), // 7: openshell.v1.IssueSandboxTokenRequest - (*IssueSandboxTokenResponse)(nil), // 8: openshell.v1.IssueSandboxTokenResponse - (*RefreshSandboxTokenRequest)(nil), // 9: openshell.v1.RefreshSandboxTokenRequest - (*RefreshSandboxTokenResponse)(nil), // 10: openshell.v1.RefreshSandboxTokenResponse - (*HealthRequest)(nil), // 11: openshell.v1.HealthRequest - (*HealthResponse)(nil), // 12: openshell.v1.HealthResponse - (*GetCurrentUserRequest)(nil), // 13: openshell.v1.GetCurrentUserRequest - (*GetCurrentUserResponse)(nil), // 14: openshell.v1.GetCurrentUserResponse - (*GetGatewayInfoRequest)(nil), // 15: openshell.v1.GetGatewayInfoRequest - (*GetGatewayInfoResponse)(nil), // 16: openshell.v1.GetGatewayInfoResponse - (*ComputeDriverInfo)(nil), // 17: openshell.v1.ComputeDriverInfo - (*ComputeDriverCapabilities)(nil), // 18: openshell.v1.ComputeDriverCapabilities - (*Sandbox)(nil), // 19: openshell.v1.Sandbox - (*SandboxSpec)(nil), // 20: openshell.v1.SandboxSpec - (*ResourceRequirements)(nil), // 21: openshell.v1.ResourceRequirements - (*GpuResourceRequirements)(nil), // 22: openshell.v1.GpuResourceRequirements - (*SandboxTemplate)(nil), // 23: openshell.v1.SandboxTemplate - (*SandboxStatus)(nil), // 24: openshell.v1.SandboxStatus - (*SandboxCondition)(nil), // 25: openshell.v1.SandboxCondition - (*PlatformEvent)(nil), // 26: openshell.v1.PlatformEvent - (*CreateSandboxRequest)(nil), // 27: openshell.v1.CreateSandboxRequest - (*GetSandboxRequest)(nil), // 28: openshell.v1.GetSandboxRequest - (*ListSandboxesRequest)(nil), // 29: openshell.v1.ListSandboxesRequest - (*ListSandboxProvidersRequest)(nil), // 30: openshell.v1.ListSandboxProvidersRequest - (*AttachSandboxProviderRequest)(nil), // 31: openshell.v1.AttachSandboxProviderRequest - (*DetachSandboxProviderRequest)(nil), // 32: openshell.v1.DetachSandboxProviderRequest - (*DeleteSandboxRequest)(nil), // 33: openshell.v1.DeleteSandboxRequest - (*StopSandboxRequest)(nil), // 34: openshell.v1.StopSandboxRequest - (*StartSandboxRequest)(nil), // 35: openshell.v1.StartSandboxRequest - (*SandboxResponse)(nil), // 36: openshell.v1.SandboxResponse - (*ListSandboxesResponse)(nil), // 37: openshell.v1.ListSandboxesResponse - (*ListSandboxProvidersResponse)(nil), // 38: openshell.v1.ListSandboxProvidersResponse - (*AttachSandboxProviderResponse)(nil), // 39: openshell.v1.AttachSandboxProviderResponse - (*DetachSandboxProviderResponse)(nil), // 40: openshell.v1.DetachSandboxProviderResponse - (*DeleteSandboxResponse)(nil), // 41: openshell.v1.DeleteSandboxResponse - (*CreateSshSessionRequest)(nil), // 42: openshell.v1.CreateSshSessionRequest - (*CreateSshSessionResponse)(nil), // 43: openshell.v1.CreateSshSessionResponse - (*ExposeServiceRequest)(nil), // 44: openshell.v1.ExposeServiceRequest - (*GetServiceRequest)(nil), // 45: openshell.v1.GetServiceRequest - (*ListServicesRequest)(nil), // 46: openshell.v1.ListServicesRequest - (*ListServicesResponse)(nil), // 47: openshell.v1.ListServicesResponse - (*DeleteServiceRequest)(nil), // 48: openshell.v1.DeleteServiceRequest - (*DeleteServiceResponse)(nil), // 49: openshell.v1.DeleteServiceResponse - (*ServiceEndpoint)(nil), // 50: openshell.v1.ServiceEndpoint - (*ServiceEndpointResponse)(nil), // 51: openshell.v1.ServiceEndpointResponse - (*RevokeSshSessionRequest)(nil), // 52: openshell.v1.RevokeSshSessionRequest - (*RevokeSshSessionResponse)(nil), // 53: openshell.v1.RevokeSshSessionResponse - (*ExecSandboxRequest)(nil), // 54: openshell.v1.ExecSandboxRequest - (*ExecSandboxStdout)(nil), // 55: openshell.v1.ExecSandboxStdout - (*ExecSandboxStderr)(nil), // 56: openshell.v1.ExecSandboxStderr - (*ExecSandboxExit)(nil), // 57: openshell.v1.ExecSandboxExit - (*ExecSandboxEvent)(nil), // 58: openshell.v1.ExecSandboxEvent - (*TcpForwardInit)(nil), // 59: openshell.v1.TcpForwardInit - (*TcpForwardFrame)(nil), // 60: openshell.v1.TcpForwardFrame - (*ExecSandboxInput)(nil), // 61: openshell.v1.ExecSandboxInput - (*ExecSandboxWindowResize)(nil), // 62: openshell.v1.ExecSandboxWindowResize - (*SshSession)(nil), // 63: openshell.v1.SshSession - (*WatchSandboxRequest)(nil), // 64: openshell.v1.WatchSandboxRequest - (*SandboxStreamEvent)(nil), // 65: openshell.v1.SandboxStreamEvent - (*SandboxLogLine)(nil), // 66: openshell.v1.SandboxLogLine - (*SandboxStreamWarning)(nil), // 67: openshell.v1.SandboxStreamWarning - (*CreateProviderRequest)(nil), // 68: openshell.v1.CreateProviderRequest - (*GetProviderRequest)(nil), // 69: openshell.v1.GetProviderRequest - (*ListProvidersRequest)(nil), // 70: openshell.v1.ListProvidersRequest - (*UpdateProviderRequest)(nil), // 71: openshell.v1.UpdateProviderRequest - (*DeleteProviderRequest)(nil), // 72: openshell.v1.DeleteProviderRequest - (*ProviderResponse)(nil), // 73: openshell.v1.ProviderResponse - (*ListProvidersResponse)(nil), // 74: openshell.v1.ListProvidersResponse - (*ListProviderProfilesRequest)(nil), // 75: openshell.v1.ListProviderProfilesRequest - (*GetProviderProfileRequest)(nil), // 76: openshell.v1.GetProviderProfileRequest - (*ProviderProfileImportItem)(nil), // 77: openshell.v1.ProviderProfileImportItem - (*ProviderProfileDiagnostic)(nil), // 78: openshell.v1.ProviderProfileDiagnostic - (*ProviderCredentialTokenGrantAudienceOverride)(nil), // 79: openshell.v1.ProviderCredentialTokenGrantAudienceOverride - (*ProviderCredentialTokenGrantSubjectToken)(nil), // 80: openshell.v1.ProviderCredentialTokenGrantSubjectToken - (*ProviderCredentialTokenGrant)(nil), // 81: openshell.v1.ProviderCredentialTokenGrant - (*ProviderProfileCredential)(nil), // 82: openshell.v1.ProviderProfileCredential - (*ProviderCredentialRefreshMaterial)(nil), // 83: openshell.v1.ProviderCredentialRefreshMaterial - (*ProviderCredentialRefreshOutput)(nil), // 84: openshell.v1.ProviderCredentialRefreshOutput - (*ProviderCredentialRefresh)(nil), // 85: openshell.v1.ProviderCredentialRefresh - (*ProviderCredentialRefreshStatus)(nil), // 86: openshell.v1.ProviderCredentialRefreshStatus - (*ProviderProfileDiscovery)(nil), // 87: openshell.v1.ProviderProfileDiscovery - (*StoredProviderCredentialRefreshState)(nil), // 88: openshell.v1.StoredProviderCredentialRefreshState - (*StoredRefreshMaterialDeletion)(nil), // 89: openshell.v1.StoredRefreshMaterialDeletion - (*GetProviderRefreshStatusRequest)(nil), // 90: openshell.v1.GetProviderRefreshStatusRequest - (*GetProviderRefreshStatusResponse)(nil), // 91: openshell.v1.GetProviderRefreshStatusResponse - (*ConfigureProviderRefreshRequest)(nil), // 92: openshell.v1.ConfigureProviderRefreshRequest - (*ConfigureProviderRefreshResponse)(nil), // 93: openshell.v1.ConfigureProviderRefreshResponse - (*RotateProviderCredentialRequest)(nil), // 94: openshell.v1.RotateProviderCredentialRequest - (*RotateProviderCredentialResponse)(nil), // 95: openshell.v1.RotateProviderCredentialResponse - (*DeleteProviderRefreshRequest)(nil), // 96: openshell.v1.DeleteProviderRefreshRequest - (*DeleteProviderRefreshResponse)(nil), // 97: openshell.v1.DeleteProviderRefreshResponse - (*ProviderProfile)(nil), // 98: openshell.v1.ProviderProfile - (*StoredProviderProfile)(nil), // 99: openshell.v1.StoredProviderProfile - (*ProviderProfileResponse)(nil), // 100: openshell.v1.ProviderProfileResponse - (*ListProviderProfilesResponse)(nil), // 101: openshell.v1.ListProviderProfilesResponse - (*ImportProviderProfilesRequest)(nil), // 102: openshell.v1.ImportProviderProfilesRequest - (*ImportProviderProfilesResponse)(nil), // 103: openshell.v1.ImportProviderProfilesResponse - (*UpdateProviderProfilesRequest)(nil), // 104: openshell.v1.UpdateProviderProfilesRequest - (*UpdateProviderProfilesResponse)(nil), // 105: openshell.v1.UpdateProviderProfilesResponse - (*LintProviderProfilesRequest)(nil), // 106: openshell.v1.LintProviderProfilesRequest - (*LintProviderProfilesResponse)(nil), // 107: openshell.v1.LintProviderProfilesResponse - (*DeleteProviderResponse)(nil), // 108: openshell.v1.DeleteProviderResponse - (*DeleteProviderProfileRequest)(nil), // 109: openshell.v1.DeleteProviderProfileRequest - (*DeleteProviderProfileResponse)(nil), // 110: openshell.v1.DeleteProviderProfileResponse - (*GetSandboxProviderEnvironmentRequest)(nil), // 111: openshell.v1.GetSandboxProviderEnvironmentRequest - (*StaticCredentialEndpointBinding)(nil), // 112: openshell.v1.StaticCredentialEndpointBinding - (*StaticCredentialBinding)(nil), // 113: openshell.v1.StaticCredentialBinding - (*GetSandboxProviderEnvironmentResponse)(nil), // 114: openshell.v1.GetSandboxProviderEnvironmentResponse - (*ExchangeProviderSubjectTokenRequest)(nil), // 115: openshell.v1.ExchangeProviderSubjectTokenRequest - (*ExchangeProviderSubjectTokenResponse)(nil), // 116: openshell.v1.ExchangeProviderSubjectTokenResponse - (*UpdateConfigRequest)(nil), // 117: openshell.v1.UpdateConfigRequest - (*PolicyMergeOperation)(nil), // 118: openshell.v1.PolicyMergeOperation - (*AddNetworkRule)(nil), // 119: openshell.v1.AddNetworkRule - (*RemoveNetworkEndpoint)(nil), // 120: openshell.v1.RemoveNetworkEndpoint - (*RemoveNetworkRule)(nil), // 121: openshell.v1.RemoveNetworkRule - (*AddDenyRules)(nil), // 122: openshell.v1.AddDenyRules - (*AddAllowRules)(nil), // 123: openshell.v1.AddAllowRules - (*RemoveNetworkBinary)(nil), // 124: openshell.v1.RemoveNetworkBinary - (*UpdateConfigResponse)(nil), // 125: openshell.v1.UpdateConfigResponse - (*GetSandboxPolicyStatusRequest)(nil), // 126: openshell.v1.GetSandboxPolicyStatusRequest - (*GetSandboxPolicyStatusResponse)(nil), // 127: openshell.v1.GetSandboxPolicyStatusResponse - (*ListSandboxPoliciesRequest)(nil), // 128: openshell.v1.ListSandboxPoliciesRequest - (*ListSandboxPoliciesResponse)(nil), // 129: openshell.v1.ListSandboxPoliciesResponse - (*ReportPolicyStatusRequest)(nil), // 130: openshell.v1.ReportPolicyStatusRequest - (*ReportPolicyStatusResponse)(nil), // 131: openshell.v1.ReportPolicyStatusResponse - (*SandboxPolicyRevision)(nil), // 132: openshell.v1.SandboxPolicyRevision - (*GetSandboxLogsRequest)(nil), // 133: openshell.v1.GetSandboxLogsRequest - (*PushSandboxLogsRequest)(nil), // 134: openshell.v1.PushSandboxLogsRequest - (*PushSandboxLogsResponse)(nil), // 135: openshell.v1.PushSandboxLogsResponse - (*GetSandboxLogsResponse)(nil), // 136: openshell.v1.GetSandboxLogsResponse - (*SupervisorMessage)(nil), // 137: openshell.v1.SupervisorMessage - (*GatewayMessage)(nil), // 138: openshell.v1.GatewayMessage - (*SupervisorHello)(nil), // 139: openshell.v1.SupervisorHello - (*SessionAccepted)(nil), // 140: openshell.v1.SessionAccepted - (*SessionRejected)(nil), // 141: openshell.v1.SessionRejected - (*SupervisorHeartbeat)(nil), // 142: openshell.v1.SupervisorHeartbeat - (*GatewayHeartbeat)(nil), // 143: openshell.v1.GatewayHeartbeat - (*ReportMainProcessExitRequest)(nil), // 144: openshell.v1.ReportMainProcessExitRequest - (*ReportMainProcessExitResponse)(nil), // 145: openshell.v1.ReportMainProcessExitResponse - (*RelayOpen)(nil), // 146: openshell.v1.RelayOpen - (*SshRelayTarget)(nil), // 147: openshell.v1.SshRelayTarget - (*TcpRelayTarget)(nil), // 148: openshell.v1.TcpRelayTarget - (*RelayInit)(nil), // 149: openshell.v1.RelayInit - (*RelayFrame)(nil), // 150: openshell.v1.RelayFrame - (*RelayOpenResult)(nil), // 151: openshell.v1.RelayOpenResult - (*RelayClose)(nil), // 152: openshell.v1.RelayClose - (*L7RequestSample)(nil), // 153: openshell.v1.L7RequestSample - (*DenialSummary)(nil), // 154: openshell.v1.DenialSummary - (*DenialGroupCount)(nil), // 155: openshell.v1.DenialGroupCount - (*NetworkActivitySummary)(nil), // 156: openshell.v1.NetworkActivitySummary - (*PolicyChunk)(nil), // 157: openshell.v1.PolicyChunk - (*DraftPolicyUpdate)(nil), // 158: openshell.v1.DraftPolicyUpdate - (*SubmitPolicyAnalysisRequest)(nil), // 159: openshell.v1.SubmitPolicyAnalysisRequest - (*SubmitPolicyAnalysisResponse)(nil), // 160: openshell.v1.SubmitPolicyAnalysisResponse - (*GetDraftPolicyRequest)(nil), // 161: openshell.v1.GetDraftPolicyRequest - (*GetDraftPolicyResponse)(nil), // 162: openshell.v1.GetDraftPolicyResponse - (*ApproveDraftChunkRequest)(nil), // 163: openshell.v1.ApproveDraftChunkRequest - (*ApproveDraftChunkResponse)(nil), // 164: openshell.v1.ApproveDraftChunkResponse - (*RejectDraftChunkRequest)(nil), // 165: openshell.v1.RejectDraftChunkRequest - (*RejectDraftChunkResponse)(nil), // 166: openshell.v1.RejectDraftChunkResponse - (*DraftChunkApproval)(nil), // 167: openshell.v1.DraftChunkApproval - (*ApproveAllDraftChunksRequest)(nil), // 168: openshell.v1.ApproveAllDraftChunksRequest - (*ApproveAllDraftChunksResponse)(nil), // 169: openshell.v1.ApproveAllDraftChunksResponse - (*EditDraftChunkRequest)(nil), // 170: openshell.v1.EditDraftChunkRequest - (*EditDraftChunkResponse)(nil), // 171: openshell.v1.EditDraftChunkResponse - (*UndoDraftChunkRequest)(nil), // 172: openshell.v1.UndoDraftChunkRequest - (*UndoDraftChunkResponse)(nil), // 173: openshell.v1.UndoDraftChunkResponse - (*ClearDraftChunksRequest)(nil), // 174: openshell.v1.ClearDraftChunksRequest - (*ClearDraftChunksResponse)(nil), // 175: openshell.v1.ClearDraftChunksResponse - (*GetDraftHistoryRequest)(nil), // 176: openshell.v1.GetDraftHistoryRequest - (*DraftHistoryEntry)(nil), // 177: openshell.v1.DraftHistoryEntry - (*GetDraftHistoryResponse)(nil), // 178: openshell.v1.GetDraftHistoryResponse - (*PolicyRevisionPayload)(nil), // 179: openshell.v1.PolicyRevisionPayload - (*DraftChunkPayload)(nil), // 180: openshell.v1.DraftChunkPayload - (*StoredPolicyRevision)(nil), // 181: openshell.v1.StoredPolicyRevision - (*StoredDraftChunk)(nil), // 182: openshell.v1.StoredDraftChunk - (*CreateWorkspaceRequest)(nil), // 183: openshell.v1.CreateWorkspaceRequest - (*CreateWorkspaceResponse)(nil), // 184: openshell.v1.CreateWorkspaceResponse - (*GetWorkspaceRequest)(nil), // 185: openshell.v1.GetWorkspaceRequest - (*GetWorkspaceResponse)(nil), // 186: openshell.v1.GetWorkspaceResponse - (*ListWorkspacesRequest)(nil), // 187: openshell.v1.ListWorkspacesRequest - (*ListWorkspacesResponse)(nil), // 188: openshell.v1.ListWorkspacesResponse - (*DeleteWorkspaceRequest)(nil), // 189: openshell.v1.DeleteWorkspaceRequest - (*DeleteWorkspaceResponse)(nil), // 190: openshell.v1.DeleteWorkspaceResponse - (*WorkspaceMember)(nil), // 191: openshell.v1.WorkspaceMember - (*AddWorkspaceMemberRequest)(nil), // 192: openshell.v1.AddWorkspaceMemberRequest - (*AddWorkspaceMemberResponse)(nil), // 193: openshell.v1.AddWorkspaceMemberResponse - (*RemoveWorkspaceMemberRequest)(nil), // 194: openshell.v1.RemoveWorkspaceMemberRequest - (*RemoveWorkspaceMemberResponse)(nil), // 195: openshell.v1.RemoveWorkspaceMemberResponse - (*ListWorkspaceMembersRequest)(nil), // 196: openshell.v1.ListWorkspaceMembersRequest - (*ListWorkspaceMembersResponse)(nil), // 197: openshell.v1.ListWorkspaceMembersResponse - (*ExtensionServiceCredential)(nil), // 198: openshell.v1.ExtensionServiceCredential - nil, // 199: openshell.v1.SandboxSpec.EnvironmentEntry - nil, // 200: openshell.v1.SandboxTemplate.LabelsEntry - nil, // 201: openshell.v1.SandboxTemplate.AnnotationsEntry - nil, // 202: openshell.v1.SandboxTemplate.EnvironmentEntry - nil, // 203: openshell.v1.PlatformEvent.MetadataEntry - nil, // 204: openshell.v1.CreateSandboxRequest.LabelsEntry - nil, // 205: openshell.v1.CreateSandboxRequest.AnnotationsEntry - nil, // 206: openshell.v1.ExecSandboxRequest.EnvironmentEntry - nil, // 207: openshell.v1.SandboxLogLine.FieldsEntry - nil, // 208: openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry - nil, // 209: openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry - nil, // 210: openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry - nil, // 211: openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry - nil, // 212: openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - nil, // 213: openshell.v1.ProviderProfile.AnnotationsEntry - nil, // 214: openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - nil, // 215: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry - nil, // 216: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - nil, // 217: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - nil, // 218: openshell.v1.UpdateConfigRequest.AnnotationsEntry - nil, // 219: openshell.v1.UpdateConfigResponse.AnnotationsEntry - nil, // 220: openshell.v1.SandboxPolicyRevision.ProvenanceEntry - nil, // 221: openshell.v1.PolicyRevisionPayload.ProvenanceEntry - nil, // 222: openshell.v1.StoredPolicyRevision.ProvenanceEntry - nil, // 223: openshell.v1.CreateWorkspaceRequest.LabelsEntry - (*datamodelv1.ObjectMeta)(nil), // 224: openshell.datamodel.v1.ObjectMeta - (*sandboxv1.SandboxPolicy)(nil), // 225: openshell.sandbox.v1.SandboxPolicy - (*structpb.Struct)(nil), // 226: google.protobuf.Struct - (*datamodelv1.Provider)(nil), // 227: openshell.datamodel.v1.Provider - (*datamodelv1.CredentialHandle)(nil), // 228: openshell.datamodel.v1.CredentialHandle - (*sandboxv1.NetworkEndpoint)(nil), // 229: openshell.sandbox.v1.NetworkEndpoint - (*sandboxv1.NetworkBinary)(nil), // 230: openshell.sandbox.v1.NetworkBinary - (*sandboxv1.SettingValue)(nil), // 231: openshell.sandbox.v1.SettingValue - (*sandboxv1.NetworkPolicyRule)(nil), // 232: openshell.sandbox.v1.NetworkPolicyRule - (*sandboxv1.L7DenyRule)(nil), // 233: openshell.sandbox.v1.L7DenyRule - (*sandboxv1.L7Rule)(nil), // 234: openshell.sandbox.v1.L7Rule - (*datamodelv1.Workspace)(nil), // 235: openshell.datamodel.v1.Workspace - (*sandboxv1.GetSandboxConfigRequest)(nil), // 236: openshell.sandbox.v1.GetSandboxConfigRequest - (*sandboxv1.GetGatewayConfigRequest)(nil), // 237: openshell.sandbox.v1.GetGatewayConfigRequest - (*sandboxv1.GetSandboxConfigResponse)(nil), // 238: openshell.sandbox.v1.GetSandboxConfigResponse - (*sandboxv1.GetGatewayConfigResponse)(nil), // 239: openshell.sandbox.v1.GetGatewayConfigResponse + (ProviderCredentialRefreshRecoveryAction)(0), // 7: openshell.v1.ProviderCredentialRefreshRecoveryAction + (*IssueSandboxTokenRequest)(nil), // 8: openshell.v1.IssueSandboxTokenRequest + (*IssueSandboxTokenResponse)(nil), // 9: openshell.v1.IssueSandboxTokenResponse + (*RefreshSandboxTokenRequest)(nil), // 10: openshell.v1.RefreshSandboxTokenRequest + (*RefreshSandboxTokenResponse)(nil), // 11: openshell.v1.RefreshSandboxTokenResponse + (*HealthRequest)(nil), // 12: openshell.v1.HealthRequest + (*HealthResponse)(nil), // 13: openshell.v1.HealthResponse + (*GetCurrentUserRequest)(nil), // 14: openshell.v1.GetCurrentUserRequest + (*GetCurrentUserResponse)(nil), // 15: openshell.v1.GetCurrentUserResponse + (*GetGatewayInfoRequest)(nil), // 16: openshell.v1.GetGatewayInfoRequest + (*GetGatewayInfoResponse)(nil), // 17: openshell.v1.GetGatewayInfoResponse + (*ComputeDriverInfo)(nil), // 18: openshell.v1.ComputeDriverInfo + (*ComputeDriverCapabilities)(nil), // 19: openshell.v1.ComputeDriverCapabilities + (*Sandbox)(nil), // 20: openshell.v1.Sandbox + (*SandboxSpec)(nil), // 21: openshell.v1.SandboxSpec + (*ResourceRequirements)(nil), // 22: openshell.v1.ResourceRequirements + (*GpuResourceRequirements)(nil), // 23: openshell.v1.GpuResourceRequirements + (*SandboxTemplate)(nil), // 24: openshell.v1.SandboxTemplate + (*SandboxStatus)(nil), // 25: openshell.v1.SandboxStatus + (*SandboxCondition)(nil), // 26: openshell.v1.SandboxCondition + (*PlatformEvent)(nil), // 27: openshell.v1.PlatformEvent + (*CreateSandboxRequest)(nil), // 28: openshell.v1.CreateSandboxRequest + (*GetSandboxRequest)(nil), // 29: openshell.v1.GetSandboxRequest + (*ListSandboxesRequest)(nil), // 30: openshell.v1.ListSandboxesRequest + (*ListSandboxProvidersRequest)(nil), // 31: openshell.v1.ListSandboxProvidersRequest + (*AttachSandboxProviderRequest)(nil), // 32: openshell.v1.AttachSandboxProviderRequest + (*DetachSandboxProviderRequest)(nil), // 33: openshell.v1.DetachSandboxProviderRequest + (*DeleteSandboxRequest)(nil), // 34: openshell.v1.DeleteSandboxRequest + (*StopSandboxRequest)(nil), // 35: openshell.v1.StopSandboxRequest + (*StartSandboxRequest)(nil), // 36: openshell.v1.StartSandboxRequest + (*SandboxResponse)(nil), // 37: openshell.v1.SandboxResponse + (*ListSandboxesResponse)(nil), // 38: openshell.v1.ListSandboxesResponse + (*ListSandboxProvidersResponse)(nil), // 39: openshell.v1.ListSandboxProvidersResponse + (*AttachSandboxProviderResponse)(nil), // 40: openshell.v1.AttachSandboxProviderResponse + (*DetachSandboxProviderResponse)(nil), // 41: openshell.v1.DetachSandboxProviderResponse + (*DeleteSandboxResponse)(nil), // 42: openshell.v1.DeleteSandboxResponse + (*CreateSshSessionRequest)(nil), // 43: openshell.v1.CreateSshSessionRequest + (*CreateSshSessionResponse)(nil), // 44: openshell.v1.CreateSshSessionResponse + (*ExposeServiceRequest)(nil), // 45: openshell.v1.ExposeServiceRequest + (*GetServiceRequest)(nil), // 46: openshell.v1.GetServiceRequest + (*ListServicesRequest)(nil), // 47: openshell.v1.ListServicesRequest + (*ListServicesResponse)(nil), // 48: openshell.v1.ListServicesResponse + (*DeleteServiceRequest)(nil), // 49: openshell.v1.DeleteServiceRequest + (*DeleteServiceResponse)(nil), // 50: openshell.v1.DeleteServiceResponse + (*ServiceEndpoint)(nil), // 51: openshell.v1.ServiceEndpoint + (*ServiceEndpointResponse)(nil), // 52: openshell.v1.ServiceEndpointResponse + (*RevokeSshSessionRequest)(nil), // 53: openshell.v1.RevokeSshSessionRequest + (*RevokeSshSessionResponse)(nil), // 54: openshell.v1.RevokeSshSessionResponse + (*ExecSandboxRequest)(nil), // 55: openshell.v1.ExecSandboxRequest + (*ExecSandboxStdout)(nil), // 56: openshell.v1.ExecSandboxStdout + (*ExecSandboxStderr)(nil), // 57: openshell.v1.ExecSandboxStderr + (*ExecSandboxExit)(nil), // 58: openshell.v1.ExecSandboxExit + (*ExecSandboxEvent)(nil), // 59: openshell.v1.ExecSandboxEvent + (*TcpForwardInit)(nil), // 60: openshell.v1.TcpForwardInit + (*TcpForwardFrame)(nil), // 61: openshell.v1.TcpForwardFrame + (*ExecSandboxInput)(nil), // 62: openshell.v1.ExecSandboxInput + (*ExecSandboxWindowResize)(nil), // 63: openshell.v1.ExecSandboxWindowResize + (*SshSession)(nil), // 64: openshell.v1.SshSession + (*WatchSandboxRequest)(nil), // 65: openshell.v1.WatchSandboxRequest + (*SandboxStreamEvent)(nil), // 66: openshell.v1.SandboxStreamEvent + (*SandboxLogLine)(nil), // 67: openshell.v1.SandboxLogLine + (*SandboxStreamWarning)(nil), // 68: openshell.v1.SandboxStreamWarning + (*CreateProviderRequest)(nil), // 69: openshell.v1.CreateProviderRequest + (*GetProviderRequest)(nil), // 70: openshell.v1.GetProviderRequest + (*ListProvidersRequest)(nil), // 71: openshell.v1.ListProvidersRequest + (*UpdateProviderRequest)(nil), // 72: openshell.v1.UpdateProviderRequest + (*DeleteProviderRequest)(nil), // 73: openshell.v1.DeleteProviderRequest + (*ProviderResponse)(nil), // 74: openshell.v1.ProviderResponse + (*ListProvidersResponse)(nil), // 75: openshell.v1.ListProvidersResponse + (*ListProviderProfilesRequest)(nil), // 76: openshell.v1.ListProviderProfilesRequest + (*GetProviderProfileRequest)(nil), // 77: openshell.v1.GetProviderProfileRequest + (*ProviderProfileImportItem)(nil), // 78: openshell.v1.ProviderProfileImportItem + (*ProviderProfileDiagnostic)(nil), // 79: openshell.v1.ProviderProfileDiagnostic + (*ProviderCredentialTokenGrantAudienceOverride)(nil), // 80: openshell.v1.ProviderCredentialTokenGrantAudienceOverride + (*ProviderCredentialTokenGrantSubjectToken)(nil), // 81: openshell.v1.ProviderCredentialTokenGrantSubjectToken + (*ProviderCredentialTokenGrant)(nil), // 82: openshell.v1.ProviderCredentialTokenGrant + (*ProviderProfileCredential)(nil), // 83: openshell.v1.ProviderProfileCredential + (*ProviderCredentialRefreshMaterial)(nil), // 84: openshell.v1.ProviderCredentialRefreshMaterial + (*ProviderCredentialRefreshOutput)(nil), // 85: openshell.v1.ProviderCredentialRefreshOutput + (*ProviderCredentialRefresh)(nil), // 86: openshell.v1.ProviderCredentialRefresh + (*ProviderCredentialRefreshStatus)(nil), // 87: openshell.v1.ProviderCredentialRefreshStatus + (*ProviderProfileDiscovery)(nil), // 88: openshell.v1.ProviderProfileDiscovery + (*StoredProviderCredentialRefreshState)(nil), // 89: openshell.v1.StoredProviderCredentialRefreshState + (*StoredRefreshMaterialDeletion)(nil), // 90: openshell.v1.StoredRefreshMaterialDeletion + (*GetProviderRefreshStatusRequest)(nil), // 91: openshell.v1.GetProviderRefreshStatusRequest + (*GetProviderRefreshStatusResponse)(nil), // 92: openshell.v1.GetProviderRefreshStatusResponse + (*ConfigureProviderRefreshRequest)(nil), // 93: openshell.v1.ConfigureProviderRefreshRequest + (*ConfigureProviderRefreshResponse)(nil), // 94: openshell.v1.ConfigureProviderRefreshResponse + (*RotateProviderCredentialRequest)(nil), // 95: openshell.v1.RotateProviderCredentialRequest + (*RotateProviderCredentialResponse)(nil), // 96: openshell.v1.RotateProviderCredentialResponse + (*DeleteProviderRefreshRequest)(nil), // 97: openshell.v1.DeleteProviderRefreshRequest + (*DeleteProviderRefreshResponse)(nil), // 98: openshell.v1.DeleteProviderRefreshResponse + (*ProviderProfile)(nil), // 99: openshell.v1.ProviderProfile + (*StoredProviderProfile)(nil), // 100: openshell.v1.StoredProviderProfile + (*ProviderProfileResponse)(nil), // 101: openshell.v1.ProviderProfileResponse + (*ListProviderProfilesResponse)(nil), // 102: openshell.v1.ListProviderProfilesResponse + (*ImportProviderProfilesRequest)(nil), // 103: openshell.v1.ImportProviderProfilesRequest + (*ImportProviderProfilesResponse)(nil), // 104: openshell.v1.ImportProviderProfilesResponse + (*UpdateProviderProfilesRequest)(nil), // 105: openshell.v1.UpdateProviderProfilesRequest + (*UpdateProviderProfilesResponse)(nil), // 106: openshell.v1.UpdateProviderProfilesResponse + (*LintProviderProfilesRequest)(nil), // 107: openshell.v1.LintProviderProfilesRequest + (*LintProviderProfilesResponse)(nil), // 108: openshell.v1.LintProviderProfilesResponse + (*DeleteProviderResponse)(nil), // 109: openshell.v1.DeleteProviderResponse + (*DeleteProviderProfileRequest)(nil), // 110: openshell.v1.DeleteProviderProfileRequest + (*DeleteProviderProfileResponse)(nil), // 111: openshell.v1.DeleteProviderProfileResponse + (*GetSandboxProviderEnvironmentRequest)(nil), // 112: openshell.v1.GetSandboxProviderEnvironmentRequest + (*StaticCredentialEndpointBinding)(nil), // 113: openshell.v1.StaticCredentialEndpointBinding + (*StaticCredentialBinding)(nil), // 114: openshell.v1.StaticCredentialBinding + (*GetSandboxProviderEnvironmentResponse)(nil), // 115: openshell.v1.GetSandboxProviderEnvironmentResponse + (*ExchangeProviderSubjectTokenRequest)(nil), // 116: openshell.v1.ExchangeProviderSubjectTokenRequest + (*ExchangeProviderSubjectTokenResponse)(nil), // 117: openshell.v1.ExchangeProviderSubjectTokenResponse + (*UpdateConfigRequest)(nil), // 118: openshell.v1.UpdateConfigRequest + (*PolicyMergeOperation)(nil), // 119: openshell.v1.PolicyMergeOperation + (*AddNetworkRule)(nil), // 120: openshell.v1.AddNetworkRule + (*RemoveNetworkEndpoint)(nil), // 121: openshell.v1.RemoveNetworkEndpoint + (*RemoveNetworkRule)(nil), // 122: openshell.v1.RemoveNetworkRule + (*AddDenyRules)(nil), // 123: openshell.v1.AddDenyRules + (*AddAllowRules)(nil), // 124: openshell.v1.AddAllowRules + (*RemoveNetworkBinary)(nil), // 125: openshell.v1.RemoveNetworkBinary + (*UpdateConfigResponse)(nil), // 126: openshell.v1.UpdateConfigResponse + (*GetSandboxPolicyStatusRequest)(nil), // 127: openshell.v1.GetSandboxPolicyStatusRequest + (*GetSandboxPolicyStatusResponse)(nil), // 128: openshell.v1.GetSandboxPolicyStatusResponse + (*ListSandboxPoliciesRequest)(nil), // 129: openshell.v1.ListSandboxPoliciesRequest + (*ListSandboxPoliciesResponse)(nil), // 130: openshell.v1.ListSandboxPoliciesResponse + (*ReportPolicyStatusRequest)(nil), // 131: openshell.v1.ReportPolicyStatusRequest + (*ReportPolicyStatusResponse)(nil), // 132: openshell.v1.ReportPolicyStatusResponse + (*SandboxPolicyRevision)(nil), // 133: openshell.v1.SandboxPolicyRevision + (*GetSandboxLogsRequest)(nil), // 134: openshell.v1.GetSandboxLogsRequest + (*PushSandboxLogsRequest)(nil), // 135: openshell.v1.PushSandboxLogsRequest + (*PushSandboxLogsResponse)(nil), // 136: openshell.v1.PushSandboxLogsResponse + (*GetSandboxLogsResponse)(nil), // 137: openshell.v1.GetSandboxLogsResponse + (*SupervisorMessage)(nil), // 138: openshell.v1.SupervisorMessage + (*GatewayMessage)(nil), // 139: openshell.v1.GatewayMessage + (*SupervisorHello)(nil), // 140: openshell.v1.SupervisorHello + (*SessionAccepted)(nil), // 141: openshell.v1.SessionAccepted + (*SessionRejected)(nil), // 142: openshell.v1.SessionRejected + (*SupervisorHeartbeat)(nil), // 143: openshell.v1.SupervisorHeartbeat + (*GatewayHeartbeat)(nil), // 144: openshell.v1.GatewayHeartbeat + (*ReportMainProcessExitRequest)(nil), // 145: openshell.v1.ReportMainProcessExitRequest + (*ReportMainProcessExitResponse)(nil), // 146: openshell.v1.ReportMainProcessExitResponse + (*RelayOpen)(nil), // 147: openshell.v1.RelayOpen + (*SshRelayTarget)(nil), // 148: openshell.v1.SshRelayTarget + (*TcpRelayTarget)(nil), // 149: openshell.v1.TcpRelayTarget + (*RelayInit)(nil), // 150: openshell.v1.RelayInit + (*RelayFrame)(nil), // 151: openshell.v1.RelayFrame + (*RelayOpenResult)(nil), // 152: openshell.v1.RelayOpenResult + (*RelayClose)(nil), // 153: openshell.v1.RelayClose + (*L7RequestSample)(nil), // 154: openshell.v1.L7RequestSample + (*DenialSummary)(nil), // 155: openshell.v1.DenialSummary + (*DenialGroupCount)(nil), // 156: openshell.v1.DenialGroupCount + (*NetworkActivitySummary)(nil), // 157: openshell.v1.NetworkActivitySummary + (*PolicyChunk)(nil), // 158: openshell.v1.PolicyChunk + (*DraftPolicyUpdate)(nil), // 159: openshell.v1.DraftPolicyUpdate + (*SubmitPolicyAnalysisRequest)(nil), // 160: openshell.v1.SubmitPolicyAnalysisRequest + (*SubmitPolicyAnalysisResponse)(nil), // 161: openshell.v1.SubmitPolicyAnalysisResponse + (*GetDraftPolicyRequest)(nil), // 162: openshell.v1.GetDraftPolicyRequest + (*GetDraftPolicyResponse)(nil), // 163: openshell.v1.GetDraftPolicyResponse + (*ApproveDraftChunkRequest)(nil), // 164: openshell.v1.ApproveDraftChunkRequest + (*ApproveDraftChunkResponse)(nil), // 165: openshell.v1.ApproveDraftChunkResponse + (*RejectDraftChunkRequest)(nil), // 166: openshell.v1.RejectDraftChunkRequest + (*RejectDraftChunkResponse)(nil), // 167: openshell.v1.RejectDraftChunkResponse + (*DraftChunkApproval)(nil), // 168: openshell.v1.DraftChunkApproval + (*ApproveAllDraftChunksRequest)(nil), // 169: openshell.v1.ApproveAllDraftChunksRequest + (*ApproveAllDraftChunksResponse)(nil), // 170: openshell.v1.ApproveAllDraftChunksResponse + (*EditDraftChunkRequest)(nil), // 171: openshell.v1.EditDraftChunkRequest + (*EditDraftChunkResponse)(nil), // 172: openshell.v1.EditDraftChunkResponse + (*UndoDraftChunkRequest)(nil), // 173: openshell.v1.UndoDraftChunkRequest + (*UndoDraftChunkResponse)(nil), // 174: openshell.v1.UndoDraftChunkResponse + (*ClearDraftChunksRequest)(nil), // 175: openshell.v1.ClearDraftChunksRequest + (*ClearDraftChunksResponse)(nil), // 176: openshell.v1.ClearDraftChunksResponse + (*GetDraftHistoryRequest)(nil), // 177: openshell.v1.GetDraftHistoryRequest + (*DraftHistoryEntry)(nil), // 178: openshell.v1.DraftHistoryEntry + (*GetDraftHistoryResponse)(nil), // 179: openshell.v1.GetDraftHistoryResponse + (*PolicyRevisionPayload)(nil), // 180: openshell.v1.PolicyRevisionPayload + (*DraftChunkPayload)(nil), // 181: openshell.v1.DraftChunkPayload + (*StoredPolicyRevision)(nil), // 182: openshell.v1.StoredPolicyRevision + (*StoredDraftChunk)(nil), // 183: openshell.v1.StoredDraftChunk + (*CreateWorkspaceRequest)(nil), // 184: openshell.v1.CreateWorkspaceRequest + (*CreateWorkspaceResponse)(nil), // 185: openshell.v1.CreateWorkspaceResponse + (*GetWorkspaceRequest)(nil), // 186: openshell.v1.GetWorkspaceRequest + (*GetWorkspaceResponse)(nil), // 187: openshell.v1.GetWorkspaceResponse + (*ListWorkspacesRequest)(nil), // 188: openshell.v1.ListWorkspacesRequest + (*ListWorkspacesResponse)(nil), // 189: openshell.v1.ListWorkspacesResponse + (*DeleteWorkspaceRequest)(nil), // 190: openshell.v1.DeleteWorkspaceRequest + (*DeleteWorkspaceResponse)(nil), // 191: openshell.v1.DeleteWorkspaceResponse + (*WorkspaceMember)(nil), // 192: openshell.v1.WorkspaceMember + (*AddWorkspaceMemberRequest)(nil), // 193: openshell.v1.AddWorkspaceMemberRequest + (*AddWorkspaceMemberResponse)(nil), // 194: openshell.v1.AddWorkspaceMemberResponse + (*RemoveWorkspaceMemberRequest)(nil), // 195: openshell.v1.RemoveWorkspaceMemberRequest + (*RemoveWorkspaceMemberResponse)(nil), // 196: openshell.v1.RemoveWorkspaceMemberResponse + (*ListWorkspaceMembersRequest)(nil), // 197: openshell.v1.ListWorkspaceMembersRequest + (*ListWorkspaceMembersResponse)(nil), // 198: openshell.v1.ListWorkspaceMembersResponse + (*ExtensionServiceCredential)(nil), // 199: openshell.v1.ExtensionServiceCredential + nil, // 200: openshell.v1.SandboxSpec.EnvironmentEntry + nil, // 201: openshell.v1.SandboxTemplate.LabelsEntry + nil, // 202: openshell.v1.SandboxTemplate.AnnotationsEntry + nil, // 203: openshell.v1.SandboxTemplate.EnvironmentEntry + nil, // 204: openshell.v1.PlatformEvent.MetadataEntry + nil, // 205: openshell.v1.CreateSandboxRequest.LabelsEntry + nil, // 206: openshell.v1.CreateSandboxRequest.AnnotationsEntry + nil, // 207: openshell.v1.ExecSandboxRequest.EnvironmentEntry + nil, // 208: openshell.v1.SandboxLogLine.FieldsEntry + nil, // 209: openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry + nil, // 210: openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry + nil, // 211: openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry + nil, // 212: openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry + nil, // 213: openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + nil, // 214: openshell.v1.ProviderProfile.AnnotationsEntry + nil, // 215: openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + nil, // 216: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry + nil, // 217: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + nil, // 218: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + nil, // 219: openshell.v1.UpdateConfigRequest.AnnotationsEntry + nil, // 220: openshell.v1.UpdateConfigResponse.AnnotationsEntry + nil, // 221: openshell.v1.SandboxPolicyRevision.ProvenanceEntry + nil, // 222: openshell.v1.PolicyRevisionPayload.ProvenanceEntry + nil, // 223: openshell.v1.StoredPolicyRevision.ProvenanceEntry + nil, // 224: openshell.v1.CreateWorkspaceRequest.LabelsEntry + (*datamodelv1.ObjectMeta)(nil), // 225: openshell.datamodel.v1.ObjectMeta + (*sandboxv1.SandboxPolicy)(nil), // 226: openshell.sandbox.v1.SandboxPolicy + (*structpb.Struct)(nil), // 227: google.protobuf.Struct + (*datamodelv1.Provider)(nil), // 228: openshell.datamodel.v1.Provider + (*datamodelv1.CredentialHandle)(nil), // 229: openshell.datamodel.v1.CredentialHandle + (*sandboxv1.NetworkEndpoint)(nil), // 230: openshell.sandbox.v1.NetworkEndpoint + (*sandboxv1.NetworkBinary)(nil), // 231: openshell.sandbox.v1.NetworkBinary + (*sandboxv1.SettingValue)(nil), // 232: openshell.sandbox.v1.SettingValue + (*sandboxv1.NetworkPolicyRule)(nil), // 233: openshell.sandbox.v1.NetworkPolicyRule + (*sandboxv1.L7DenyRule)(nil), // 234: openshell.sandbox.v1.L7DenyRule + (*sandboxv1.L7Rule)(nil), // 235: openshell.sandbox.v1.L7Rule + (*datamodelv1.Workspace)(nil), // 236: openshell.datamodel.v1.Workspace + (*sandboxv1.GetSandboxConfigRequest)(nil), // 237: openshell.sandbox.v1.GetSandboxConfigRequest + (*sandboxv1.GetGatewayConfigRequest)(nil), // 238: openshell.sandbox.v1.GetGatewayConfigRequest + (*sandboxv1.GetSandboxConfigResponse)(nil), // 239: openshell.sandbox.v1.GetSandboxConfigResponse + (*sandboxv1.GetGatewayConfigResponse)(nil), // 240: openshell.sandbox.v1.GetGatewayConfigResponse } var file_openshell_proto_depIdxs = []int32{ - 198, // 0: openshell.v1.RefreshSandboxTokenResponse.extension_credentials:type_name -> openshell.v1.ExtensionServiceCredential + 199, // 0: openshell.v1.RefreshSandboxTokenResponse.extension_credentials:type_name -> openshell.v1.ExtensionServiceCredential 5, // 1: openshell.v1.HealthResponse.status:type_name -> openshell.v1.ServiceStatus 5, // 2: openshell.v1.GetGatewayInfoResponse.status:type_name -> openshell.v1.ServiceStatus - 17, // 3: openshell.v1.GetGatewayInfoResponse.compute_drivers:type_name -> openshell.v1.ComputeDriverInfo - 18, // 4: openshell.v1.ComputeDriverInfo.capabilities:type_name -> openshell.v1.ComputeDriverCapabilities - 224, // 5: openshell.v1.Sandbox.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 20, // 6: openshell.v1.Sandbox.spec:type_name -> openshell.v1.SandboxSpec - 24, // 7: openshell.v1.Sandbox.status:type_name -> openshell.v1.SandboxStatus - 199, // 8: openshell.v1.SandboxSpec.environment:type_name -> openshell.v1.SandboxSpec.EnvironmentEntry - 23, // 9: openshell.v1.SandboxSpec.template:type_name -> openshell.v1.SandboxTemplate - 225, // 10: openshell.v1.SandboxSpec.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 21, // 11: openshell.v1.SandboxSpec.resource_requirements:type_name -> openshell.v1.ResourceRequirements - 22, // 12: openshell.v1.ResourceRequirements.gpu:type_name -> openshell.v1.GpuResourceRequirements - 200, // 13: openshell.v1.SandboxTemplate.labels:type_name -> openshell.v1.SandboxTemplate.LabelsEntry - 201, // 14: openshell.v1.SandboxTemplate.annotations:type_name -> openshell.v1.SandboxTemplate.AnnotationsEntry - 202, // 15: openshell.v1.SandboxTemplate.environment:type_name -> openshell.v1.SandboxTemplate.EnvironmentEntry - 226, // 16: openshell.v1.SandboxTemplate.resources:type_name -> google.protobuf.Struct - 226, // 17: openshell.v1.SandboxTemplate.driver_config:type_name -> google.protobuf.Struct - 25, // 18: openshell.v1.SandboxStatus.conditions:type_name -> openshell.v1.SandboxCondition + 18, // 3: openshell.v1.GetGatewayInfoResponse.compute_drivers:type_name -> openshell.v1.ComputeDriverInfo + 19, // 4: openshell.v1.ComputeDriverInfo.capabilities:type_name -> openshell.v1.ComputeDriverCapabilities + 225, // 5: openshell.v1.Sandbox.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 21, // 6: openshell.v1.Sandbox.spec:type_name -> openshell.v1.SandboxSpec + 25, // 7: openshell.v1.Sandbox.status:type_name -> openshell.v1.SandboxStatus + 200, // 8: openshell.v1.SandboxSpec.environment:type_name -> openshell.v1.SandboxSpec.EnvironmentEntry + 24, // 9: openshell.v1.SandboxSpec.template:type_name -> openshell.v1.SandboxTemplate + 226, // 10: openshell.v1.SandboxSpec.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 22, // 11: openshell.v1.SandboxSpec.resource_requirements:type_name -> openshell.v1.ResourceRequirements + 23, // 12: openshell.v1.ResourceRequirements.gpu:type_name -> openshell.v1.GpuResourceRequirements + 201, // 13: openshell.v1.SandboxTemplate.labels:type_name -> openshell.v1.SandboxTemplate.LabelsEntry + 202, // 14: openshell.v1.SandboxTemplate.annotations:type_name -> openshell.v1.SandboxTemplate.AnnotationsEntry + 203, // 15: openshell.v1.SandboxTemplate.environment:type_name -> openshell.v1.SandboxTemplate.EnvironmentEntry + 227, // 16: openshell.v1.SandboxTemplate.resources:type_name -> google.protobuf.Struct + 227, // 17: openshell.v1.SandboxTemplate.driver_config:type_name -> google.protobuf.Struct + 26, // 18: openshell.v1.SandboxStatus.conditions:type_name -> openshell.v1.SandboxCondition 0, // 19: openshell.v1.SandboxStatus.phase:type_name -> openshell.v1.SandboxPhase - 203, // 20: openshell.v1.PlatformEvent.metadata:type_name -> openshell.v1.PlatformEvent.MetadataEntry - 20, // 21: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec - 204, // 22: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry - 205, // 23: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry - 19, // 24: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox - 19, // 25: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox - 227, // 26: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 19, // 27: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 19, // 28: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 51, // 29: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse - 224, // 30: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 50, // 31: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint - 206, // 32: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry - 55, // 33: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout - 56, // 34: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr - 57, // 35: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit - 147, // 36: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget - 148, // 37: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget - 59, // 38: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit - 54, // 39: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest - 62, // 40: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize - 224, // 41: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 19, // 42: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox - 66, // 43: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine - 26, // 44: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent - 67, // 45: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning - 158, // 46: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate - 207, // 47: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry - 227, // 48: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 227, // 49: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 208, // 50: openshell.v1.UpdateProviderRequest.credential_expires_at_ms:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry - 227, // 51: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider - 227, // 52: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 98, // 53: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile - 79, // 54: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride + 204, // 20: openshell.v1.PlatformEvent.metadata:type_name -> openshell.v1.PlatformEvent.MetadataEntry + 21, // 21: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec + 205, // 22: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry + 206, // 23: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry + 20, // 24: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox + 20, // 25: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox + 228, // 26: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 20, // 27: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 20, // 28: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 52, // 29: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse + 225, // 30: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 51, // 31: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint + 207, // 32: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry + 56, // 33: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout + 57, // 34: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr + 58, // 35: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit + 148, // 36: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget + 149, // 37: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget + 60, // 38: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit + 55, // 39: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest + 63, // 40: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize + 225, // 41: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 20, // 42: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox + 67, // 43: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine + 27, // 44: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent + 68, // 45: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning + 159, // 46: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate + 208, // 47: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry + 228, // 48: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 228, // 49: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 209, // 50: openshell.v1.UpdateProviderRequest.credential_expires_at_ms:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry + 228, // 51: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider + 228, // 52: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 99, // 53: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile + 80, // 54: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride 1, // 55: openshell.v1.ProviderCredentialTokenGrant.grant_type:type_name -> openshell.v1.ProviderCredentialTokenGrantType - 80, // 56: openshell.v1.ProviderCredentialTokenGrant.subject_token:type_name -> openshell.v1.ProviderCredentialTokenGrantSubjectToken - 85, // 57: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh - 81, // 58: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant + 81, // 56: openshell.v1.ProviderCredentialTokenGrant.subject_token:type_name -> openshell.v1.ProviderCredentialTokenGrantSubjectToken + 86, // 57: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh + 82, // 58: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant 2, // 59: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 83, // 60: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial - 84, // 61: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput + 84, // 60: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial + 85, // 61: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput 2, // 62: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 224, // 63: openshell.v1.StoredProviderCredentialRefreshState.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 2, // 64: openshell.v1.StoredProviderCredentialRefreshState.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 209, // 65: openshell.v1.StoredProviderCredentialRefreshState.material:type_name -> openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry - 210, // 66: openshell.v1.StoredProviderCredentialRefreshState.additional_output_keys:type_name -> openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry - 211, // 67: openshell.v1.StoredProviderCredentialRefreshState.secret_material_handles:type_name -> openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry - 89, // 68: openshell.v1.StoredProviderCredentialRefreshState.pending_secret_deletions:type_name -> openshell.v1.StoredRefreshMaterialDeletion - 228, // 69: openshell.v1.StoredRefreshMaterialDeletion.handle:type_name -> openshell.datamodel.v1.CredentialHandle - 86, // 70: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 2, // 71: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 212, // 72: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - 86, // 73: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 86, // 74: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 3, // 75: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory - 82, // 76: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential - 229, // 77: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint - 230, // 78: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary - 87, // 79: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery - 213, // 80: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry - 224, // 81: openshell.v1.StoredProviderProfile.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 98, // 82: openshell.v1.StoredProviderProfile.profile:type_name -> openshell.v1.ProviderProfile - 98, // 83: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile - 98, // 84: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 77, // 85: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 78, // 86: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 98, // 87: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 77, // 88: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem - 78, // 89: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 98, // 90: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile - 77, // 91: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 78, // 92: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 112, // 93: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding - 214, // 94: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - 215, // 95: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expires_at_ms:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry - 216, // 96: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - 217, // 97: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - 225, // 98: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 231, // 99: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue - 118, // 100: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation - 218, // 101: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry - 119, // 102: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule - 120, // 103: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint - 121, // 104: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule - 122, // 105: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules - 123, // 106: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules - 124, // 107: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary - 232, // 108: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 233, // 109: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule - 234, // 110: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule - 219, // 111: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry - 132, // 112: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision - 132, // 113: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision - 4, // 114: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus - 4, // 115: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus - 225, // 116: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 220, // 117: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry - 66, // 118: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine - 66, // 119: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine - 139, // 120: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello - 142, // 121: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat - 151, // 122: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult - 152, // 123: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose - 140, // 124: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted - 141, // 125: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected - 143, // 126: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat - 146, // 127: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen - 152, // 128: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose - 147, // 129: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget - 148, // 130: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget - 149, // 131: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit - 153, // 132: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample - 155, // 133: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount - 232, // 134: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 225, // 135: openshell.v1.PolicyChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 225, // 136: openshell.v1.PolicyChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 154, // 137: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary - 157, // 138: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk - 156, // 139: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary - 157, // 140: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk - 167, // 141: openshell.v1.ApproveAllDraftChunksRequest.approvals:type_name -> openshell.v1.DraftChunkApproval - 232, // 142: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 177, // 143: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry - 225, // 144: openshell.v1.PolicyRevisionPayload.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 221, // 145: openshell.v1.PolicyRevisionPayload.provenance:type_name -> openshell.v1.PolicyRevisionPayload.ProvenanceEntry - 232, // 146: openshell.v1.DraftChunkPayload.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 225, // 147: openshell.v1.DraftChunkPayload.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 225, // 148: openshell.v1.DraftChunkPayload.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 222, // 149: openshell.v1.StoredPolicyRevision.provenance:type_name -> openshell.v1.StoredPolicyRevision.ProvenanceEntry - 225, // 150: openshell.v1.StoredDraftChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 225, // 151: openshell.v1.StoredDraftChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 223, // 152: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry - 235, // 153: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 235, // 154: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 235, // 155: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace - 224, // 156: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 6, // 157: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole - 6, // 158: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole - 191, // 159: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember - 191, // 160: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember - 228, // 161: openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry.value:type_name -> openshell.datamodel.v1.CredentialHandle - 82, // 162: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential - 113, // 163: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding - 11, // 164: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest - 13, // 165: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest - 15, // 166: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest - 27, // 167: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest - 28, // 168: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest - 29, // 169: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest - 30, // 170: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest - 31, // 171: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest - 32, // 172: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest - 33, // 173: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest - 34, // 174: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest - 35, // 175: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest - 42, // 176: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest - 44, // 177: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest - 45, // 178: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest - 46, // 179: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest - 48, // 180: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest - 52, // 181: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest - 54, // 182: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest - 60, // 183: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame - 61, // 184: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput - 68, // 185: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest - 69, // 186: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest - 70, // 187: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest - 75, // 188: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest - 76, // 189: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest - 102, // 190: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest - 104, // 191: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest - 106, // 192: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest - 71, // 193: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest - 90, // 194: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest - 92, // 195: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest - 94, // 196: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest - 96, // 197: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest - 72, // 198: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest - 109, // 199: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest - 236, // 200: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest - 237, // 201: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest - 117, // 202: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest - 126, // 203: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest - 128, // 204: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest - 130, // 205: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest - 111, // 206: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest - 115, // 207: openshell.v1.OpenShell.ExchangeProviderSubjectToken:input_type -> openshell.v1.ExchangeProviderSubjectTokenRequest - 133, // 208: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest - 134, // 209: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest - 137, // 210: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage - 144, // 211: openshell.v1.OpenShell.ReportMainProcessExit:input_type -> openshell.v1.ReportMainProcessExitRequest - 150, // 212: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame - 64, // 213: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest - 159, // 214: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest - 161, // 215: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest - 163, // 216: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest - 165, // 217: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest - 168, // 218: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest - 170, // 219: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest - 172, // 220: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest - 174, // 221: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest - 176, // 222: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest - 7, // 223: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest - 9, // 224: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest - 183, // 225: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest - 185, // 226: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest - 187, // 227: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest - 189, // 228: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest - 192, // 229: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest - 194, // 230: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest - 196, // 231: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest - 12, // 232: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse - 14, // 233: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse - 16, // 234: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse - 36, // 235: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse - 36, // 236: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse - 37, // 237: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse - 38, // 238: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse - 39, // 239: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse - 40, // 240: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse - 41, // 241: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse - 36, // 242: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse - 36, // 243: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse - 43, // 244: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse - 51, // 245: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse - 51, // 246: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse - 47, // 247: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse - 49, // 248: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse - 53, // 249: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse - 58, // 250: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent - 60, // 251: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame - 58, // 252: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent - 73, // 253: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse - 73, // 254: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse - 74, // 255: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse - 101, // 256: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse - 100, // 257: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse - 103, // 258: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse - 105, // 259: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse - 107, // 260: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse - 73, // 261: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse - 91, // 262: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse - 93, // 263: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse - 95, // 264: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse - 97, // 265: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse - 108, // 266: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse - 110, // 267: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse - 238, // 268: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse - 239, // 269: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse - 125, // 270: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse - 127, // 271: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse - 129, // 272: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse - 131, // 273: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse - 114, // 274: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse - 116, // 275: openshell.v1.OpenShell.ExchangeProviderSubjectToken:output_type -> openshell.v1.ExchangeProviderSubjectTokenResponse - 136, // 276: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse - 135, // 277: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse - 138, // 278: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage - 145, // 279: openshell.v1.OpenShell.ReportMainProcessExit:output_type -> openshell.v1.ReportMainProcessExitResponse - 150, // 280: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame - 65, // 281: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent - 160, // 282: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse - 162, // 283: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse - 164, // 284: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse - 166, // 285: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse - 169, // 286: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse - 171, // 287: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse - 173, // 288: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse - 175, // 289: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse - 178, // 290: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse - 8, // 291: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse - 10, // 292: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse - 184, // 293: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse - 186, // 294: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse - 188, // 295: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse - 190, // 296: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse - 193, // 297: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse - 195, // 298: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse - 197, // 299: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse - 232, // [232:300] is the sub-list for method output_type - 164, // [164:232] is the sub-list for method input_type - 164, // [164:164] is the sub-list for extension type_name - 164, // [164:164] is the sub-list for extension extendee - 0, // [0:164] is the sub-list for field type_name + 7, // 63: openshell.v1.ProviderCredentialRefreshStatus.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction + 225, // 64: openshell.v1.StoredProviderCredentialRefreshState.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 2, // 65: openshell.v1.StoredProviderCredentialRefreshState.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 210, // 66: openshell.v1.StoredProviderCredentialRefreshState.material:type_name -> openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry + 211, // 67: openshell.v1.StoredProviderCredentialRefreshState.additional_output_keys:type_name -> openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry + 212, // 68: openshell.v1.StoredProviderCredentialRefreshState.secret_material_handles:type_name -> openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry + 90, // 69: openshell.v1.StoredProviderCredentialRefreshState.pending_secret_deletions:type_name -> openshell.v1.StoredRefreshMaterialDeletion + 7, // 70: openshell.v1.StoredProviderCredentialRefreshState.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction + 229, // 71: openshell.v1.StoredRefreshMaterialDeletion.handle:type_name -> openshell.datamodel.v1.CredentialHandle + 87, // 72: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 2, // 73: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 213, // 74: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + 87, // 75: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 87, // 76: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 3, // 77: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory + 83, // 78: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential + 230, // 79: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint + 231, // 80: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary + 88, // 81: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery + 214, // 82: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry + 225, // 83: openshell.v1.StoredProviderProfile.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 99, // 84: openshell.v1.StoredProviderProfile.profile:type_name -> openshell.v1.ProviderProfile + 99, // 85: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile + 99, // 86: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 78, // 87: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 79, // 88: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 99, // 89: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 78, // 90: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem + 79, // 91: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 99, // 92: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile + 78, // 93: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 79, // 94: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 113, // 95: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding + 215, // 96: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + 216, // 97: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expires_at_ms:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry + 217, // 98: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + 218, // 99: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + 226, // 100: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 232, // 101: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue + 119, // 102: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation + 219, // 103: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry + 120, // 104: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule + 121, // 105: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint + 122, // 106: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule + 123, // 107: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules + 124, // 108: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules + 125, // 109: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary + 233, // 110: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 234, // 111: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule + 235, // 112: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule + 220, // 113: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry + 133, // 114: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision + 133, // 115: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision + 4, // 116: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus + 4, // 117: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus + 226, // 118: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 221, // 119: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry + 67, // 120: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine + 67, // 121: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine + 140, // 122: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello + 143, // 123: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat + 152, // 124: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult + 153, // 125: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose + 141, // 126: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted + 142, // 127: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected + 144, // 128: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat + 147, // 129: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen + 153, // 130: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose + 148, // 131: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget + 149, // 132: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget + 150, // 133: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit + 154, // 134: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample + 156, // 135: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount + 233, // 136: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 226, // 137: openshell.v1.PolicyChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 226, // 138: openshell.v1.PolicyChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 155, // 139: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary + 158, // 140: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk + 157, // 141: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary + 158, // 142: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk + 168, // 143: openshell.v1.ApproveAllDraftChunksRequest.approvals:type_name -> openshell.v1.DraftChunkApproval + 233, // 144: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 178, // 145: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry + 226, // 146: openshell.v1.PolicyRevisionPayload.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 222, // 147: openshell.v1.PolicyRevisionPayload.provenance:type_name -> openshell.v1.PolicyRevisionPayload.ProvenanceEntry + 233, // 148: openshell.v1.DraftChunkPayload.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 226, // 149: openshell.v1.DraftChunkPayload.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 226, // 150: openshell.v1.DraftChunkPayload.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 223, // 151: openshell.v1.StoredPolicyRevision.provenance:type_name -> openshell.v1.StoredPolicyRevision.ProvenanceEntry + 226, // 152: openshell.v1.StoredDraftChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 226, // 153: openshell.v1.StoredDraftChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 224, // 154: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry + 236, // 155: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 236, // 156: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 236, // 157: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace + 225, // 158: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 6, // 159: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole + 6, // 160: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole + 192, // 161: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember + 192, // 162: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember + 229, // 163: openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry.value:type_name -> openshell.datamodel.v1.CredentialHandle + 83, // 164: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential + 114, // 165: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding + 12, // 166: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest + 14, // 167: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest + 16, // 168: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest + 28, // 169: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest + 29, // 170: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest + 30, // 171: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest + 31, // 172: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest + 32, // 173: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest + 33, // 174: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest + 34, // 175: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest + 35, // 176: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest + 36, // 177: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest + 43, // 178: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest + 45, // 179: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest + 46, // 180: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest + 47, // 181: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest + 49, // 182: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest + 53, // 183: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest + 55, // 184: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest + 61, // 185: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame + 62, // 186: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput + 69, // 187: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest + 70, // 188: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest + 71, // 189: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest + 76, // 190: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest + 77, // 191: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest + 103, // 192: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest + 105, // 193: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest + 107, // 194: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest + 72, // 195: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest + 91, // 196: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest + 93, // 197: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest + 95, // 198: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest + 97, // 199: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest + 73, // 200: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest + 110, // 201: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest + 237, // 202: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest + 238, // 203: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest + 118, // 204: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest + 127, // 205: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest + 129, // 206: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest + 131, // 207: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest + 112, // 208: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest + 116, // 209: openshell.v1.OpenShell.ExchangeProviderSubjectToken:input_type -> openshell.v1.ExchangeProviderSubjectTokenRequest + 134, // 210: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest + 135, // 211: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest + 138, // 212: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage + 145, // 213: openshell.v1.OpenShell.ReportMainProcessExit:input_type -> openshell.v1.ReportMainProcessExitRequest + 151, // 214: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame + 65, // 215: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest + 160, // 216: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest + 162, // 217: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest + 164, // 218: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest + 166, // 219: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest + 169, // 220: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest + 171, // 221: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest + 173, // 222: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest + 175, // 223: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest + 177, // 224: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest + 8, // 225: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest + 10, // 226: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest + 184, // 227: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest + 186, // 228: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest + 188, // 229: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest + 190, // 230: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest + 193, // 231: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest + 195, // 232: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest + 197, // 233: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest + 13, // 234: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse + 15, // 235: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse + 17, // 236: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse + 37, // 237: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse + 37, // 238: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse + 38, // 239: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse + 39, // 240: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse + 40, // 241: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse + 41, // 242: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse + 42, // 243: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse + 37, // 244: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse + 37, // 245: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse + 44, // 246: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse + 52, // 247: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse + 52, // 248: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse + 48, // 249: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse + 50, // 250: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse + 54, // 251: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse + 59, // 252: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent + 61, // 253: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame + 59, // 254: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent + 74, // 255: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse + 74, // 256: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse + 75, // 257: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse + 102, // 258: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse + 101, // 259: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse + 104, // 260: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse + 106, // 261: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse + 108, // 262: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse + 74, // 263: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse + 92, // 264: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse + 94, // 265: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse + 96, // 266: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse + 98, // 267: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse + 109, // 268: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse + 111, // 269: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse + 239, // 270: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse + 240, // 271: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse + 126, // 272: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse + 128, // 273: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse + 130, // 274: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse + 132, // 275: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse + 115, // 276: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse + 117, // 277: openshell.v1.OpenShell.ExchangeProviderSubjectToken:output_type -> openshell.v1.ExchangeProviderSubjectTokenResponse + 137, // 278: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse + 136, // 279: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse + 139, // 280: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage + 146, // 281: openshell.v1.OpenShell.ReportMainProcessExit:output_type -> openshell.v1.ReportMainProcessExitResponse + 151, // 282: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame + 66, // 283: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent + 161, // 284: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse + 163, // 285: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse + 165, // 286: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse + 167, // 287: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse + 170, // 288: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse + 172, // 289: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse + 174, // 290: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse + 176, // 291: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse + 179, // 292: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse + 9, // 293: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse + 11, // 294: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse + 185, // 295: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse + 187, // 296: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse + 189, // 297: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse + 191, // 298: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse + 194, // 299: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse + 196, // 300: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse + 198, // 301: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse + 234, // [234:302] is the sub-list for method output_type + 166, // [166:234] is the sub-list for method input_type + 166, // [166:166] is the sub-list for extension type_name + 166, // [166:166] is the sub-list for extension extendee + 0, // [0:166] is the sub-list for field type_name } func init() { file_openshell_proto_init() } @@ -15706,7 +15860,7 @@ 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: 7, + NumEnums: 8, NumMessages: 217, NumExtensions: 0, NumServices: 1, diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index e12353bdeb..b0e7ed696c 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -45,10 +45,29 @@ await client.sandbox.delete(sandbox.name) ``` `connect()` constructs a lazy client; call `health()` when startup must verify -gateway reachability. Authentication material is static for the client's -lifetime, so create a new client after refreshing an OIDC or edge token. The -root client has no explicit close method because Connect does not retain a -dedicated session. Close operation-scoped streams and forward handles instead. +gateway reachability. Static `oidcToken` and `edgeToken` values remain fixed for +the client's lifetime. For long-running service automation, use the renewable +client-credentials provider: + +```ts +import { clientCredentials, OpenShellClient } from '@nvidia/openshell-sdk' + +const client = await OpenShellClient.connect({ + gateway, + oidcTokenProvider: clientCredentials({ + issuer: 'https://idp.example.com/realms/openshell', + clientId: 'openshell-service', + clientSecret: () => process.env.OPENSHELL_OIDC_CLIENT_SECRET!, + scopes: ['sandbox:read', 'sandbox:write'], + audience: 'openshell-gateway', + }), +}) +``` + +The provider discovers and validates the issuer, keeps credentials and tokens +in memory, and renews before expiry. The root client has no explicit close +method because Connect does not retain a dedicated session. Close +operation-scoped streams and forward handles instead. Express the create-time safety boundary with `policy`. Sandbox-scoped `setPolicy` cannot introduce static policy fields later, so set filesystem, landlock, diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 6dae221887..61cdce3871 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -3,11 +3,6 @@ // Public API surface for @nvidia/openshell-sdk. // -// OidcRefresher (single-flight OIDC refresh) is intentionally not yet exported. -// It is the one piece of genuinely shared, cross-language behavior; it will be -// added alongside a conformance suite that pins it byte-identical across the -// TypeScript, Python, and Go SDKs. - export type { ConnectOptions, EffectiveSettingView, @@ -42,3 +37,5 @@ export type { export { errorCode, OpenShellClient, SandboxClient } from './client.js'; export type { SdkErrorCode } from './errors.js'; export { SdkError } from './errors.js'; +export type { ClientCredentialsOptions, OidcTokenProvider } from './oidc.js'; +export { clientCredentials } from './oidc.js'; diff --git a/sdk/typescript/src/oidc.test.ts b/sdk/typescript/src/oidc.test.ts new file mode 100644 index 0000000000..88a8ef0af1 --- /dev/null +++ b/sdk/typescript/src/oidc.test.ts @@ -0,0 +1,262 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { clientCredentials } from './oidc.js'; + +const conformance = JSON.parse( + readFileSync(new URL('../../conformance/oauth-client-credentials.json', import.meta.url), 'utf8'), +) as { + request: Record; + urls: { allowed: string[]; rejected: string[] }; + expiry: { leeway_seconds: number; valid_expires_in: number; invalid_expires_in: unknown[] }; + discovery: { + configured_issuer: string; + matching_issuer: string; + mismatched_issuer: string; + redirect_statuses: number[]; + }; + limits: { max_response_bytes: number }; +}; + +const servers: ReturnType[] = []; +afterEach(async () => { + vi.useRealTimers(); + await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(() => resolve())))); +}); + +async function providerServer( + expiresIn: unknown = conformance.expiry.valid_expires_in, +): Promise<{ issuer: string; forms: URLSearchParams[] }> { + const forms: URLSearchParams[] = []; + let issuer = ''; + const server = createServer((req, res) => { + if (req.url === '/.well-known/openid-configuration') { + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ issuer, token_endpoint: `${issuer}/token` })); + return; + } + let body = ''; + req.setEncoding('utf8'); + req.on('data', (chunk) => (body += chunk)); + req.on('end', () => { + forms.push(new URLSearchParams(body)); + res.setHeader('content-type', 'application/json'); + res.end(JSON.stringify({ access_token: `token-${forms.length}`, expires_in: expiresIn })); + }); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('missing address'); + issuer = `http://127.0.0.1:${address.port}`; + return { issuer, forms }; +} + +describe('clientCredentials', () => { + it('accepts and rejects the shared URL vectors', () => { + for (const issuer of conformance.urls.allowed) { + expect(() => clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' })).not.toThrow(); + } + for (const issuer of conformance.urls.rejected) { + expect(() => clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' })).toThrow(); + } + expect(conformance.expiry.leeway_seconds).toBe(30); + }); + + it('sends exact explicit fields without interactive scopes and caches the token', async () => { + const { issuer, forms } = await providerServer(); + const provider = clientCredentials({ + issuer, + clientId: conformance.request.client_id as string, + clientSecret: conformance.request.client_secret as string, + scopes: conformance.request.scopes as string[], + audience: conformance.request.audience as string, + }); + expect(await provider.getToken()).toBe('token-1'); + expect(await provider.getToken()).toBe('token-1'); + expect(forms).toHaveLength(1); + expect(Object.fromEntries(forms[0])).toEqual( + Object.fromEntries( + ['grant_type', 'client_id', 'client_secret', 'scope', 'audience'].map((field) => [ + field, + conformance.request[field], + ]), + ), + ); + }); + + it('coalesces concurrent acquisition', async () => { + const { issuer, forms } = await providerServer(); + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' }); + expect(await Promise.all(Array.from({ length: 12 }, () => provider.getToken()))).toEqual(Array(12).fill('token-1')); + expect(forms).toHaveLength(1); + }); + + it('renews inside the leeway instead of returning a stale token', async () => { + const { issuer, forms } = await providerServer(30); + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' }); + expect(await provider.getToken()).toBe('token-1'); + expect(await provider.getToken()).toBe('token-2'); + expect(forms).toHaveLength(2); + }); + + it.each(conformance.expiry.invalid_expires_in)('rejects invalid expires_in value %j', async (expiresIn) => { + const { issuer } = await providerServer(expiresIn); + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' }); + await expect(provider.getToken()).rejects.toThrow(/positive finite expires_in/); + }); + + it.each(conformance.discovery.redirect_statuses)('refuses discovery redirect status %i', async (status) => { + let issuer = ''; + let redirected = false; + const server = createServer((req, res) => { + if (req.url === '/redirected') redirected = true; + res.writeHead(status, { location: `${issuer}/redirected` }); + res.end(); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('missing address'); + issuer = `http://127.0.0.1:${address.port}`; + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' }); + await expect(provider.getToken()).rejects.toThrow(new RegExp(`HTTP ${status}`)); + expect(redirected).toBe(false); + }); + + it.each(conformance.discovery.redirect_statuses)('refuses token redirect status %i', async (status) => { + let issuer = ''; + let redirected = false; + const server = createServer((req, res) => { + if (req.url === '/.well-known/openid-configuration') { + res.end(JSON.stringify({ issuer, token_endpoint: `${issuer}/token` })); + return; + } + if (req.url === '/redirected') redirected = true; + res.writeHead(status, { location: `${issuer}/redirected` }); + res.end(); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('missing address'); + issuer = `http://127.0.0.1:${address.port}`; + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' }); + await expect(provider.getToken()).rejects.toThrow(new RegExp(`HTTP ${status}`)); + expect(redirected).toBe(false); + }); + + it('rejects a mismatched discovery issuer', async () => { + let issuer = ''; + const server = createServer((_req, res) => { + res.end( + JSON.stringify({ + issuer: conformance.discovery.mismatched_issuer, + token_endpoint: `${issuer}/token`, + }), + ); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('missing address'); + issuer = `http://127.0.0.1:${address.port}`; + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' }); + await expect(provider.getToken()).rejects.toThrow(/issuer mismatch/); + }); + + it('rejects responses larger than the shared bound', async () => { + let issuer = ''; + const server = createServer((req, res) => { + if (req.url === '/.well-known/openid-configuration') { + res.end('x'.repeat(conformance.limits.max_response_bytes + 1)); + return; + } + res.end(JSON.stringify({ issuer, token_endpoint: `${issuer}/token` })); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('missing address'); + issuer = `http://127.0.0.1:${address.port}`; + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' }); + await expect(provider.getToken()).rejects.toThrow(/too large/); + }); + + it('times out while reading a stalled body and retries cleanly', async () => { + let issuer = ''; + let discoveryCalls = 0; + const server = createServer((req, res) => { + if (req.url === '/.well-known/openid-configuration') { + discoveryCalls += 1; + if (discoveryCalls === 1) { + res.writeHead(200, { 'content-type': 'application/json' }); + res.write('{"issuer":'); + return; + } + res.end(JSON.stringify({ issuer, token_endpoint: `${issuer}/token` })); + return; + } + res.end(JSON.stringify({ access_token: 'recovered', expires_in: 120 })); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('missing address'); + issuer = `http://127.0.0.1:${address.port}`; + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret', timeoutMs: 100 }); + + await expect(provider.getToken()).rejects.toThrow(/discovery request timed out/); + await expect(provider.getToken()).resolves.toBe('recovered'); + expect(discoveryCalls).toBe(2); + }); + + it('lets one waiter cancel without canceling the shared exchange', async () => { + let issuer = ''; + let releaseToken!: () => void; + let markStarted!: () => void; + const release = new Promise((resolve) => (releaseToken = resolve)); + const started = new Promise((resolve) => (markStarted = resolve)); + const server = createServer(async (req, res) => { + if (req.url === '/.well-known/openid-configuration') { + res.end(JSON.stringify({ issuer, token_endpoint: `${issuer}/token` })); + return; + } + markStarted(); + await release; + res.end(JSON.stringify({ access_token: 'shared', expires_in: 120 })); + }); + servers.push(server); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('missing address'); + issuer = `http://127.0.0.1:${address.port}`; + const provider = clientCredentials({ issuer, clientId: 'client', clientSecret: 'secret' }); + const controller = new AbortController(); + const canceled = provider.getToken(controller.signal); + await started; + const remaining = provider.getToken(); + controller.abort(); + await expect(canceled).rejects.toThrow(/canceled/); + releaseToken(); + await expect(remaining).resolves.toBe('shared'); + }); + + it('rejects remote plaintext and redacts supplier errors', async () => { + expect(() => clientCredentials({ issuer: 'http://example.com', clientId: 'c', clientSecret: 's' })).toThrow( + /HTTPS/, + ); + const { issuer } = await providerServer(); + const provider = clientCredentials({ + issuer, + clientId: 'client', + clientSecret: () => { + throw new Error('supplier-sensitive-detail'); + }, + }); + await expect(provider.getToken()).rejects.not.toThrow(/supplier-sensitive-detail/); + }); +}); diff --git a/sdk/typescript/src/oidc.ts b/sdk/typescript/src/oidc.ts new file mode 100644 index 0000000000..3a117a26b1 --- /dev/null +++ b/sdk/typescript/src/oidc.ts @@ -0,0 +1,208 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { isIP } from 'node:net'; +import { SdkError } from './errors.js'; + +const EXPIRY_LEEWAY_MS = 30_000; +const MAX_RESPONSE_BYTES = 1 << 20; + +export interface OidcTokenProvider { + getToken(signal?: AbortSignal): Promise; +} + +export interface ClientCredentialsOptions { + issuer: string; + clientId: string; + clientSecret: string | (() => string | Promise); + scopes?: readonly string[]; + audience?: string; + /** Timeout for each complete discovery or token response, including its body. */ + timeoutMs?: number; +} + +interface CachedToken { + accessToken: string; + expiresAt: number; +} + +function isLoopback(hostname: string): boolean { + const host = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname; + if (host.toLowerCase() === 'localhost' || host === '::1') return true; + if (isIP(host) === 4) return host.startsWith('127.'); + return false; +} + +function secureUrl(name: string, raw: string): URL { + let url: URL; + try { + url = new URL(raw); + } catch { + throw new SdkError('invalid_config', `invalid OAuth ${name} URL`); + } + if (url.username || url.password || url.hash) { + throw new SdkError('invalid_config', `OAuth ${name} URL must not contain userinfo or a fragment`); + } + if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLoopback(url.hostname))) { + throw new SdkError('invalid_config', `OAuth ${name} URL must use HTTPS (HTTP is allowed only for loopback hosts)`); + } + return url; +} + +function withoutTrailingSlash(raw: string): string { + return raw.replace(/\/+$/, ''); +} + +async function boundedJson(response: Response, kind: string): Promise> { + if (!response.body) throw new SdkError('auth', `OAuth ${kind} returned an empty response`); + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > MAX_RESPONSE_BYTES) { + await reader.cancel(); + throw new SdkError('auth', `OAuth ${kind} response is too large`); + } + chunks.push(value); + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + try { + const value: unknown = JSON.parse(new TextDecoder().decode(bytes)); + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('not an object'); + return value as Record; + } catch { + throw new SdkError('auth', `OAuth ${kind} returned invalid JSON`); + } +} + +function waitFor(promise: Promise, signal?: AbortSignal): Promise { + if (!signal) return promise; + if (signal.aborted) return Promise.reject(new SdkError('canceled', 'OAuth token request was canceled')); + return new Promise((resolve, reject) => { + const canceled = () => reject(new SdkError('canceled', 'OAuth token request was canceled')); + signal.addEventListener('abort', canceled, { once: true }); + promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', canceled)); + }); +} + +class ClientCredentialsProvider implements OidcTokenProvider { + readonly #options: ClientCredentialsOptions; + readonly #issuer: string; + #tokenEndpoint?: string; + #cached?: CachedToken; + #inFlight?: Promise; + + constructor(options: ClientCredentialsOptions) { + if (!options.clientId) throw new SdkError('invalid_config', 'OAuth clientId is required'); + if (typeof options.clientSecret === 'string' && !options.clientSecret) { + throw new SdkError('invalid_config', 'OAuth clientSecret must not be empty'); + } + this.#issuer = withoutTrailingSlash(secureUrl('issuer', options.issuer).toString()); + this.#options = { ...options, scopes: options.scopes ? [...options.scopes] : undefined }; + } + + async getToken(signal?: AbortSignal): Promise { + if (this.#cached && Date.now() + EXPIRY_LEEWAY_MS < this.#cached.expiresAt) return this.#cached.accessToken; + if (!this.#inFlight) { + this.#inFlight = this.#exchange().finally(() => { + this.#inFlight = undefined; + }); + } + return waitFor(this.#inFlight, signal); + } + + async #secret(): Promise { + try { + const value = + typeof this.#options.clientSecret === 'string' + ? this.#options.clientSecret + : await this.#options.clientSecret(); + if (!value) throw new Error('empty'); + return value; + } catch { + throw new SdkError('auth', 'OAuth client secret supplier failed'); + } + } + + async #requestJson( + url: string, + init: RequestInit, + responseKind: string, + operation: string, + ): Promise> { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), this.#options.timeoutMs ?? 30_000); + try { + const response = await fetch(url, { ...init, redirect: 'manual', signal: controller.signal }); + if (response.status !== 200) { + await response.body?.cancel(); + throw new SdkError('auth', `OAuth ${operation} failed with HTTP ${response.status}`); + } + return await boundedJson(response, responseKind); + } catch (error) { + if (error instanceof SdkError) throw error; + if (controller.signal.aborted) { + throw new SdkError('auth', `OAuth ${operation} request timed out`); + } + throw new SdkError('auth', 'OAuth client credentials request failed'); + } finally { + clearTimeout(timeout); + } + } + + async #exchange(): Promise { + if (!this.#tokenEndpoint) { + const discovery = await this.#requestJson( + `${this.#issuer}/.well-known/openid-configuration`, + { headers: { accept: 'application/json' } }, + 'discovery', + 'discovery', + ); + if (typeof discovery.issuer !== 'string' || withoutTrailingSlash(discovery.issuer) !== this.#issuer) { + throw new SdkError('auth', 'OAuth discovery issuer mismatch'); + } + if (typeof discovery.token_endpoint !== 'string') { + throw new SdkError('auth', 'OAuth discovery document is missing token_endpoint'); + } + this.#tokenEndpoint = secureUrl('token endpoint', discovery.token_endpoint).toString(); + } + + const form = new URLSearchParams({ + grant_type: 'client_credentials', + client_id: this.#options.clientId, + client_secret: await this.#secret(), + }); + if (this.#options.scopes?.length) form.set('scope', this.#options.scopes.join(' ')); + if (this.#options.audience) form.set('audience', this.#options.audience); + const token = await this.#requestJson( + this.#tokenEndpoint, + { + method: 'POST', + headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' }, + body: form, + }, + 'client credentials response', + 'client credentials exchange', + ); + if (typeof token.access_token !== 'string' || !token.access_token) { + throw new SdkError('auth', 'OAuth client credentials response is missing access_token'); + } + if (typeof token.expires_in !== 'number' || !Number.isFinite(token.expires_in) || token.expires_in <= 0) { + throw new SdkError('auth', 'OAuth client credentials response requires a positive finite expires_in'); + } + this.#cached = { accessToken: token.access_token, expiresAt: Date.now() + token.expires_in * 1000 }; + return token.access_token; + } +} + +export function clientCredentials(options: ClientCredentialsOptions): OidcTokenProvider { + return new ClientCredentialsProvider(options); +} diff --git a/sdk/typescript/src/transport.test.ts b/sdk/typescript/src/transport.test.ts index ff4469d893..7961b72516 100644 --- a/sdk/typescript/src/transport.test.ts +++ b/sdk/typescript/src/transport.test.ts @@ -5,9 +5,9 @@ // contract without a live gateway: only PEM bytes are validated, no handshake // is performed. -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { errorCode } from './errors.js'; -import { buildTransport } from './transport.js'; +import { authInterceptor, buildTransport } from './transport.js'; const pem = (label: string) => Buffer.from(`-----BEGIN ${label}-----\ntest\n-----END ${label}-----\n`); @@ -63,6 +63,12 @@ describe('buildTransport token exclusivity', () => { } }); + it('rejects a renewable provider combined with another token', () => { + const oidcTokenProvider = { getToken: async () => 'token' }; + const fn = () => buildTransport({ gateway: 'https://gw.local', oidcToken: 'a', oidcTokenProvider }); + expect(fn).toThrow(/mutually exclusive/); + }); + it('rejects edge tokens that could inject cookies or headers', () => { for (const edgeToken of ['', 'jwt; other=value', 'jwt\r\nx-injected: yes', 'jwt with spaces']) { const fn = () => buildTransport({ gateway: 'https://gw.local', edgeToken }); @@ -82,6 +88,29 @@ describe('buildTransport token exclusivity', () => { }); }); +describe('renewable bearer interceptor', () => { + it('awaits the provider and attaches its current token to every request', async () => { + const signal = new AbortController().signal; + const getToken = vi.fn().mockResolvedValueOnce('token-1').mockResolvedValueOnce('token-2'); + const seen: string[] = []; + const next = vi.fn(async (req: { header: Headers }) => { + seen.push(req.header.get('authorization') ?? ''); + return {} as never; + }); + const invoke = authInterceptor({ + gateway: 'https://gw.local', + oidcTokenProvider: { getToken }, + })(next as never); + + await invoke({ header: new Headers(), signal } as never); + await invoke({ header: new Headers(), signal } as never); + + expect(seen).toEqual(['Bearer token-1', 'Bearer token-2']); + expect(getToken).toHaveBeenNthCalledWith(1, signal); + expect(getToken).toHaveBeenNthCalledWith(2, signal); + }); +}); + describe('buildTransport plaintext auth guard', () => { it('rejects a token over http:// to a non-loopback host', () => { const fn = () => buildTransport({ gateway: 'http://gw.remote:8080', oidcToken: 'a' }); diff --git a/sdk/typescript/src/transport.ts b/sdk/typescript/src/transport.ts index 2d5092b894..7820d2c11b 100644 --- a/sdk/typescript/src/transport.ts +++ b/sdk/typescript/src/transport.ts @@ -13,6 +13,7 @@ import type { Interceptor, Transport } from '@connectrpc/connect'; import { createGrpcTransport } from '@connectrpc/connect-node'; import { SdkError } from './errors.js'; +import type { OidcTokenProvider } from './oidc.js'; export interface ConnectOptions { /** Gateway URL (`http://...` or `https://...`). */ @@ -29,23 +30,29 @@ export interface ConnectOptions { clientKey?: Buffer; /** Bearer token for direct OIDC auth. Mutually exclusive with edgeToken. */ oidcToken?: string; + /** Renewable OIDC bearer provider. Mutually exclusive with oidcToken and edgeToken. */ + oidcTokenProvider?: OidcTokenProvider; /** Cloudflare Access token. See the sidecar note above for CF-fronted gateways. */ edgeToken?: string; /** Disable TLS verification (dev/debug only). */ insecureSkipVerify?: boolean; /** - * Permit sending an auth token (oidcToken/edgeToken) over plaintext `http://` - * to a non-loopback host. Off by default: tokens over cleartext to a remote - * host leak credentials on the wire. Loopback hosts are always allowed. + * Permit sending an auth token (oidcToken/oidcTokenProvider/edgeToken) over + * plaintext `http://` to a non-loopback host. Off by default: tokens over + * cleartext to a remote host leak credentials on the wire. Loopback hosts are + * always allowed. */ allowInsecureAuth?: boolean; } // OIDC bearer takes precedence; otherwise attach the Cloudflare Access header + // cookie. No-op when neither token is set. -function authInterceptor(opts: ConnectOptions): Interceptor { +/** @internal Exported for transport contract tests; not part of the package root API. */ +export function authInterceptor(opts: ConnectOptions): Interceptor { return (next) => async (req) => { - if (opts.oidcToken) { + if (opts.oidcTokenProvider) { + req.header.set('authorization', `Bearer ${await opts.oidcTokenProvider.getToken(req.signal)}`); + } else if (opts.oidcToken) { req.header.set('authorization', `Bearer ${opts.oidcToken}`); } else if (opts.edgeToken) { req.header.set('cf-access-jwt-assertion', opts.edgeToken); @@ -71,8 +78,11 @@ function assertMtlsPair(opts: ConnectOptions): void { // silently prefers OIDC when both are set. Reject that ambiguity up front so a // caller does not think an edge token is in effect when it is being ignored. function assertTokenExclusivity(opts: ConnectOptions): void { - if (opts.oidcToken !== undefined && opts.edgeToken !== undefined) { - throw new SdkError('invalid_config', 'oidcToken and edgeToken are mutually exclusive'); + const configured = [opts.oidcToken, opts.oidcTokenProvider, opts.edgeToken].filter( + (value) => value !== undefined, + ).length; + if (configured > 1) { + throw new SdkError('invalid_config', 'oidcToken, oidcTokenProvider, and edgeToken are mutually exclusive'); } } @@ -96,7 +106,7 @@ function isLoopbackHost(host: string): boolean { // host puts the credential on the wire in the clear. Refuse it unless the caller // explicitly opts in. Loopback (local-dev / edge-sidecar) is always fine. function assertTokenTransportSecurity(opts: ConnectOptions): void { - const hasToken = opts.oidcToken !== undefined || opts.edgeToken !== undefined; + const hasToken = opts.oidcToken !== undefined || opts.oidcTokenProvider !== undefined || opts.edgeToken !== undefined; if (!hasToken || opts.allowInsecureAuth || opts.gateway.startsWith('https://')) return; let host: string; try { diff --git a/tasks/python.toml b/tasks/python.toml index cdd0c8c4c1..9623bb226b 100644 --- a/tasks/python.toml +++ b/tasks/python.toml @@ -4,193 +4,35 @@ # Python development, build, lint, and format tasks ["python:dev"] -description = "Install Python package in development mode (builds CLI binary)" +description = "Install the Python SDK in development mode" depends = ["python:proto"] -run = "uv sync --group dev && uv pip install ." +run = "uv sync --group dev" hide = true ["build:python:wheel"] -description = "Build Python wheel with CLI binary (native)" +description = "Build the pure-Python SDK wheel" depends = ["python:proto"] -run = "uv run maturin build --release" -hide = true - -["python:build"] -description = "Alias for build:python:wheel" -depends = ["build:python:wheel"] -hide = true - -["build:python:wheel:linux"] -description = "Build a Linux Python wheel natively on the current host" -depends = ["python:proto"] -run = ''' +run = """ #!/usr/bin/env bash set -euo pipefail -WHEEL_OUTPUT_DIR=${WHEEL_OUTPUT_DIR:?Set WHEEL_OUTPUT_DIR to a per-platform wheel output directory} -EXPECTED_HOST_ARCH=${EXPECTED_HOST_ARCH:?Set EXPECTED_HOST_ARCH to amd64 or arm64} -ORIGINAL_CARGO_TOML="" - -normalize_arch() { - case "$1" in - x86_64|amd64) echo amd64 ;; - aarch64|arm64) echo arm64 ;; - *) echo "$1" ;; - esac -} - -cleanup() { - if [ -n "$ORIGINAL_CARGO_TOML" ] && [ -f "$ORIGINAL_CARGO_TOML" ]; then - cp "$ORIGINAL_CARGO_TOML" Cargo.toml - rm -f "$ORIGINAL_CARGO_TOML" - fi -} - -trap cleanup EXIT - -if [ "$(uname -s)" != "Linux" ]; then - echo "build:python:wheel:linux requires a Linux host" >&2 - exit 1 -fi - -HOST_ARCH=$(normalize_arch "$(uname -m)") -EXPECTED_HOST_ARCH=$(normalize_arch "$EXPECTED_HOST_ARCH") -if [ "$HOST_ARCH" != "$EXPECTED_HOST_ARCH" ]; then - echo "build:python:wheel:linux expected ${EXPECTED_HOST_ARCH} host, got ${HOST_ARCH}" >&2 - exit 1 -fi - -# Avoid failures when RUSTC_WRAPPER is set to an unresolved `sccache` binary. -if command -v sccache >/dev/null 2>&1; then - export RUSTC_WRAPPER="$(command -v sccache)" -else - unset RUSTC_WRAPPER || true -fi - -if [ -n "${OPENSHELL_CARGO_VERSION:-}" ]; then - ORIGINAL_CARGO_TOML=$(mktemp) - cp Cargo.toml "$ORIGINAL_CARGO_TOML" - sed -i -E '/^\[workspace\.package\]/,/^\[/{s/^version[[:space:]]*=[[:space:]]*".*"/version = "'"${OPENSHELL_CARGO_VERSION}"'"/}' Cargo.toml -fi - +WHEEL_OUTPUT_DIR=${WHEEL_OUTPUT_DIR:-target/wheels} rm -rf "$WHEEL_OUTPUT_DIR" mkdir -p "$WHEEL_OUTPUT_DIR" -uv run maturin build --release --out "$WHEEL_OUTPUT_DIR" - -ls -la "$WHEEL_OUTPUT_DIR"/*.whl -''' -hide = true - -["build:python:wheel:linux:amd64"] -description = "Build Python wheel for Linux amd64 natively" -depends = ["EXPECTED_HOST_ARCH=amd64 WHEEL_OUTPUT_DIR=target/wheels/linux-amd64 build:python:wheel:linux"] -hide = true - -["python:build:linux:amd64"] -description = "Alias for build:python:wheel:linux:amd64" -depends = ["build:python:wheel:linux:amd64"] -hide = true - -["build:python:wheel:linux:arm64"] -description = "Build Python wheel for Linux arm64 natively" -depends = ["EXPECTED_HOST_ARCH=arm64 WHEEL_OUTPUT_DIR=target/wheels/linux-arm64 build:python:wheel:linux"] -hide = true - -["python:build:linux:arm64"] -description = "Alias for build:python:wheel:linux:arm64" -depends = ["build:python:wheel:linux:arm64"] -hide = true +uv build --wheel --out-dir "$WHEEL_OUTPUT_DIR" -["build:python:wheel:macos"] -description = "Build Python wheel for macOS arm64" -depends = ["python:proto"] -run = """ -#!/usr/bin/env bash -set -euo pipefail - -if [ "$(uname -s)" = "Darwin" ] && [ -z "${OPENSHELL_CARGO_VERSION:-}" ]; then - # Avoid failures when RUSTC_WRAPPER is set to an unresolved `sccache` binary. - if command -v sccache >/dev/null 2>&1; then - export RUSTC_WRAPPER="$(command -v sccache)" - else - unset RUSTC_WRAPPER || true - fi - - mkdir -p target/wheels - - rustup target add aarch64-apple-darwin - - uv run maturin build --release --target aarch64-apple-darwin --out target/wheels -else - echo "Building macOS wheel via Docker cross-toolchain" - mise run build:python:wheel:macos:docker -fi - -ls -la target/wheels/*.whl -""" -hide = true - -["python:build:macos"] -description = "Alias for build:python:wheel:macos" -depends = ["build:python:wheel:macos"] -hide = true - -["build:python:wheel:macos:docker"] -description = "Build Python wheel for macOS arm64 from Docker" -depends = ["python:proto"] -run = """ -#!/usr/bin/env bash -set -euo pipefail - -source tasks/scripts/container-engine.sh - -sha256_16() { - if command -v sha256sum >/dev/null 2>&1; then - sha256sum "$1" | awk '{print substr($1, 1, 16)}' - else - shasum -a 256 "$1" | awk '{print substr($1, 1, 16)}' - fi -} - -sha256_16_stdin() { - if command -v sha256sum >/dev/null 2>&1; then - sha256sum | awk '{print substr($1, 1, 16)}' - else - shasum -a 256 | awk '{print substr($1, 1, 16)}' - fi -} - -CARGO_VERSION=${OPENSHELL_CARGO_VERSION:-} -OSXCROSS_IMAGE_REF=${OSXCROSS_IMAGE:-crazymax/osxcross:latest} -if [ -z "$CARGO_VERSION" ] && [ -n "${CI:-}" ]; then - CARGO_VERSION=$(uv run python tasks/scripts/release.py get-version --cargo) +VERIFY_ARGS=() +if [ -n "${SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL:-}" ]; then + VERIFY_ARGS+=(--expected-version "$SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL") fi - -LOCK_HASH=$(sha256_16 Cargo.lock) -RUST_SCOPE=${RUST_TOOLCHAIN_SCOPE:-rustup-1.95.0} -CACHE_SCOPE_INPUT="v1|python-wheels-macos|base|${LOCK_HASH}|${RUST_SCOPE}" -CARGO_TARGET_CACHE_SCOPE=$(printf '%s' "$CACHE_SCOPE_INPUT" | sha256_16_stdin) - -mkdir -p target/wheels - -ce build \ - -f deploy/docker/Dockerfile.python-wheels-macos \ - --target wheels \ - --build-arg "OSXCROSS_IMAGE=${OSXCROSS_IMAGE_REF}" \ - --build-arg "CARGO_TARGET_CACHE_SCOPE=${CARGO_TARGET_CACHE_SCOPE}" \ - ${CARGO_VERSION:+--build-arg "OPENSHELL_CARGO_VERSION=${CARGO_VERSION}"} \ - ${OPENSHELL_IMAGE_TAG:+--build-arg "OPENSHELL_IMAGE_TAG=${OPENSHELL_IMAGE_TAG}"} \ - --output type=local,dest=target/wheels \ - . - -ls -la target/wheels/*macosx*arm64.whl +uv run --no-project python tasks/scripts/verify-python-wheel.py "$WHEEL_OUTPUT_DIR" "${VERIFY_ARGS[@]}" """ hide = true -["python:build:macos:docker"] -description = "Alias for build:python:wheel:macos:docker" -depends = ["build:python:wheel:macos:docker"] +["python:build"] +description = "Alias for build:python:wheel" +depends = ["build:python:wheel"] hide = true ["python:lint"] diff --git a/tasks/scripts/stage-prebuilt-binaries.sh b/tasks/scripts/stage-prebuilt-binaries.sh index b7eb1dad74..757a21298b 100755 --- a/tasks/scripts/stage-prebuilt-binaries.sh +++ b/tasks/scripts/stage-prebuilt-binaries.sh @@ -165,7 +165,8 @@ build_component_for_arch() { local target local stage local features - local cargo_subcommand + local -a cargo_subcommand + local -a cargo_env local build_target local current_host_os local current_host_arch @@ -183,6 +184,7 @@ build_component_for_arch() { current_host_arch="$(host_arch)" cargo_subcommand=(cargo build) + cargo_env=() build_target="$target" build_rustflags="${RUSTFLAGS:-}" @@ -221,6 +223,13 @@ build_component_for_arch() { fi fi + if [[ "${OPENSHELL_AUDITABLE:-0}" == "1" ]]; then + cargo_subcommand=("${cargo_subcommand[0]}" auditable "${cargo_subcommand[@]:1}") + # mise.toml injects RUSTC_WRAPPER=sccache. Unset it after mise constructs + # the environment so it cannot wrap cargo-auditable's workspace wrapper. + cargo_env=(env -u RUSTC_WRAPPER) + fi + echo "Building ${binary} for linux/${arch} (${build_target}, libc: ${target_libc})..." mise x -- rustup target add "$target" >/dev/null 2>&1 || true @@ -245,7 +254,7 @@ build_component_for_arch() { if [[ -n "$build_rustflags" ]]; then export RUSTFLAGS="$build_rustflags" fi - CARGO_INCREMENTAL=0 mise x -- "${cargo_subcommand[@]}" "${args[@]}" + CARGO_INCREMENTAL=0 mise x -- "${cargo_env[@]}" "${cargo_subcommand[@]}" "${args[@]}" ) binary_path="${ROOT}/target/${target}/release/${binary}" @@ -269,6 +278,14 @@ if [[ "$#" -gt 0 ]]; then exit 1 fi +case "${OPENSHELL_AUDITABLE:-0}" in + 0|1) ;; + *) + echo "unsupported OPENSHELL_AUDITABLE: ${OPENSHELL_AUDITABLE} (expected 0 or 1)" >&2 + exit 1 + ;; +esac + restore_cargo_toml=0 trap restore_workspace_version EXIT diff --git a/tasks/scripts/verify-python-wheel.py b/tasks/scripts/verify-python-wheel.py new file mode 100644 index 0000000000..6234c0cdb6 --- /dev/null +++ b/tasks/scripts/verify-python-wheel.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 + +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import argparse +import sys +from configparser import ConfigParser +from configparser import Error as ConfigParserError +from email.parser import Parser +from pathlib import Path +from zipfile import BadZipFile, ZipFile + +PROTO_STEMS = ("datamodel", "inference", "openshell", "options", "sandbox") +BYTECODE_SUFFIXES = (".pyc", ".pyo") +NATIVE_SUFFIXES = (".dll", ".dylib", ".exe", ".pyd", ".so") + + +def _find_wheel(path: Path) -> Path: + if path.is_file(): + return path + + wheels = sorted(path.glob("*.whl")) + if len(wheels) != 1: + raise ValueError(f"expected exactly one wheel in {path}, found {len(wheels)}") + return wheels[0] + + +def _required_files() -> set[str]: + files = { + "openshell/__init__.py", + "openshell/sandbox.py", + "openshell/py.typed", + "openshell/_proto/__init__.py", + } + for stem in PROTO_STEMS: + files.add(f"openshell/_proto/{stem}_pb2.py") + files.add(f"openshell/_proto/{stem}_pb2.pyi") + files.add(f"openshell/_proto/{stem}_pb2_grpc.py") + return files + + +def _single_member(names: set[str], suffix: str) -> str: + matches = [name for name in names if name.endswith(suffix)] + if len(matches) != 1: + raise ValueError(f"expected exactly one {suffix} file, found {len(matches)}") + return matches[0] + + +def verify_wheel(path: Path, expected_version: str | None = None) -> Path: + wheel = _find_wheel(path) + if not wheel.name.endswith("-py3-none-any.whl"): + raise ValueError(f"wheel is not platform-independent: {wheel.name}") + + with ZipFile(wheel) as archive: + names = set(archive.namelist()) + missing = sorted(_required_files() - names) + if missing: + raise ValueError(f"wheel is missing required files: {', '.join(missing)}") + + scripts = sorted( + name + for name in names + if not name.endswith("/") + and Path(name).name in {"openshell", "openshell.exe"} + ) + if scripts: + raise ValueError( + f"wheel contains an openshell executable: {', '.join(scripts)}" + ) + + entry_points = [ + name for name in names if name.endswith(".dist-info/entry_points.txt") + ] + if len(entry_points) > 1: + raise ValueError( + f"expected at most one entry_points.txt file, found {len(entry_points)}" + ) + if entry_points: + parser = ConfigParser(interpolation=None) + try: + parser.read_string(archive.read(entry_points[0]).decode()) + except (ConfigParserError, UnicodeDecodeError) as error: + raise ValueError( + "wheel contains invalid entry point metadata" + ) from error + if parser.has_option("console_scripts", "openshell"): + raise ValueError("wheel defines an openshell console script") + + bytecode_files = sorted( + name for name in names if name.endswith(BYTECODE_SUFFIXES) + ) + if bytecode_files: + raise ValueError( + f"wheel contains Python bytecode: {', '.join(bytecode_files)}" + ) + + native_files = sorted(name for name in names if name.endswith(NATIVE_SUFFIXES)) + if native_files: + raise ValueError(f"wheel contains native files: {', '.join(native_files)}") + + metadata_name = _single_member(names, ".dist-info/METADATA") + metadata = Parser().parsestr(archive.read(metadata_name).decode()) + if metadata["Name"] != "openshell": + raise ValueError(f"unexpected distribution name: {metadata['Name']}") + + version = metadata["Version"] + filename_version = wheel.name.removesuffix("-py3-none-any.whl").removeprefix( + "openshell-" + ) + if version != filename_version: + raise ValueError( + f"wheel filename version {filename_version} does not match metadata {version}" + ) + if expected_version is not None and version != expected_version: + raise ValueError(f"expected version {expected_version}, found {version}") + + wheel_name = _single_member(names, ".dist-info/WHEEL") + wheel_metadata = Parser().parsestr(archive.read(wheel_name).decode()) + if wheel_metadata.get_all("Tag", []) != ["py3-none-any"]: + raise ValueError( + f"unexpected wheel tags: {wheel_metadata.get_all('Tag', [])}" + ) + if wheel_metadata["Root-Is-Purelib"] != "true": + raise ValueError("wheel is not marked as pure Python") + + return wheel + + +def main() -> int: + parser = argparse.ArgumentParser(description="Verify the OpenShell Python wheel") + parser.add_argument( + "path", type=Path, help="Wheel file or directory containing one wheel" + ) + parser.add_argument("--expected-version") + args = parser.parse_args() + + try: + wheel = verify_wheel(args.path, args.expected_version) + except (BadZipFile, OSError, ValueError) as error: + print(f"ERROR: {error}", file=sys.stderr) + return 1 + + print(f"Verified {wheel}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/test.toml b/tasks/test.toml index a796ea67b4..dfb632dda0 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -18,8 +18,8 @@ depends = [ ["test:docs-website"] description = "Test the docs-website sync script" -# --no-project skips the workspace (maturin) build; --with supplies pytest and -# the script's runtime dep (PyYAML), which live outside the project env. +# --no-project skips installing the OpenShell package; --with supplies pytest +# and the script's runtime dependency (PyYAML), which lives outside the project env. run = "uv run --no-project --with pytest --with pyyaml pytest tasks/scripts/sync_docs_website_test.py" ["test:sbom"] @@ -116,6 +116,12 @@ run = [ "CONTAINER_RUNTIME=podman e2e/with-keycloak.sh env OPENSHELL_E2E_OIDC_GATEWAY=1 e2e/with-podman-gateway.sh cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-oidc-pkce --test oidc_pkce", ] +["e2e:provider-refresh-keycloak"] +description = "Run provider refresh recovery e2e against Keycloak and a Podman gateway" +run = [ + "CONTAINER_RUNTIME=podman e2e/with-keycloak.sh e2e/with-podman-gateway.sh cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-provider-refresh-keycloak --test provider_refresh_keycloak -- --nocapture", +] + ["e2e:oidc-pkce:docker"] description = "Run Linux browser PKCE and RBAC e2e tests against Keycloak and a Docker gateway" run = [ diff --git a/uv.lock b/uv.lock index 1e86bc0df2..b12d0c0fcd 100644 --- a/uv.lock +++ b/uv.lock @@ -302,30 +302,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] -[[package]] -name = "maturin" -version = "1.11.5" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a4/84/bfed8cc10e2d8b6656cf0f0ca6609218e6fcb45a62929f5094e1063570f7/maturin-1.11.5.tar.gz", hash = "sha256:7579cf47640fb9595a19fe83a742cbf63203f0343055c349c1cab39045a30c29", size = 226885, upload-time = "2026-01-09T11:06:13.801Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d2/6c/3443d2f8c6d4eae5fc7479cd4053542aff4c1a8566d0019d0612d241b15a/maturin-1.11.5-py3-none-linux_armv6l.whl", hash = "sha256:edd1d4d35050ea2b9ef42aa01e87fe019a1e822940346b35ccb973e0aa8f6d82", size = 8845897, upload-time = "2026-01-09T11:06:17.327Z" }, - { url = "https://files.pythonhosted.org/packages/c5/03/abf1826d8aebc0d47ef6d21bdd752d98d63ac4372ad2b115db9cd5176229/maturin-1.11.5-py3-none-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:2a596eab137cb3e169b97e89a739515abfa7a8755e2e5f0fc91432ef446f74f4", size = 17233855, upload-time = "2026-01-09T11:06:04.272Z" }, - { url = "https://files.pythonhosted.org/packages/90/a1/5ad62913271724035a7e4bcf796d7c95b4119317ae5f8cb034844aa99bc4/maturin-1.11.5-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:1c27a2eb47821edf26c75d100b3150b52dca2c1a5f074d7514af06f7a7acb9d5", size = 8881776, upload-time = "2026-01-09T11:06:10.24Z" }, - { url = "https://files.pythonhosted.org/packages/c6/66/997974b44f8d3de641281ec04fbf5b6ca821bdc8291a2fa73305978db74d/maturin-1.11.5-py3-none-manylinux_2_12_i686.manylinux2010_i686.musllinux_1_1_i686.whl", hash = "sha256:f1320dacddcd3aa84a4bdfc77ee6fdb60e4c3835c853d7eb79c09473628b0498", size = 8870347, upload-time = "2026-01-09T11:06:12.178Z" }, - { url = "https://files.pythonhosted.org/packages/58/e0/c8fa042daf0608cc2e9a59b6df3a9e287bfc7f229136f17727f4118bac2d/maturin-1.11.5-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.musllinux_1_1_x86_64.whl", hash = "sha256:ffe7418834ff3b4a6c987187b7abb85ba033f4733e089d77d84e2de87057b4e7", size = 9291396, upload-time = "2026-01-09T11:06:02.05Z" }, - { url = "https://files.pythonhosted.org/packages/99/af/9d3edc8375efc8d435d5f24794bc4de234d4e743447592da970d53b31361/maturin-1.11.5-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:c739b243d012386902f112ea63a54a94848932b70ae3565fa5e121fd1c0200e0", size = 8827831, upload-time = "2026-01-09T11:06:19.523Z" }, - { url = "https://files.pythonhosted.org/packages/8a/12/cc341f6abbf9005f90935a4ee5dc7b30e2df7d1bb90b96d48b756b2c0ee7/maturin-1.11.5-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.musllinux_1_1_armv7l.whl", hash = "sha256:8127d2cd25950bacbcdc8a2ec6daab1d4d27200f7d73964392680ad64d27f7f0", size = 8718895, upload-time = "2026-01-09T11:06:21.617Z" }, - { url = "https://files.pythonhosted.org/packages/76/17/654a59c66287e287373f2a0086e4fc8a23f0545a81c2bd6e324db26a5801/maturin-1.11.5-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.musllinux_1_1_ppc64le.whl", hash = "sha256:2a4e872fb78e77748217084ffeb59de565d08a86ccefdace054520aaa7b66db4", size = 11384741, upload-time = "2026-01-09T11:06:15.261Z" }, - { url = "https://files.pythonhosted.org/packages/2e/da/7118de648182971d723ea99d79c55007f96cdafc95f5322cc1ad15f6683e/maturin-1.11.5-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2079447967819b5cf615e5b5b99a406d662effdc8d6afd493dcd253c6afc3707", size = 9423814, upload-time = "2026-01-09T11:05:57.242Z" }, - { url = "https://files.pythonhosted.org/packages/cf/8f/be14395c6e23b19ddaa0c171e68915bdcd1ef61ad1f411739c6721196903/maturin-1.11.5-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:50f6c668c1d5d4d4dc1c3ffec7b4270dab493e5b2368f8e4213f4bcde6a50eea", size = 9104378, upload-time = "2026-01-09T11:05:59.835Z" }, - { url = "https://files.pythonhosted.org/packages/77/83/53ea82a2f42a03930ea5545673d11a4ef49bb886827353a701f41a5f11c4/maturin-1.11.5-py3-none-win32.whl", hash = "sha256:49f85ce6cbe478e9743ecddd6da2964afc0ded57013aa4d054256be702d23d40", size = 7738696, upload-time = "2026-01-09T11:06:06.651Z" }, - { url = "https://files.pythonhosted.org/packages/3c/41/353a26d49aa80081c514a6354d429efbecedb90d0153ec598cece3baa607/maturin-1.11.5-py3-none-win_amd64.whl", hash = "sha256:70d3e5beffb9ef9dfae5f3c1a7eeb572091505eb8cb076e9434518df1c42a73b", size = 9029838, upload-time = "2026-01-09T11:05:54.543Z" }, - { url = "https://files.pythonhosted.org/packages/15/67/c94f8f5440bc42d54113a2d99de0d6107f06b5a33f31823e52b2715d856f/maturin-1.11.5-py3-none-win_arm64.whl", hash = "sha256:9348f7f0a346108e0c96e6719be91da4470bd43c15802435e9f4157f5cca43d4", size = 7624029, upload-time = "2026-01-09T11:06:08.728Z" }, -] - [[package]] name = "openshell" -source = { virtual = "." } +source = { editable = "." } dependencies = [ { name = "cloudpickle" }, { name = "grpcio" }, @@ -336,7 +315,6 @@ dependencies = [ [package.dev-dependencies] dev = [ { name = "grpcio-tools" }, - { name = "maturin" }, { name = "pyelftools" }, { name = "pytest" }, { name = "pytest-asyncio" }, @@ -344,7 +322,6 @@ dev = [ { name = "pytest-xdist" }, { name = "pyyaml" }, { name = "ruff" }, - { name = "setuptools-scm" }, { name = "ty" }, { name = "types-pyyaml" }, ] @@ -360,7 +337,6 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ { name = "grpcio-tools", specifier = ">=1.60" }, - { name = "maturin", specifier = ">=1.5,<2.0" }, { name = "pyelftools", specifier = ">=0.30" }, { name = "pytest", specifier = ">=8.0" }, { name = "pytest-asyncio", specifier = ">=0.23" }, @@ -368,7 +344,6 @@ dev = [ { name = "pytest-xdist", specifier = ">=3.0" }, { name = "pyyaml", specifier = "==6.0.2" }, { name = "ruff", specifier = ">=0.4" }, - { name = "setuptools-scm", specifier = ">=8" }, { name = "ty", specifier = ">=0.0.1a6" }, { name = "types-pyyaml", specifier = ">=6.0.12.20260518" }, ] @@ -550,19 +525,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/94/b8/f1f62a5e3c0ad2ff1d189590bfa4c46b4f3b6e49cef6f26c6ee4e575394d/setuptools-80.10.2-py3-none-any.whl", hash = "sha256:95b30ddfb717250edb492926c92b5221f7ef3fbcc2b07579bcd4a27da21d0173", size = 1064234, upload-time = "2026-01-25T22:38:15.216Z" }, ] -[[package]] -name = "setuptools-scm" -version = "9.2.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "packaging" }, - { name = "setuptools" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7b/b1/19587742aad604f1988a8a362e660e8c3ac03adccdb71c96d86526e5eb62/setuptools_scm-9.2.2.tar.gz", hash = "sha256:1c674ab4665686a0887d7e24c03ab25f24201c213e82ea689d2f3e169ef7ef57", size = 203385, upload-time = "2025-10-19T22:08:05.608Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/3d/ea/ac2bf868899d0d2e82ef72d350d97a846110c709bacf2d968431576ca915/setuptools_scm-9.2.2-py3-none-any.whl", hash = "sha256:30e8f84d2ab1ba7cb0e653429b179395d0c33775d54807fc5f1dd6671801aef7", size = 62975, upload-time = "2025-10-19T22:08:04.007Z" }, -] - [[package]] name = "tomli" version = "2.4.1"